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:sx.blah.discord.modules.ModuleLoader.java

/**
 * Manually loads a module./*from  w  ww .j a  v  a2  s.com*/
 *
 * @param module The module to load.
 * @return Whether the module was successfully loaded.
 */
public boolean loadModule(IModule module) {
    if (!loadedModules.contains(module) && !canModuleLoad(module)) {
        return false;
    }
    Class<? extends IModule> clazz = module.getClass();
    if (clazz.isAnnotationPresent(Requires.class)) {
        Requires annotation = clazz.getAnnotation(Requires.class);
        if (!hasDependency(loadedModules, annotation.value())) {
            return false;
        }
    }
    boolean enabled = module.enable(client);
    if (enabled) {
        client.getDispatcher().registerListener(module);
        if (!loadedModules.contains(module))
            loadedModules.add(module);

        client.getDispatcher().dispatch(new ModuleEnabledEvent(module));
    }

    return true;
}

From source file:sx.blah.discord.modules.ModuleLoader.java

/**
 * Manually unloads a module./*from w w w . j  a  va2 s  .co m*/
 *
 * @param module The module to unload.
 */
public void unloadModule(IModule module) {
    loadedModules.remove(module);
    module.disable();
    client.getDispatcher().unregisterListener(module);

    loadedModules.removeIf(mod -> {
        Class<? extends IModule> clazz = module.getClass();
        if (clazz.isAnnotationPresent(Requires.class)) {
            Requires annotation = clazz.getAnnotation(Requires.class);
            if (annotation.value().equals(module.getClass().getName())) {
                unloadModule(mod);
                return true;
            }
        }
        return false;
    });

    client.getDispatcher().dispatch(new ModuleDisabledEvent(module));
}

From source file:org.openspotlight.graph.internal.NodeAndLinkSupport.java

@SuppressWarnings("unchecked")
public static Class<? extends Node> findTargetClass(final Class<?> type) {
    Class<?> currentType = type;
    while (currentType != null) {
        if (!Node.class.isAssignableFrom(currentType)) {
            throw logAndReturn(new IllegalStateException(
                    "No SLNode inherited type found with annotation " + DefineHierarchy.class.getSimpleName()));
        }/*from  ww  w .ja  v a 2 s .c  om*/
        if (currentType.isAnnotationPresent(DefineHierarchy.class)) {
            return (Class<? extends Node>) currentType;
        }
        currentType = currentType.getSuperclass();
    }
    throw logAndReturn(new IllegalStateException(
            "No SLNode inherited type found with annotation " + DefineHierarchy.class.getSimpleName()));
}

From source file:com.arpnetworking.jackson.BuilderDeserializer.java

private static void addTo(final Set<Type> visited, final Map<Class<?>, JsonDeserializer<?>> deserializerMap,
        final Type targetType) {
    if (visited.contains(targetType)) {
        return;/*from w  w  w.  j av a  2 s .  c  om*/
    }
    visited.add(targetType);

    if (targetType instanceof Class<?>) {
        @SuppressWarnings("unchecked")
        final Class<Object> targetClass = (Class<Object>) targetType;
        try {
            // Look-up and register the builder for this class
            final Class<? extends Builder<? extends Object>> builderClass = getBuilderForClass(targetClass);
            deserializerMap.put(targetClass, BuilderDeserializer.of(builderClass));

            LOGGER.info("Registered builder for class; builderClass=" + builderClass + " targetClass="
                    + targetClass);

            // Process all setters on the builder
            for (final Method method : builderClass.getMethods()) {
                if (isSetterMethod(builderClass, method)) {
                    final Type setterArgumentType = method.getGenericParameterTypes()[0];
                    // Recursively register builders for each setter's type
                    addTo(visited, deserializerMap, setterArgumentType);
                }
            }
        } catch (final ClassNotFoundException e) {
            // Log that the class is not build-able
            LOGGER.debug("Ignoring class without builder; targetClass=" + targetClass);
        }

        // Support for JsonSubTypes annotation
        if (targetClass.isAnnotationPresent(JsonSubTypes.class)) {
            final JsonSubTypes.Type[] subTypes = targetClass.getAnnotation(JsonSubTypes.class).value();
            for (final JsonSubTypes.Type subType : subTypes) {
                addTo(visited, deserializerMap, subType.value());
            }
        }

        // Support for JsonTypeInfo annotation
        // TODO(vkoskela): Support JsonTypeInfo classpath scan [MAI-116]
    }

    if (targetType instanceof ParameterizedType) {
        // Recursively register builders for each parameterized type
        final ParameterizedType targetParameterizedType = (ParameterizedType) targetType;
        final Type rawType = targetParameterizedType.getRawType();
        addTo(visited, deserializerMap, rawType);
        for (final Type argumentActualType : targetParameterizedType.getActualTypeArguments()) {
            addTo(visited, deserializerMap, argumentActualType);
        }
    }
}

From source file:org.apache.olingo.ext.proxy.commons.EntityContainerInvocationHandler.java

@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    if (isSelfMethod(method)) {
        return invokeSelfMethod(method, args);
    } else if ("flush".equals(method.getName()) && ArrayUtils.isEmpty(args)) {
        service.getPersistenceManager().flush();
        return ClassUtils.returnVoid();
    } else if ("flushAsync".equals(method.getName()) && ArrayUtils.isEmpty(args)) {
        return service.getPersistenceManager().flushAsync();
    } else if ("operations".equals(method.getName()) && ArrayUtils.isEmpty(args)) {
        final Class<?> returnType = method.getReturnType();

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[] { returnType }, OperationInvocationHandler.getInstance(this));
    } else {/*from   ww  w .jav a2s . c o  m*/
        final Class<?> returnType = method.getReturnType();

        if (returnType.isAnnotationPresent(EntitySet.class)) {
            return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                    new Class<?>[] { returnType }, EntitySetInvocationHandler.getInstance(returnType, service));
        } else if (returnType
                .isAnnotationPresent(org.apache.olingo.ext.proxy.api.annotations.EntityType.class)) {
            return getSingleton(method);
        }

        throw new NoSuchMethodException(method.getName());
    }
}

From source file:org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator.java

protected void checkForIndexes(final MongoPersistentEntity<?> entity) {
    final Class<?> type = entity.getType();
    if (!classesSeen.containsKey(type)) {
        if (log.isDebugEnabled()) {
            log.debug("Analyzing class " + type + " for index information.");
        }/*  w  w  w  .j av  a 2s. co  m*/

        // Make sure indexes get created
        if (type.isAnnotationPresent(CompoundIndexes.class)) {
            CompoundIndexes indexes = type.getAnnotation(CompoundIndexes.class);
            for (CompoundIndex index : indexes.value()) {

                String indexColl = StringUtils.hasText(index.collection()) ? index.collection()
                        : entity.getCollection();
                DBObject definition = (DBObject) JSON.parse(index.def());

                ensureIndex(indexColl, index.name(), definition, index.unique(), index.dropDups(),
                        index.sparse());

                if (log.isDebugEnabled()) {
                    log.debug("Created compound index " + index);
                }
            }
        }

        entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
            public void doWithPersistentProperty(MongoPersistentProperty persistentProperty) {

                Field field = persistentProperty.getField();

                if (field.isAnnotationPresent(Indexed.class)) {

                    Indexed index = field.getAnnotation(Indexed.class);
                    String name = index.name();

                    if (!StringUtils.hasText(name)) {
                        name = persistentProperty.getFieldName();
                    } else {
                        if (!name.equals(field.getName()) && index.unique() && !index.sparse()) {
                            // Names don't match, and sparse is not true. This situation will generate an error on the server.
                            if (log.isWarnEnabled()) {
                                log.warn("The index name " + name + " doesn't match this property name: "
                                        + field.getName()
                                        + ". Setting sparse=true on this index will prevent errors when inserting documents.");
                            }
                        }
                    }

                    String collection = StringUtils.hasText(index.collection()) ? index.collection()
                            : entity.getCollection();
                    int direction = index.direction() == IndexDirection.ASCENDING ? 1 : -1;
                    DBObject definition = new BasicDBObject(persistentProperty.getFieldName(), direction);

                    ensureIndex(collection, name, definition, index.unique(), index.dropDups(), index.sparse());

                    if (log.isDebugEnabled()) {
                        log.debug("Created property index " + index);
                    }

                } else if (field.isAnnotationPresent(GeoSpatialIndexed.class)) {

                    GeoSpatialIndexed index = field.getAnnotation(GeoSpatialIndexed.class);

                    GeospatialIndex indexObject = new GeospatialIndex(persistentProperty.getFieldName());
                    indexObject.withMin(index.min()).withMax(index.max());
                    indexObject.named(StringUtils.hasText(index.name()) ? index.name() : field.getName());

                    String collection = StringUtils.hasText(index.collection()) ? index.collection()
                            : entity.getCollection();
                    mongoDbFactory.getDb().getCollection(collection).ensureIndex(indexObject.getIndexKeys(),
                            indexObject.getIndexOptions());

                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Created %s for entity %s in collection %s! ", indexObject,
                                entity.getType(), collection));
                    }
                }
            }
        });

        classesSeen.put(type, true);
    }
}

From source file:com.impetus.kundera.configure.MetamodelConfiguration.java

/**
 * @param clazz/*from w w w  . ja  v a2 s .c  o  m*/
 */
private List<Class<?>> onValidateClientProperties(List<Class<?>> classes, Class<?> clazz,
        final String persistenceUnit) {
    if (clazz.isAnnotationPresent(Entity.class) && clazz.isAnnotationPresent(Table.class)) {
        classes.add(clazz);
    }
    return classes;
}

From source file:com.impetus.kundera.metadata.processor.TableProcessor.java

/**
 * Add named/native query annotated fields to application meta data.
 * //from  w  ww  .  jav a 2 s.  com
 * @param clazz
 *            entity class.
 */
private void addNamedNativeQueryMetadata(Class clazz) {
    ApplicationMetadata appMetadata = KunderaMetadata.INSTANCE.getApplicationMetadata();
    String name, query = null;
    if (clazz.isAnnotationPresent(NamedQuery.class)) {
        NamedQuery ann = (NamedQuery) clazz.getAnnotation(NamedQuery.class);
        appMetadata.addQueryToCollection(ann.name(), ann.query(), false, clazz);
    }

    if (clazz.isAnnotationPresent(NamedQueries.class)) {
        NamedQueries ann = (NamedQueries) clazz.getAnnotation(NamedQueries.class);

        NamedQuery[] anns = ann.value();
        for (NamedQuery a : anns) {
            appMetadata.addQueryToCollection(a.name(), a.query(), false, clazz);
        }
    }

    if (clazz.isAnnotationPresent(NamedNativeQuery.class)) {
        NamedNativeQuery ann = (NamedNativeQuery) clazz.getAnnotation(NamedNativeQuery.class);
        appMetadata.addQueryToCollection(ann.name(), ann.query(), true, clazz);
    }

    if (clazz.isAnnotationPresent(NamedNativeQueries.class)) {
        NamedNativeQueries ann = (NamedNativeQueries) clazz.getAnnotation(NamedNativeQueries.class);

        NamedNativeQuery[] anns = ann.value();
        for (NamedNativeQuery a : anns) {
            appMetadata.addQueryToCollection(a.name(), a.query(), true, clazz);
        }
    }
}

From source file:com.googlecode.wicketelements.security.AnnotationSecurityCheck.java

public <T extends IRequestableComponent> List<Class<? extends InstantiationSecurityConstraint>> findSecurityConstraintsForInstantiation(
        final Class<T> componentClassParam) {
    Reqs.PARAM_REQ.Object.requireNotNull(componentClassParam,
            "Cannot find security constraints an a null component class!");
    List<Class<? extends InstantiationSecurityConstraint>> list = Collections.emptyList();
    if (componentClassParam.isAnnotationPresent(InstantiateAction.class)) {
        final InstantiateAction annot = componentClassParam.getAnnotation(InstantiateAction.class);
        list = Arrays.asList(annot.constraints());
    }/*from w ww  . j  ava  2  s  . c  o  m*/
    return list;
}

From source file:org.wso2.carbon.identity.common.testng.CarbonBasedTestListener.java

private boolean annotationPresent(Class c, Class clazz) {

    return c.isAnnotationPresent(clazz);
}