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.laxser.blitz.web.ControllerInterceptorAdapter.java

/**
 * true??//from  w ww.j  a  v  a2s. co  m
 * 
 * @param controllerClazz
 * @param actionMethod
 * @return
 */
protected final boolean checkDenyAnnotations(Class<?> controllerClazz, Method actionMethod) {
    List<Class<? extends Annotation>> denyAnnotations = getDenyAnnotationClasses();
    if (denyAnnotations == null || denyAnnotations.size() == 0) {
        return false;
    }
    for (Class<? extends Annotation> denyAnnotation : denyAnnotations) {
        if (denyAnnotation == null) {
            continue;
        }
        BitSet scopeSet = getAnnotationScope(denyAnnotation);
        if (scopeSet.get(AnnotationScope.METHOD.ordinal())) {
            if (actionMethod.isAnnotationPresent(denyAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.CLASS.ordinal())) {
            if (controllerClazz.isAnnotationPresent(denyAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.ANNOTATION.ordinal())) {
            for (Annotation annotation : actionMethod.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(denyAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
                }
            }
            for (Annotation annotation : controllerClazz.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(denyAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
                }
            }
        }
    }
    return false;
}

From source file:de.xaniox.heavyspleef.core.flag.FlagRegistry.java

public void registerFlag(Class<? extends AbstractFlag<?>> clazz, I18NSupplier i18nSupplier, Object cookie) {
    Validate.notNull(clazz, "clazz cannot be null");
    Validate.isTrue(!isFlagPresent(clazz), "Cannot register flag twice: " + clazz.getName());

    if (i18nSupplier == null) {
        i18nSupplier = GLOBAL_SUPPLIER;//  w  ww  .ja v a 2s.c  om
    }

    /* Check if the class provides the required Flag annotation */
    Validate.isTrue(clazz.isAnnotationPresent(Flag.class),
            "Flag-Class must be annotated with the @Flag annotation");

    Flag flagAnnotation = clazz.getAnnotation(Flag.class);
    String name = flagAnnotation.name();

    Validate.isTrue(!name.isEmpty(),
            "name() of annotation of flag for class " + clazz.getCanonicalName() + " cannot be empty");

    /* Generate a path */
    StringBuilder pathBuilder = new StringBuilder();
    Flag parentFlagData = flagAnnotation;

    do {
        pathBuilder.insert(0, parentFlagData.name());

        Class<? extends AbstractFlag<?>> parentFlagClass = parentFlagData.parent();
        parentFlagData = parentFlagClass.getAnnotation(Flag.class);

        if (parentFlagData != null && parentFlagClass != NullFlag.class) {
            pathBuilder.insert(0, FLAG_PATH_SEPERATOR);
        }
    } while (parentFlagData != null);

    String path = pathBuilder.toString();

    /* Check for name collides */
    for (String flagPath : registeredFlagsMap.primaryKeySet()) {
        if (flagPath.equalsIgnoreCase(path)) {
            throw new IllegalArgumentException("Flag " + clazz.getName() + " collides with "
                    + registeredFlagsMap.get(flagPath).flagClass.getName());
        }
    }

    /* Check if the class can be instantiated */
    try {
        Constructor<? extends AbstractFlag<?>> constructor = clazz.getDeclaredConstructor();

        //Make the constructor accessible for future uses
        constructor.setAccessible(true);
    } catch (NoSuchMethodException | SecurityException e) {
        throw new IllegalArgumentException("Flag-Class must provide an empty constructor");
    }

    FlagClassHolder holder = new FlagClassHolder();
    holder.flagClass = clazz;
    holder.supplier = i18nSupplier;
    holder.cookie = cookie;

    Field[] instanceInjectableFields = null;

    if (checkHooks(flagAnnotation)) {
        inject(holder, null, null);
        instanceInjectableFields = getInjectableDeclaredFieldsByFilter(clazz,
                new FieldFilter(FieldFilter.INSTANCE_MODE));

        if (initializationPolicy == InitializationPolicy.COMMIT) {
            Method[] initMethods = getInitMethods(holder);
            for (Method method : initMethods) {
                queuedInitMethods.offer(method);
            }
        } else if (initializationPolicy == InitializationPolicy.REGISTER) {
            runInitMethods(holder);
        }

        if (flagAnnotation.hasCommands()) {
            CommandManager manager = heavySpleef.getCommandManager();
            manager.registerSpleefCommands(clazz);
        }

        holder.staticFieldsInjected = true;
        holder.staticMethodsInitialized = true;
    }

    holder.injectingFields = instanceInjectableFields;
    registeredFlagsMap.put(path, flagAnnotation, holder);

    if (heavySpleef.isGamesLoaded()) {
        for (Game game : heavySpleef.getGameManager().getGames()) {
            for (AbstractFlag<?> flag : game.getFlagManager().getFlags()) {
                if (!(flag instanceof UnloadedFlag)) {
                    continue;
                }

                UnloadedFlag unloaded = (UnloadedFlag) flag;
                if (!unloaded.getFlagName().equals(path)) {
                    continue;
                }

                game.removeFlag(path);

                AbstractFlag<?> newFlag = newFlagInstance(path, AbstractFlag.class, game);
                newFlag.unmarshal(unloaded.getXmlElement());

                game.addFlag(newFlag);
            }
        }
    }
}

From source file:org.apache.metron.stellar.dsl.functions.BasicStellarTest.java

@Test
public void ensureDocumentation() {
    ClassLoader classLoader = getClass().getClassLoader();
    int numFound = 0;
    for (Class<?> clazz : new ClasspathFunctionResolver().resolvables()) {
        if (clazz.isAnnotationPresent(Stellar.class)) {
            numFound++;/*from  w w  w. jav  a2 s .c  om*/
            Stellar annotation = clazz.getAnnotation(Stellar.class);
            Assert.assertFalse("Must specify a name for " + clazz.getName(),
                    StringUtils.isEmpty(annotation.name()));
            Assert.assertFalse("Must specify a description annotation for " + clazz.getName(),
                    StringUtils.isEmpty(annotation.description()));
            Assert.assertFalse("Must specify a returns annotation for " + clazz.getName(),
                    StringUtils.isEmpty(annotation.returns()));
        }
    }
    Assert.assertTrue(numFound > 0);
}

From source file:org.firebrandocm.dao.ClassMetadata.java

/**
 * Constructor./*from   www  . ja va2  s .co  m*/
 * Extracts and caches metadata for persistent entity classes
 *
 * @param target             the target class
 * @param persistenceFactory the persistence factory managing the entity
 */
public ClassMetadata(Class<T> target, AbstractPersistenceFactory persistenceFactory)
        throws ClassNotFoundException, IntrospectionException, InstantiationException, IllegalAccessException {
    log.debug(String.format("Initializing class metadata for %s", target));
    this.target = target;
    //If this is a top level structure that holds a column family
    if (target.isAnnotationPresent(ColumnFamily.class)) {
        ColumnFamily columnFamilyAnnotation = target.getAnnotation(ColumnFamily.class);
        consistencyLevel = columnFamilyAnnotation.consistencyLevel();
        counterColumnFamily = columnFamilyAnnotation.defaultValidationClass() == CounterColumnType.class;
        keySpace = StringUtils.defaultIfEmpty(columnFamilyAnnotation.keySpace(),
                persistenceFactory.getDefaultKeySpace());
        columnFamily = target.getSimpleName();
        initializeColumnFamilyDefinition();
        processFields(target, "");
        processMethods(target);
        addClassTypePropertyIfSupported();
        initializeProxyFactory(persistenceFactory);
        initializeNamedQueries(target);
    } else {
        throw new IllegalArgumentException(target + " is not annotated with " + ColumnFamily.class);
    }
}

From source file:org.auraframework.integration.test.util.WebDriverTestCase.java

/**
 * Checks if the current test is marked with the flapper annotation.
 *//*from w w  w . j  a v a  2 s  .  c o m*/
private boolean isFlapper() {
    Class<?> testClass = getClass();
    if (testClass.isAnnotationPresent(Flapper.class)) {
        return true;
    }
    if (getTestLabels().contains("flapper")) {
        return true;
    }
    try {
        return testClass.getMethod(getName()).isAnnotationPresent(Flapper.class);
    } catch (Throwable t) {
        return false;
    }
}

From source file:com.laxser.blitz.web.ControllerInterceptorAdapter.java

/**
 * false?//from w  w w. j  av  a  2s .  com
 * 
 * @param controllerClazz
 *            
 * @param actionMethod
 *            ?
 * @return
 */
protected final boolean checkRequiredAnnotations(Class<?> controllerClazz, Method actionMethod) {
    List<Class<? extends Annotation>> requiredAnnotations = getRequiredAnnotationClasses();
    if (requiredAnnotations == null || requiredAnnotations.size() == 0) {
        return true;
    }
    for (Class<? extends Annotation> requiredAnnotation : requiredAnnotations) {
        if (requiredAnnotation == null) {
            continue;
        }
        BitSet scopeSet = getAnnotationScope(requiredAnnotation);
        if (scopeSet.get(AnnotationScope.METHOD.ordinal())) {
            if (actionMethod.isAnnotationPresent(requiredAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.CLASS.ordinal())) {
            if (controllerClazz.isAnnotationPresent(requiredAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.ANNOTATION.ordinal())) {
            for (Annotation annotation : actionMethod.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(requiredAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
                }
            }
            for (Annotation annotation : controllerClazz.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(requiredAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
                }
            }
        }
    }
    return false;
}

From source file:de.xaniox.heavyspleef.core.flag.FlagManager.java

public void addFlag(AbstractFlag<?> flag, boolean disable) {
    Class<?> clazz = flag.getClass();
    String path;//from ww w  .  j  a  v a2s.  com

    if (flag instanceof UnloadedFlag) {
        UnloadedFlag unloadedFlag = (UnloadedFlag) flag;
        path = unloadedFlag.getFlagName();

        for (UnloadedFlag unloaded : unloadedFlags) {
            if (unloaded.getFlagName().equals(path)) {
                throw new IllegalStateException("Unloaded flag with name " + path + " already registered");
            }
        }

        if (flags.containsKey(path) || disabledFlags.contains(path)) {
            return;
        }

        unloadedFlags.add(unloadedFlag);
    } else {
        Validate.isTrue(clazz.isAnnotationPresent(Flag.class),
                "Flag class " + clazz.getCanonicalName() + " must annotate " + Flag.class.getCanonicalName());
        Flag flagAnnotation = clazz.getAnnotation(Flag.class);
        path = generatePath(flagAnnotation);

        if (flags.containsKey(path) || disabledFlags.contains(path)) {
            return;
        }

        if (disable) {
            disabledFlags.add(path);
        } else {
            flags.put(path, flag);

            if (clazz.isAnnotationPresent(BukkitListener.class) && !migrateManager) {
                Bukkit.getPluginManager().registerEvents(flag, plugin);
            }

            if (flagAnnotation.hasGameProperties()) {
                Map<GameProperty, Object> flagGamePropertiesMap = new EnumMap<GameProperty, Object>(
                        GameProperty.class);
                flag.defineGameProperties(flagGamePropertiesMap);

                if (!flagGamePropertiesMap.isEmpty()) {
                    GamePropertyBundle properties = new GamePropertyBundle(flag, flagGamePropertiesMap);
                    propertyBundles.add(properties);
                }
            }

            if (flagAnnotation.parent() != NullFlag.class) {
                AbstractFlag<?> parent = getFlag(flagAnnotation.parent());
                flag.setParent(parent);
            }
        }
    }
}

From source file:org.vulpe.model.dao.impl.jpa.AbstractVulpeBaseDAOJPA.java

/**
 * Returns NamedQuery defined in entity// ww  w .  ja  v  a 2s  . c  o m
 */
protected NamedQuery getNamedQuery(final Class<?> entityClass, final String nameQuery) {
    if (entityClass.isAnnotationPresent(NamedQueries.class)) {
        final NamedQueries namedQueries = entityClass.getAnnotation(NamedQueries.class);
        for (NamedQuery namedQuery : namedQueries.value()) {
            if (namedQuery.name().equals(nameQuery)) {
                return namedQuery;
            }
        }
    } else if (entityClass.isAnnotationPresent(NamedQuery.class)) {
        final NamedQuery namedQuery = entityClass.getAnnotation(NamedQuery.class);
        if (namedQuery.name().equals(nameQuery)) {
            return namedQuery;
        }
    }
    return null;
}

From source file:org.firebrandocm.dao.ClassMeta.java

/**
     * Constructor./*from  w  w w  .j a  v a 2s.  c  o m*/
     * Extracts and caches metadata for persistent entity classes
     *
     * @param target             the target class
     * @param persistenceFactory the persistence factory managing the entity
     */
    public ClassMeta(Class<T> target, AbstractPersistenceFactory persistenceFactory)
            throws ClassNotFoundException, IntrospectionException, InstantiationException, IllegalAccessException {
        log.debug(String.format("Initializing class metadata for %s", target));
        this.target = target;
        //If this is a top level structure that holds a column family
        if (target.isAnnotationPresent(ColumnFamily.class)) {
            ColumnFamily columnFamilyAnnotation = target.getAnnotation(ColumnFamily.class);
            consistencyLevel = columnFamilyAnnotation.consistencyLevel();
            counterColumnFamily = columnFamilyAnnotation.defaultValidationClass() == CounterColumnType.class;
            keySpace = StringUtils.defaultIfEmpty(columnFamilyAnnotation.keySpace(),
                    persistenceFactory.getDefaultKeySpace());
            columnFamily = target.getSimpleName();
            initializeColumnFamilyDefinition();
            processFields(target, "");
            processMethods(target);
            addClassTypePropertyIfSupported();
            initializeProxyFactory(persistenceFactory);
            initializeNamedQueries(target);
        } else {
            throw new IllegalArgumentException(target + " is not annotated with " + ColumnFamily.class);
        }
    }

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

private void registerBeanDefinitions(XmlWebApplicationContext context, List<Class<?>> classes) {
    DefaultListableBeanFactory bf = (DefaultListableBeanFactory) context.getBeanFactory();
    String[] definedClasses = new String[bf.getBeanDefinitionCount()];
    String[] definitionNames = bf.getBeanDefinitionNames();
    for (int i = 0; i < definedClasses.length; i++) {
        String name = definitionNames[i];
        definedClasses[i] = bf.getBeanDefinition(name).getBeanClassName();
    }// w w w.j a v  a 2s  .  c  o  m
    for (Class<?> clazz : classes) {
        // ?
        if (!isCandidate(clazz)) {
            continue;
        }

        // bean
        String clazzName = clazz.getName();
        if (ArrayUtils.contains(definedClasses, clazzName)) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Ignores bean definition because it has been exist in context: " + clazz.getName());
            }
            continue;
        }
        //
        String beanName = null;
        if (StringUtils.isEmpty(beanName) && clazz.isAnnotationPresent(Component.class)) {
            beanName = clazz.getAnnotation(Component.class).value();
        }
        if (StringUtils.isEmpty(beanName) && clazz.isAnnotationPresent(Resource.class)) {
            beanName = clazz.getAnnotation(Resource.class).name();
        }
        if (StringUtils.isEmpty(beanName) && clazz.isAnnotationPresent(Service.class)) {
            beanName = clazz.getAnnotation(Service.class).value();
        }
        if (StringUtils.isEmpty(beanName)) {
            beanName = AUTO_BEAN_NAME_PREFIX + clazz.getName();
        }

        bf.registerBeanDefinition(beanName, new AnnotatedGenericBeanDefinition(clazz));
    }
}