Example usage for java.lang Class isAnnotationPresent

List of usage examples for java.lang Class isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang Class isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:com.haulmont.cuba.gui.app.security.role.edit.tabs.EntityPermissionsFrame.java

protected void initCheckBoxesControls() {
    operationControls = new EntityOperationControl[] { new EntityOperationControl(EntityOp.CREATE,
            "createPermissionVariant", "createOpLabel", "createAllowCheck", "createDenyCheck") {
        @Override/*from  w w w  . j  a v  a2s.c o m*/
        public boolean applicableToEntity(Class javaClass) {
            return javaClass.isAnnotationPresent(Entity.class);
        }
    }, new EntityOperationControl(EntityOp.READ, "readPermissionVariant", "readOpLabel", "readAllowCheck",
            "readDenyCheck"),
            new EntityOperationControl(EntityOp.UPDATE, "updatePermissionVariant", "updateOpLabel",
                    "updateAllowCheck", "updateDenyCheck"),
            new EntityOperationControl(EntityOp.DELETE, "deletePermissionVariant", "deleteOpLabel",
                    "deleteAllowCheck", "deleteDenyCheck") {
                @Override
                public boolean applicableToEntity(Class javaClass) {
                    return javaClass.isAnnotationPresent(Entity.class);
                }
            } };

    attachAllCheckBoxListener(allAllowCheck, PermissionVariant.ALLOWED);
    attachAllCheckBoxListener(allDenyCheck, PermissionVariant.DISALLOWED);

    for (EntityOperationControl control : operationControls) {
        // Allow checkbox
        attachCheckBoxListener(control.getAllowChecker(), control.getMetaProperty(), control.getOperation(),
                PermissionVariant.ALLOWED);
        // Deny checkbox
        attachCheckBoxListener(control.getDenyChecker(), control.getMetaProperty(), control.getOperation(),
                PermissionVariant.DISALLOWED);
    }
}

From source file:org.eclipse.scada.configuration.recipe.lib.internal.DefaultExecutableFactory.java

private Executable createCallWrapper(final String name, final Class<?> clazz, final String methodName,
        final Execute execute, final RunnerContext ctx) throws Exception {
    logger.debug("Creating call wrapper for class: {}, method: {}", clazz, methodName);

    final Object o;

    if (clazz.isAnnotationPresent(Singleton.class)) {
        if (!ctx.getSingletons().containsKey(clazz)) {
            ctx.getSingletons().put(clazz, clazz.newInstance());
        }/*from  w ww .  j  a v a2 s.  c o  m*/
        o = ctx.getSingletons().get(clazz);
    } else {
        o = clazz.newInstance();
    }

    final Method m = gatherMethods(clazz, methodName);

    return new Executable() {

        @Override
        public void run(final RunnerContext ctx) {
            try {
                final RunnerContext localContext = makeLocalContext(ctx, execute);
                applyContext(o, localContext);
                final Object[] args = makeArgs(m, localContext);
                m.invoke(o, args);
                captureOutput(o, ctx, execute.getOutput());
            } catch (final Throwable e) {
                logger.info("Method call failed", e);
                throw new RuntimeException(String.format("Failed to call method: %s", methodName), e);
            }
        }
    };
}

From source file:org.gradle.model.internal.manage.schema.extract.StructStrategy.java

public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext,
        final ModelSchemaCache cache) {
    ModelType<R> type = extractionContext.getType();
    Class<? super R> clazz = type.getRawClass();
    if (clazz.isAnnotationPresent(Managed.class)) {
        validateType(type, extractionContext);

        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
        if (!clazz.isInterface()) {
            methods = filterIgnoredMethods(methods);
        }/*from   w w  w. jav  a 2  s .c  om*/
        ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods,
                new Function<Method, String>() {
                    public String apply(Method method) {
                        return method.getName();
                    }
                });

        ensureNoOverloadedMethods(extractionContext, methodsByName);

        List<ModelProperty<?>> properties = Lists.newLinkedList();
        List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length);
        ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering();

        for (String methodName : methodsByName.keySet()) {
            if (methodName.startsWith("get") && !methodName.equals("get")) {
                ImmutableList<Method> getterMethods = methodsByName.get(methodName);

                // The overload check earlier verified that all methods for are equivalent for our purposes
                // So, taking the first one with the most specialized return type is fine.
                Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods);

                boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers());

                if (sampleMethod.getParameterTypes().length != 0) {
                    throw invalidMethod(extractionContext, "getter methods cannot take parameters",
                            sampleMethod);
                }

                Character getterPropertyNameFirstChar = methodName.charAt(3);
                if (!Character.isUpperCase(getterPropertyNameFirstChar)) {
                    throw invalidMethod(extractionContext,
                            "the 4th character of the getter method name must be an uppercase character",
                            sampleMethod);
                }

                ModelType<?> returnType = ModelType.returnType(sampleMethod);

                String propertyNameCapitalized = methodName.substring(3);
                String propertyName = StringUtils.uncapitalize(propertyNameCapitalized);
                String setterName = "set" + propertyNameCapitalized;
                ImmutableList<Method> setterMethods = methodsByName.get(setterName);

                boolean isWritable = !setterMethods.isEmpty();
                if (isWritable) {
                    Method setter = setterMethods.get(0);

                    if (!abstractGetter) {
                        throw invalidMethod(extractionContext,
                                "setters are not allowed for non-abstract getters", setter);
                    }
                    validateSetter(extractionContext, returnType, setter);
                    handled.addAll(setterMethods);
                }

                if (abstractGetter) {
                    ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet
                            .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() {
                                public ModelType<?> apply(Method input) {
                                    return ModelType.of(input.getDeclaringClass());
                                }
                            }));

                    boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() {
                        public boolean apply(Method input) {
                            return input.getAnnotation(Unmanaged.class) != null;
                        }
                    });

                    properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses,
                            unmanaged));
                }
                handled.addAll(getterMethods);
            }
        }

        Iterable<Method> notHandled = Iterables.filter(methodsByName.values(),
                Predicates.not(Predicates.in(handled)));

        // TODO - should call out valid getters without setters
        if (!Iterables.isEmpty(notHandled)) {
            throw invalidMethods(extractionContext, "only paired getter/setter methods are supported",
                    notHandled);
        }

        Class<R> concreteClass = type.getConcreteClass();
        Class<? extends R> implClass = classGenerator.generate(concreteClass);
        final ModelStructSchema<R> schema = ModelSchema.struct(type, properties, implClass);
        extractionContext.addValidator(new Action<ModelSchemaExtractionContext<R>>() {
            @Override
            public void execute(ModelSchemaExtractionContext<R> validatorModelSchemaExtractionContext) {
                ensureCanBeInstantiated(extractionContext, schema);
            }
        });
        Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties,
                new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() {
                    public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) {
                        return toPropertyExtractionContext(extractionContext, property, cache);
                    }
                });

        return new ModelSchemaExtractionResult<R>(schema, propertyDependencies);
    } else {
        return null;
    }
}

From source file:org.ff4j.aop.FeatureAutoProxy.java

private Object[] addAnnotedInterface(Class<?> currentInterface) {
    String currentInterfaceName = currentInterface.getCanonicalName();
    if (!currentInterfaceName.startsWith("java.")) {
        // Avoid process same interface several times
        Boolean isInterfaceFlipped = processedInterface.get(currentInterfaceName);
        if (isInterfaceFlipped != null) {
            if (isInterfaceFlipped) {
                return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
            }/*  www .  j  ava 2 s .  com*/
        } else {
            if (currentInterface.isAnnotationPresent(Flip.class)) {
                // If annotation is registered on Interface class 
                processedInterface.put(currentInterfaceName, true);
                return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
            } else {
                for (Method method : currentInterface.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(Flip.class)) {
                        processedInterface.put(currentInterfaceName, true);
                        return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
                    }
                }
                processedInterface.put(currentInterfaceName, false);
            }
        }
    }
    return null;
}

From source file:org.springframework.data.elasticsearch.core.ElasticsearchTemplate.java

private ElasticsearchPersistentEntity getPersistentEntityFor(Class clazz) {
    Assert.isTrue(clazz.isAnnotationPresent(Document.class), "Unable to identify index name. "
            + clazz.getSimpleName()//w w  w .  jav  a 2  s  .  c o  m
            + " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")");
    return elasticsearchConverter.getMappingContext().getPersistentEntity(clazz);
}

From source file:org.silverpeas.core.test.extention.SilverTestEnv.java

@SuppressWarnings({ "unchecked" })
private <T> void putInTestBeanContainer(final T bean, final Class type, Annotation... qualifiers) {
    Set existing = TestBeanContainer.getMockedBeanContainer().getAllBeansByType(type, qualifiers);
    if (!existing.isEmpty()) {
        if (!type.isAnnotationPresent(Singleton.class)) {
            final HashSet all = new HashSet(existing);
            all.add(bean);//from   w w  w .java2  s  . c  o m
            when(TestBeanContainer.getMockedBeanContainer().getAllBeansByType(type, qualifiers))
                    .thenReturn(all);
            when(TestBeanContainer.getMockedBeanContainer().getBeanByType(type, qualifiers))
                    .thenThrow(new AmbiguousResolutionException("A bean of type " + type + " already exist!"));
        }
    } else {
        when(TestBeanContainer.getMockedBeanContainer().getBeanByType(type, qualifiers)).thenReturn(bean);
        when(TestBeanContainer.getMockedBeanContainer().getAllBeansByType(type, qualifiers))
                .thenReturn(Stream.of(bean).collect(Collectors.toSet()));
    }
}

From source file:com.laxser.blitz.web.impl.module.ModulesBuilderImpl.java

/** ??? */
private ControllerErrorHandler getContextErrorHandler(XmlWebApplicationContext context) {
    ControllerErrorHandler errorHandler = null;
    String[] names = context.getBeanNamesForType(ControllerErrorHandler.class);
    for (int i = 0; errorHandler == null && i < names.length; i++) {
        errorHandler = (ControllerErrorHandler) context.getBean(names[i]);
        Class<?> userClass = ClassUtils.getUserClass(errorHandler);
        if (userClass.isAnnotationPresent(Ignored.class)) {
            logger.debug("Ignored controllerErrorHandler: " + errorHandler);
            errorHandler = null;
            continue;
        }//from   ww  w.  ja  va  2s  .c o m
    }
    return errorHandler;
}

From source file:com.zht.common.rabc.service.impl.RbacPermissionServiceImpl.java

@Override
public void scanPacgeToloadPermis(String packagz) {
    Set<Class<?>> calssSet = PermissionUtil.scanAllController(packagz);
    if (calssSet == null || calssSet.size() == 0) {
        throw new ServiceLogicalException("??");
    }// w  w w  .j  a va  2s.c  o m
    List<RbacPermission> pList = new ArrayList<RbacPermission>();
    for (Class<?> calzz : calssSet) {
        Method[] methods = calzz.getDeclaredMethods();
        String clazzUrl = "";
        if (calzz.isAnnotationPresent(RequestMapping.class)) {
            RequestMapping rm = calzz.getAnnotation(RequestMapping.class);
            String[] clazzUrlArray = rm.value();
            clazzUrl = clazzUrlArray[0];
        }
        if (methods == null || methods.length == 0) {
            continue;
        }
        for (Method method : methods) {
            String url = "";
            if (method.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping mrp = method.getAnnotation(RequestMapping.class);
                String[] methodUrl = mrp.value();
                System.out.println(clazzUrl + methodUrl[0]);//permission--URL
                url = clazzUrl + methodUrl[0];
            }
            if (method.isAnnotationPresent(RequiresPermissions.class)) {
                Annotation rp = method.getAnnotation(RequiresPermissions.class);
                String[] methodRPerms = ((RequiresPermissions) rp).value();//permission--Code
                if (methodRPerms != null && methodRPerms.length > 1) {// pemis
                    for (String str : methodRPerms) {
                        RbacPermission perms = new RbacPermission();
                        perms.setUrl(url);
                        perms.setCode(str);
                        perms.setName("SCAN");
                        perms.setEnabled(true);
                        perms.setType("P");
                        pList.add(perms);
                    }
                } else if (methodRPerms != null && methodRPerms.length == 1) {
                    RbacPermission perms = new RbacPermission();
                    perms.setUrl(url);
                    perms.setCode(methodRPerms[0]);
                    pList.add(perms);
                    perms.setName("SCAN");
                    perms.setEnabled(true);
                    perms.setType("P");
                    pList.add(perms);
                } else if (methodRPerms == null || methodRPerms.length == 0) {
                    RbacPermission perms = new RbacPermission();
                    perms.setUrl(url);
                    perms.setCode("");
                    perms.setName("SCAN");
                    perms.setEnabled(true);
                    perms.setType("P");
                    pList.add(perms);
                    pList.add(perms);
                }
            }

        }
        for (RbacPermission p : pList) {
            $base_save(p);
        }
    }
}

From source file:com.wit.android.support.fragment.BaseFragment.java

/**
 * Gathers all ids presented within ClickableViews annotation. Note, that this is recursive method,
 * which will gather all ids from {@link com.wit.android.support.fragment.annotation.ClickableViews}
 * annotation presented above the given <var>classOfFragment</var>.
 *
 * @param classOfFragment Class of fragment where to check ClickableViews annotation.
 * @param ids             List of already gathered ids.
 * @return List of all gathered clickable view's ids.
 */// w  w w .  ja v  a  2s  .c  om
private List<Integer> gatherClickableViewIds(Class<?> classOfFragment, List<Integer> ids) {
    if (classOfFragment.isAnnotationPresent(ClickableViews.class)) {
        final ClickableViews clickableViews = classOfFragment.getAnnotation(ClickableViews.class);
        if (clickableViews.value().length > 0) {
            ids.addAll(idsToList(clickableViews.value()));
        }
    }
    // Obtain also ids of super class, but only to this BaseFragment super.
    final Class<?> superOfFragment = classOfFragment.getSuperclass();
    if (superOfFragment != null && !superOfFragment.equals(BaseFragment.class)) {
        gatherClickableViewIds(superOfFragment, ids);
    }
    return ids;
}

From source file:com.laxser.blitz.web.impl.module.ModulesBuilderImpl.java

private List<ParamResolver> findContextResolvers(XmlWebApplicationContext context) {
    String[] resolverNames = SpringUtils.getBeanNames(context.getBeanFactory(), ParamResolver.class);
    ArrayList<ParamResolver> resolvers = new ArrayList<ParamResolver>(resolverNames.length);
    for (String beanName : resolverNames) {
        ParamResolver resolver = (ParamResolver) context.getBean(beanName);
        Class<?> userClass = ClassUtils.getUserClass(resolver);
        if (userClass.isAnnotationPresent(Ignored.class)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Ignored context resolver:" + resolver);
            }/*from  w ww . j ava 2s .co m*/
            continue;
        }
        if (userClass.isAnnotationPresent(NotForSubModules.class)
                && context.getBeanFactory().getBeanDefinition(beanName) == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Ignored context resolver (NotForSubModules):" + resolver);
            }
            continue;
        }
        resolvers.add(resolver);
        if (logger.isDebugEnabled()) {
            logger.debug("context resolver[" + resolver.getClass().getName());
        }
    }
    return resolvers;
}