Example usage for java.lang.reflect Modifier isAbstract

List of usage examples for java.lang.reflect Modifier isAbstract

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isAbstract.

Prototype

public static boolean isAbstract(int mod) 

Source Link

Document

Return true if the integer argument includes the abstract modifier, false otherwise.

Usage

From source file:org.jbpm.instance.migration.MigrationUtils.java

private static boolean isConcreteClass(Class type) {
    return !type.isInterface() && !Modifier.isAbstract(type.getModifiers());
}

From source file:org.lightjason.agentspeak.common.CCommon.java

/**
 * get all classes within an Java package as action
 *
 * @param p_package full-qualified package name or empty for default package
 * @return action stream//  w  w  w  . j a  v  a 2  s  . c o  m
 */
@SuppressWarnings("unchecked")
public static Stream<IAction> actionsFromPackage(final String... p_package) {
    return ((p_package == null) || (p_package.length == 0)
            ? Stream.of(MessageFormat.format("{0}.{1}", PACKAGEROOT, "action.buildin"))
            : Arrays.stream(p_package)).flatMap(j -> {
                try {
                    return ClassPath.from(Thread.currentThread().getContextClassLoader())
                            .getTopLevelClassesRecursive(j).parallelStream().map(ClassPath.ClassInfo::load)
                            .filter(i -> !Modifier.isAbstract(i.getModifiers()))
                            .filter(i -> !Modifier.isInterface(i.getModifiers()))
                            .filter(i -> Modifier.isPublic(i.getModifiers()))
                            .filter(IAction.class::isAssignableFrom).map(i -> {
                                try {
                                    return (IAction) i.newInstance();
                                } catch (final IllegalAccessException | InstantiationException l_exception) {
                                    LOGGER.warning(CCommon.languagestring(CCommon.class, "actioninstantiate", i,
                                            l_exception));
                                    return null;
                                }
                            })

                            // action can be instantiate
                            .filter(Objects::nonNull)

                            // check usable action name
                            .filter(CCommon::actionusable);
                } catch (final IOException l_exception) {
                    throw new UncheckedIOException(l_exception);
                }
            });
}

From source file:org.blocks4j.reconf.client.elements.ConfigurationItemElement.java

private static boolean isConcrete(Method method) {
    return !Modifier.isAbstract(method.getModifiers());
}

From source file:com.github.geequery.codegen.ast.JavaUnit.java

/**
 * Equals//www  .  ja  v  a2  s  .  c  o  m
 * @param idfields ?fields
 * @param overwirte ?
 * @param doSuperMethod ?
 * @return
 */
public boolean createEqualsMethod(List<JavaField> idfields, boolean overwirte, String doSuperMethod) {
    JavaMethod equals = new JavaMethod("equals");
    equals.setReturnType(boolean.class);
    equals.addparam(IClassUtil.of(Object.class), "rhs0", Modifier.FINAL);
    if (methods.containsKey(equals.getKey())) {//?
        if (!overwirte) {
            return false;
        }
    }
    equals.addContent("if (rhs0 == null)return false;");
    String simpleName = getSimpleName();
    equals.addContent(simpleName + " rhs=(" + simpleName + ")rhs0;");
    //
    for (int i = 0; i < idfields.size(); i++) {
        JavaField field = idfields.get(i);
        String name = field.getName();
        if (Modifier.isAbstract(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) {
            continue;
        }
        equals.addContent("if(!ObjectUtils.equals(" + name + ", rhs." + name + ")) return false;");
    }
    if (StringUtils.isEmpty(doSuperMethod)) {
        equals.addContent("return true;");
    } else {
        equals.addContent("return super." + doSuperMethod + "(rhs);");
    }
    addMethod(equals);
    addImport(ObjectUtils.class);
    return true;
}

From source file:org.atemsource.atem.impl.pojo.ScannedPojoEntityTypeRepository.java

protected synchronized AbstractEntityType createEntityType(final Class clazz) {
    AbstractEntityType entityType;/*  w w  w .j  a v a  2s.  c o m*/
    entityType = beanCreator.create(entityTypeClass);
    entityType.setEntityClass(clazz);
    entityType.setRepository(this);

    entityType.setAbstractType(clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()));
    entityType.setCode(clazz.getName());
    addEntityTypeToLookup(clazz, entityType);
    return entityType;
}

From source file:org.apache.syncope.client.console.init.ClassPathScanImplementationLookup.java

@SuppressWarnings("unchecked")
public void load() {
    pages = new ArrayList<>();
    previewers = new ArrayList<>();
    extPages = new ArrayList<>();
    extWidgets = new ArrayList<>();
    ssoLoginFormPanels = new ArrayList<>();
    reportletConfs = new HashMap<>();
    accountRuleConfs = new HashMap<>();
    passwordRuleConfs = new HashMap<>();
    pullCorrelationRuleConfs = new HashMap<>();

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);//from w  w  w  .java2 s  .  c  o  m
    scanner.addIncludeFilter(new AssignableTypeFilter(BasePage.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(AbstractBinaryPreviewer.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(BaseExtPage.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(BaseExtWidget.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(SSOLoginFormPanel.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(ReportletConf.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(AccountRuleConf.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(PasswordRuleConf.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(PullCorrelationRuleConf.class));

    scanner.findCandidateComponents(getBasePackage()).forEach(bd -> {
        try {
            Class<?> clazz = ClassUtils.resolveClassName(bd.getBeanClassName(),
                    ClassUtils.getDefaultClassLoader());
            boolean isAbsractClazz = Modifier.isAbstract(clazz.getModifiers());

            if (!isAbsractClazz) {
                if (BaseExtPage.class.isAssignableFrom(clazz)) {
                    if (clazz.isAnnotationPresent(ExtPage.class)) {
                        extPages.add((Class<? extends BaseExtPage>) clazz);
                    } else {
                        LOG.error("Could not find annotation {} in {}, ignoring", ExtPage.class.getName(),
                                clazz.getName());
                    }
                } else if (BaseExtWidget.class.isAssignableFrom(clazz)) {
                    if (clazz.isAnnotationPresent(ExtWidget.class)) {
                        extWidgets.add((Class<? extends BaseExtWidget>) clazz);
                    } else {
                        LOG.error("Could not find annotation {} in {}, ignoring", ExtWidget.class.getName(),
                                clazz.getName());
                    }
                } else if (BasePage.class.isAssignableFrom(clazz)) {
                    pages.add((Class<? extends BasePage>) clazz);
                } else if (AbstractBinaryPreviewer.class.isAssignableFrom(clazz)) {
                    previewers.add((Class<? extends AbstractBinaryPreviewer>) clazz);
                } else if (SSOLoginFormPanel.class.isAssignableFrom(clazz)) {
                    ssoLoginFormPanels.add((Class<? extends SSOLoginFormPanel>) clazz);
                } else if (ReportletConf.class.isAssignableFrom(clazz)) {
                    reportletConfs.put(clazz.getName(), (Class<? extends ReportletConf>) clazz);
                } else if (AccountRuleConf.class.isAssignableFrom(clazz)) {
                    accountRuleConfs.put(clazz.getName(), (Class<? extends AccountRuleConf>) clazz);
                } else if (PasswordRuleConf.class.isAssignableFrom(clazz)) {
                    passwordRuleConfs.put(clazz.getName(), (Class<? extends PasswordRuleConf>) clazz);
                } else if (PullCorrelationRuleConf.class.isAssignableFrom(clazz)) {
                    pullCorrelationRuleConfs.put(clazz.getName(),
                            (Class<? extends PullCorrelationRuleConf>) clazz);
                }
            }
        } catch (Throwable t) {
            LOG.warn("Could not inspect class {}", bd.getBeanClassName(), t);
        }
    });
    pages = Collections.unmodifiableList(pages);
    previewers = Collections.unmodifiableList(previewers);

    Collections.sort(extPages, (o1, o2) -> ObjectUtils.compare(o1.getAnnotation(ExtPage.class).priority(),
            o2.getAnnotation(ExtPage.class).priority()));
    extPages = Collections.unmodifiableList(extPages);

    Collections.sort(extWidgets, (o1, o2) -> ObjectUtils.compare(o1.getAnnotation(ExtWidget.class).priority(),
            o2.getAnnotation(ExtWidget.class).priority()));
    extWidgets = Collections.unmodifiableList(extWidgets);

    ssoLoginFormPanels = Collections.unmodifiableList(ssoLoginFormPanels);

    reportletConfs = Collections.unmodifiableMap(reportletConfs);
    accountRuleConfs = Collections.unmodifiableMap(accountRuleConfs);
    passwordRuleConfs = Collections.unmodifiableMap(passwordRuleConfs);
    pullCorrelationRuleConfs = Collections.unmodifiableMap(pullCorrelationRuleConfs);

    LOG.debug("Binary previewers found: {}", previewers);
    LOG.debug("Extension pages found: {}", extPages);
    LOG.debug("Extension widgets found: {}", extWidgets);
    LOG.debug("SSO Login pages found: {}", ssoLoginFormPanels);
    LOG.debug("Reportlet configurations found: {}", reportletConfs);
    LOG.debug("Account Rule configurations found: {}", accountRuleConfs);
    LOG.debug("Password Rule configurations found: {}", passwordRuleConfs);
    LOG.debug("Pull Correlation Rule configurations found: {}", pullCorrelationRuleConfs);
}

From source file:eu.squadd.testing.objectspopulator.RandomValuePopulator.java

public Object populateAllFields(final Class targetClass, Map exclusions)
        throws IllegalAccessException, InstantiationException {
    final Object target;
    try {//from w  ww . j a  v  a  2s. co m
        if (isMathNumberType(targetClass)) {
            target = getMathNumberType(targetClass);
        } else {
            target = ConstructorUtils.invokeConstructor(targetClass, null);
        }
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
            | InstantiationException ex) {
        System.err.println(ex.getMessage());
        return null;
    }

    //final Object target = targetClass.newInstance();
    //Get all fields present on the target class
    final Set<Field> allFields = getAllFields(targetClass, Predicates.<Field>alwaysTrue());
    if (this.stopOnMxRecusionDepth)
        this.currentRecursionDepth++;

    //Iterate through fields if recursion depth is not reached
    if (!this.stopOnMxRecusionDepth || (this.stopOnMxRecusionDepth
            && this.currentRecursionDepth <= scannerFactory.getRecursionDepth())) {
        for (final Field field : allFields) {
            try {
                // check if the field is not on exclusion list                
                if (exclusions != null && exclusions.containsValue(field.getName()))
                    continue;

                //Set fields to be accessible even when private
                field.setAccessible(true);

                final Class<?> fieldType = field.getType();

                if (fieldType.isEnum() && Enum.class.isAssignableFrom(fieldType)) {
                    //handle any enums here if you have any

                } else if (isMathNumberType(fieldType)) {
                    //System.out.println("*** Math number found, populating it: "+fieldType);                
                    field.set(target, getManufacturedPojo(fieldType));
                } //Check if the field is a collection
                else if (Collection.class.isAssignableFrom(fieldType)) {

                    //Get the generic type class of the collection
                    final Class<?> genericClass = getGenericClass(field);

                    //Check if the generic type of a list is abstract
                    if (Modifier.isAbstract(genericClass.getModifiers())) {

                        System.out.println("Abstract classes are not supported !!!");

                        // this stuff needs real class extending abstract one to work
                        //final List<Object> list = new ArrayList();
                        //list.add(populateAllIn(ClassExtendingAbstract.class));
                        //field.set(target, list);
                    } else {
                        final List<Object> list = new ArrayList();
                        list.add(populateAllFields(genericClass, exclusions));
                        field.set(target, list);
                    }

                } else if ((isSimpleType(fieldType) || isSimplePrimitiveWrapperType(fieldType))
                        && !fieldType.isEnum()) {
                    field.set(target, getManufacturedPojo(fieldType));
                } else if (!fieldType.isEnum()) {
                    field.set(target, populateAllFields(fieldType, exclusions));
                }
            } catch (IllegalAccessException | InstantiationException ex) {
                System.err.println(ex.getMessage());
            }
        }
    }
    return target;
}

From source file:org.apache.openjpa.enhance.ApplicationIdTool.java

/**
 * Constructs a new ApplicationIdTool capable of generating an
 * object id class for <code>type</code>.
 */// w w w  .  ja  va 2  s . c  o  m
public ApplicationIdTool(OpenJPAConfiguration conf, Class type) {
    _log = conf.getLog(OpenJPAConfiguration.LOG_ENHANCE);
    _type = type;

    MetaDataRepository repos = conf.newMetaDataRepositoryInstance();
    repos.setValidate(repos.VALIDATE_NONE);
    repos.setSourceMode(repos.MODE_MAPPING, false);
    loadObjectIds(repos, true);
    _meta = repos.getMetaData(type, null, false);
    if (_meta != null) {
        _abstract = Modifier.isAbstract(_meta.getDescribedType().getModifiers());
        _fields = getDeclaredPrimaryKeyFields(_meta);
    }
}

From source file:org.structr.web.common.TestHelper.java

public static void testViews(final App app, final InputStream specificationSource,
        final Map<String, List<String>> additionalRequiredAttributes) {

    final Map<String, Map<String, List<String>>> viewMap = new LinkedHashMap<>();
    final Map<String, List<String>> requiredAttributes = new LinkedHashMap<>();
    final Map<String, List<String>> baseMap = new LinkedHashMap<>();
    boolean fail = false;

    baseMap.put("ui", Arrays.asList("id", "type", "name", "owner", "createdBy", "hidden", "createdDate",
            "lastModifiedDate", "visibleToPublicUsers", "visibleToAuthenticatedUsers"));
    baseMap.put("_html_", Arrays.asList("_html_data", "_html_is", "_html_properties"));
    baseMap.put("public", Arrays.asList("id", "type"));

    requiredAttributes.put("DynamicResourceAccess", Arrays.asList("signature", "i:flags"));
    requiredAttributes.put("Localization", Arrays.asList("locale"));
    requiredAttributes.put("ResourceAccess", Arrays.asList("signature", "i:flags"));

    // insert required attributes specified by test class
    if (additionalRequiredAttributes != null) {

        for (final Entry<String, List<String>> entry : additionalRequiredAttributes.entrySet()) {

            final String key = entry.getKey();
            final List<String> add = entry.getValue();

            List<String> list = requiredAttributes.get(key);
            if (list != null) {

                list.addAll(add);//from   ww w  .j  a  va2 s.  com

            } else {

                requiredAttributes.put(key, add);
            }
        }
    }

    // load specs
    try (final InputStream is = specificationSource) {

        // build view map from specification
        for (final String line : IOUtils.readLines(is, "utf-8")) {

            if (StringUtils.isNotBlank(line) && line.contains("=") && !line.trim().startsWith("#")) {

                // format is Type.viewName = list of property names
                final String[] parts = line.split("=");
                final String[] keyParts = parts[0].split("\\.");
                final String type = keyParts[0];
                final String viewName = keyParts[1];

                Map<String, List<String>> typeMap = viewMap.get(type);
                if (typeMap == null) {

                    typeMap = new LinkedHashMap<>();
                    viewMap.put(type, typeMap);
                }

                // "empty"views are possible too
                if (parts.length == 2) {

                    final String[] valueParts = parts[1].split(",");
                    final List<String> list = new LinkedList<>(Arrays.asList(valueParts));
                    final List<String> base = baseMap.get(viewName);

                    // common properties
                    if (base != null) {

                        list.addAll(base);
                    }

                    typeMap.put(viewName, list);
                }
            }
        }

    } catch (IOException ioex) {
        throw new AssertionError("Unable to load view specification: " + ioex.getMessage());
    }

    // create test user
    try (final Tx tx = app.tx()) {

        app.create(User.class, new NodeAttribute<>(StructrApp.key(User.class, "name"), "admin"),
                new NodeAttribute<>(StructrApp.key(User.class, "password"), "admin"),
                new NodeAttribute<>(StructrApp.key(User.class, "isAdmin"), true));

        tx.success();

    } catch (FrameworkException fex) {
        fex.printStackTrace();
        throw new AssertionError("Unexpected exception");
    }

    // create an instance of each of the internal types and check the views
    for (final Entry<String, Map<String, List<String>>> entry : viewMap.entrySet()) {

        final String typeName = entry.getKey();
        final Map<String, List<String>> typeMap = entry.getValue();
        final Class type = SchemaHelper.getEntityClassForRawType(typeName);

        if (type != null) {

            // only test node types for now..
            if (!Modifier.isAbstract(type.getModifiers()) && !type.isInterface()
                    && !RelationshipInterface.class.isAssignableFrom(type)) {

                final String body = createPostBody(requiredAttributes.get(typeName));

                // create entity
                final String uuid = StringUtils.substringAfterLast(
                        RestAssured.given().header("X-User", "admin").header("X-Password", "admin")
                                //.filter(RequestLoggingFilter.logRequestTo(System.out))
                                .filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(401))
                                .filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(403))
                                .filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(404))
                                .filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(422))
                                .filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(500)).body(body)
                                .expect().statusCode(201).when().post("/" + typeName).header("Location"),
                        "/");

                for (final Entry<String, List<String>> view : typeMap.entrySet()) {

                    final String viewName = view.getKey();
                    final List<String> keys = view.getValue();

                    // check entity
                    final Map<String, Object> result = RestAssured.given().header("X-User", "admin")
                            .header("X-Password", "admin").expect().statusCode(200).when()
                            .get("/" + typeName + "/" + uuid + "/" + viewName).andReturn().body().as(Map.class);

                    final Map<String, Object> item = (Map<String, Object>) result.get("result");
                    final Set<String> expectedKeys = new TreeSet<>(keys);
                    final Set<String> itemKeySet = item.keySet();

                    expectedKeys.removeAll(itemKeySet);

                    if (!expectedKeys.isEmpty()) {

                        System.out.println(type.getSimpleName() + "." + viewName
                                + " is missing the following keys: " + expectedKeys);
                        fail = true;
                    }

                    expectedKeys.clear();
                    expectedKeys.addAll(keys);

                    itemKeySet.removeAll(expectedKeys);

                    if (!itemKeySet.isEmpty()) {

                        System.out.println(type.getSimpleName() + "." + viewName
                                + " contains keys that are not listed in the specification: " + itemKeySet);
                        fail = true;
                    }
                }
            }
        }
    }

    if (fail) {
        throw new AssertionError(
                "View configuration does not match expected configuration, see log output for details.");
    }
}

From source file:ca.uhn.fhir.rest.method.BaseResourceReturningMethodBinding.java

@SuppressWarnings("unchecked")
public BaseResourceReturningMethodBinding(Class<?> theReturnResourceType, Method theMethod,
        FhirContext theContext, Object theProvider) {
    super(theMethod, theContext, theProvider);

    Class<?> methodReturnType = theMethod.getReturnType();
    if (Collection.class.isAssignableFrom(methodReturnType)) {

        myMethodReturnType = MethodReturnTypeEnum.LIST_OF_RESOURCES;
        Class<?> collectionType = ReflectionUtil.getGenericCollectionTypeOfMethodReturnType(theMethod);
        if (collectionType != null) {
            if (!Object.class.equals(collectionType) && !IBaseResource.class.isAssignableFrom(collectionType)) {
                throw new ConfigurationException(
                        "Method " + theMethod.getDeclaringClass().getSimpleName() + "#" + theMethod.getName()
                                + " returns an invalid collection generic type: " + collectionType);
            }// w  w  w  .j  a v a 2 s  . c o  m
        }
        myResourceListCollectionType = collectionType;

    } else if (IBaseResource.class.isAssignableFrom(methodReturnType)) {
        if (Modifier.isAbstract(methodReturnType.getModifiers()) == false && theContext
                .getResourceDefinition((Class<? extends IBaseResource>) methodReturnType).isBundle()) {
            myMethodReturnType = MethodReturnTypeEnum.BUNDLE_RESOURCE;
        } else {
            myMethodReturnType = MethodReturnTypeEnum.RESOURCE;
        }
    } else if (Bundle.class.isAssignableFrom(methodReturnType)) {
        myMethodReturnType = MethodReturnTypeEnum.BUNDLE;
    } else if (IBundleProvider.class.isAssignableFrom(methodReturnType)) {
        myMethodReturnType = MethodReturnTypeEnum.BUNDLE_PROVIDER;
    } else if (MethodOutcome.class.isAssignableFrom(methodReturnType)) {
        myMethodReturnType = MethodReturnTypeEnum.METHOD_OUTCOME;
    } else {
        throw new ConfigurationException("Invalid return type '" + methodReturnType.getCanonicalName()
                + "' on method '" + theMethod.getName() + "' on type: "
                + theMethod.getDeclaringClass().getCanonicalName());
    }

    if (theReturnResourceType != null) {
        if (IBaseResource.class.isAssignableFrom(theReturnResourceType)) {
            if (Modifier.isAbstract(theReturnResourceType.getModifiers())
                    || Modifier.isInterface(theReturnResourceType.getModifiers())) {
                // If we're returning an abstract type, that's ok
            } else {
                myResourceType = (Class<? extends IResource>) theReturnResourceType;
                myResourceName = theContext.getResourceDefinition(myResourceType).getName();
            }
        }
    }

    myPreferTypesList = createPreferTypesList();
}