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:br.com.caelum.vraptor.ioc.spring.StereotypedBeansRegistrar.java

private void handleRefresh(ApplicationContext beanFactory) {
    String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
    for (String name : beanDefinitionNames) {
        Class<?> beanType = beanFactory.getType(name);
        LOGGER.debug("scanning {} for bean definition {}", beanType, name);
        if (beanType == null) {
            LOGGER.info("null type for bean {}", name);
            continue;
        }/*from  ww w  .  j  a v  a  2s.c om*/

        for (StereotypeHandler handler : stereotypeHandlers) {
            LOGGER.trace("scanning {} with {}", beanType, handler);
            if (beanType.isAnnotationPresent(handler.stereotype())) {
                handler.handle(beanType);
            }
        }
    }
}

From source file:com.terremark.handlers.CloudApiAuthenticationHandler.java

/**
 * Method invoked in the chain. If the request entity class is not annotated with
 * {@link com.terremark.annotations.AuthenticationNotRequired AuthenticationNotRequired} this method will add the
 * {@code x-tmrk-authorization} header.//  w  w  w .  j  a  v  a 2 s .  c o m
 *
 * @param request Client request.
 * @param context Request context.
 * @return Client response.
 * @throws Exception If there is a problem invoking the chain.
 */
@Override
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public final ClientResponse handle(final ClientRequest request, final HandlerContext context) throws Exception {
    final Class<?> responseEntityClass = (Class<?>) request.getAttributes()
            .get(ClientRequestImpl.RESPONSE_ENTITY_CLASS_TYPE);
    if (responseEntityClass == null
            || !responseEntityClass.isAnnotationPresent(AuthenticationNotRequired.class)) {
        request.getHeaders().putSingle(TERREMARK_AUTHORIZATION_HEADER,
                getTerremarkAuthorizationHeaderValue(request));
    }

    return context.doChain(request);
}

From source file:org.powertac.common.state.StateLogging.java

@AfterReturning("newState()")
public void newstate(JoinPoint jp) {
    Object thing = jp.getTarget();
    Class<?> clazz = thing.getClass();
    Object[] args = jp.getArgs();
    Signature sig = jp.getSignature();
    Long id = findId(thing);//from www. j  a va  2 s . c  o m
    if ("readResolve".equals(sig.getName())) {
        args = collectProperties(thing);
        writeLog(clazz.getName(), id, "-rr", args);
    } else if (clazz.isAnnotationPresent(Domain.class)) {
        // Runtime check annotation to prevent logging subclasses of @Domain
        writeLog(clazz.getName(), id, "new", args);
    }
}

From source file:org.vaadin.spring.stuff.sidebar.SideBarUtils.java

private void scanForItems() {
    logger.debug("Scanning for side bar items");
    String[] beanNames = applicationContext.getBeanNamesForAnnotation(SideBarItem.class);
    for (String beanName : beanNames) {
        logger.debug("Bean [{}] declares a side bar item", beanName);
        Class<?> beanType = applicationContext.getType(beanName);
        if (Runnable.class.isAssignableFrom(beanType)) {
            logger.debug("Adding side bar item for action [{}]", beanType);
            this.items.add(new SideBarItemDescriptor.ActionItemDescriptor(beanName, applicationContext));
        } else if (View.class.isAssignableFrom(beanType) && beanType.isAnnotationPresent(VaadinView.class)) {
            logger.debug("Adding side bar item for view [{}]", beanType);
            this.items.add(new SideBarItemDescriptor.ViewItemDescriptor(beanName, applicationContext));
        }/*from ww w .  j av a 2 s. c  om*/
    }
}

From source file:org.vaadin.spring.sidebar.SideBarUtils.java

private void scanForItems() {
    logger.debug("Scanning for side bar items");
    String[] beanNames = applicationContext.getBeanNamesForAnnotation(SideBarItem.class);
    for (String beanName : beanNames) {
        logger.debug("Bean [{}] declares a side bar item", beanName);
        Class<?> beanType = applicationContext.getType(beanName);
        if (Runnable.class.isAssignableFrom(beanType)) {
            logger.debug("Adding side bar item for action [{}]", beanType);
            this.items.add(new SideBarItemDescriptor.ActionItemDescriptor(beanName, applicationContext));
        } else if (View.class.isAssignableFrom(beanType) && beanType.isAnnotationPresent(SpringView.class)) {
            logger.debug("Adding side bar item for view [{}]", beanType);
            this.items.add(new SideBarItemDescriptor.ViewItemDescriptor(beanName, applicationContext));
        }/*www  . ja v  a  2 s.c om*/
    }
}

From source file:com.github.kongchen.swagger.docgen.mavenplugin.SpringMavenDocumentSource.java

@Override
public void loadDocuments() throws GenerateException {
    Map<String, SpringResource> resourceMap = new HashMap<String, SpringResource>();
    SwaggerConfig swaggerConfig = new SwaggerConfig();
    swaggerConfig.setApiVersion(apiSource.getApiVersion());
    swaggerConfig.setSwaggerVersion(SwaggerSpec.version());
    List<ApiListingReference> apiListingReferences = new ArrayList<ApiListingReference>();
    List<AuthorizationType> authorizationTypes = new ArrayList<AuthorizationType>();

    //relate all methods to one base request mapping if multiple controllers exist for that mapping
    //get all methods from each controller & find their request mapping
    //create map - resource string (after first slash) as key, new SpringResource as value
    for (Class<?> c : apiSource.getValidClasses()) {
        RequestMapping requestMapping = (RequestMapping) c.getAnnotation(RequestMapping.class);
        String description = "";
        if (c.isAnnotationPresent(Api.class)) {
            description = ((Api) c.getAnnotation(Api.class)).value();
        }/*from w  w  w .  jav a2s  .  co m*/
        if (requestMapping != null && requestMapping.value().length != 0) {
            //This try/catch block is to stop a bamboo build from failing due to NoClassDefFoundError
            //This occurs when a class or method loaded by reflections contains a type that has no dependency
            try {
                resourceMap = analyzeController(c, resourceMap, description);
                List<Method> mList = new ArrayList<Method>(Arrays.asList(c.getMethods()));
                if (c.getSuperclass() != null) {
                    mList.addAll(Arrays.asList(c.getSuperclass().getMethods()));
                }
                for (Method m : mList) {
                    if (m.isAnnotationPresent(RequestMapping.class)) {
                        RequestMapping methodReq = m.getAnnotation(RequestMapping.class);
                        //isolate resource name - attempt first by the first part of the mapping
                        if (methodReq != null && methodReq.value().length != 0) {
                            for (int i = 0; i < methodReq.value().length; i++) {
                                String resourceKey = "";
                                String resourceName = Utils.parseResourceName(methodReq.value()[i]);
                                if (!(resourceName.equals(""))) {
                                    String version = Utils.parseVersion(requestMapping.value()[0]);
                                    //get version - first try by class mapping, then method
                                    if (version.equals("")) {
                                        //class mapping failed - use method
                                        version = Utils.parseVersion(methodReq.value()[i]);
                                    }
                                    resourceKey = Utils.createResourceKey(resourceName, version);
                                    if ((!(resourceMap.containsKey(resourceKey)))) {
                                        resourceMap.put(resourceKey,
                                                new SpringResource(c, resourceName, resourceKey, description));
                                    }
                                    resourceMap.get(resourceKey).addMethod(m);
                                }
                            }
                        }
                    }
                }
            } catch (NoClassDefFoundError e) {
                LOG.error(e.getMessage());
                LOG.info(c.getName());
                //exception occurs when a method type or annotation is not recognized by the plugin
            } catch (ClassNotFoundException e) {
                LOG.error(e.getMessage());
                LOG.info(c.getName());
            }

        }
    }
    for (String str : resourceMap.keySet()) {
        ApiListing doc = null;
        SpringResource resource = resourceMap.get(str);

        try {
            doc = getDocFromSpringResource(resource, swaggerConfig);
            setBasePath(doc.basePath());
        } catch (Exception e) {
            LOG.error("DOC NOT GENERATED FOR: " + resource.getResourceName());
            e.printStackTrace();
        }
        if (doc == null)
            continue;
        ApiListingReference apiListingReference = new ApiListingReference(doc.resourcePath(), doc.description(),
                doc.position());
        apiListingReferences.add(apiListingReference);
        acceptDocument(doc);

    }
    // sort apiListingRefernce by position
    Collections.sort(apiListingReferences, new Comparator<ApiListingReference>() {
        @Override
        public int compare(ApiListingReference o1, ApiListingReference o2) {
            if (o1 == null && o2 == null)
                return 0;
            if (o1 == null && o2 != null)
                return -1;
            if (o1 != null && o2 == null)
                return 1;
            return o1.position() - o2.position();
        }
    });
    serviceDocument = new ResourceListing(swaggerConfig.apiVersion(), swaggerConfig.swaggerVersion(),
            scala.collection.immutable.List
                    .fromIterator(JavaConversions.asScalaIterator(apiListingReferences.iterator())),
            scala.collection.immutable.List.fromIterator(
                    JavaConversions.asScalaIterator(authorizationTypes.iterator())),
            swaggerConfig.info());
}

From source file:net.ymate.platform.plugin.impl.DefaultPluginFactory.java

@SuppressWarnings("unchecked")
private List<Class<? extends IBeanHandler>> __doLoadBeanHandles() throws Exception {
    List<Class<? extends IBeanHandler>> _returnValues = new ArrayList<Class<? extends IBeanHandler>>();
    IBeanLoader _loader = new DefaultBeanLoader();
    ////from  ww w  .j  a v  a 2  s.co  m
    IBeanFilter _beanFilter = new IBeanFilter() {
        public boolean filter(Class<?> targetClass) {
            return !(targetClass.isInterface() || targetClass.isAnnotation() || targetClass.isEnum())
                    && (targetClass.isAnnotationPresent(Handler.class)
                            && ClassUtils.isInterfaceOf(targetClass, IBeanHandler.class));
        }
    };
    //
    for (String _package : __config.getAutoscanPackages()) {
        for (Class<?> _targetClass : _loader.load(_package, _beanFilter)) {
            _returnValues.add((Class<? extends IBeanHandler>) _targetClass);
        }
    }
    return _returnValues;
}

From source file:org.springframework.data.document.mongodb.mapping.MongoPersistentEntityIndexCreator.java

protected void checkForIndexes(final MongoPersistentEntity<?> entity) {
    final Class<?> type = entity.getType();
    if (!classesSeen.contains(type)) {
        if (log.isDebugEnabled()) {
            log.debug("Analyzing class " + type + " for index information.");
        }/*w  w  w . ja va  2  s . 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 = index.collection();
                if ("".equals(indexColl)) {
                    indexColl = entity.getCollection();
                }
                ensureIndex(indexColl, index.name(), index.def(), index.direction(), index.unique(),
                        index.dropDups(), index.sparse());
                if (log.isDebugEnabled()) {
                    log.debug("Created compound index " + index);
                }
            }
        }

        entity.doWithProperties(new PropertyHandler() {
            public void doWithPersistentProperty(PersistentProperty persistentProperty) {
                Field field = persistentProperty.getField();
                if (field.isAnnotationPresent(Indexed.class)) {
                    Indexed index = field.getAnnotation(Indexed.class);
                    String name = index.name();
                    if ("".equals(name)) {
                        name = field.getName();
                    } 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();
                    ensureIndex(collection, name, null, index.direction(), 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(
                            StringUtils.hasText(index.name()) ? index.name() : field.getName());
                    indexObject.withMin(index.min()).withMax(index.max());

                    String collection = StringUtils.hasText(index.collection()) ? index.collection()
                            : entity.getCollection();
                    mongoTemplate.ensureIndex(collection, indexObject);

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

        classesSeen.add(type);
    }

}

From source file:org.broadinstitute.gatk.tools.walkers.help.WalkerDocumentationHandler.java

/**
 * Utility function that finds the values of ReadFilters annotation applied to an instance of class c.
 *
 * @param myClass the class to query for the annotation
 * @param bucket a container in which we store the annotations collected
 * @return a hash set of values, otherwise an empty set
 *///from   w  w  w.j ava  2 s .  c o  m
private HashSet<HashMap<String, Object>> getReadFilters(Class myClass,
        HashSet<HashMap<String, Object>> bucket) {
    //
    // Retrieve annotation
    if (myClass.isAnnotationPresent(ReadFilters.class)) {
        final Annotation thisAnnotation = myClass.getAnnotation(ReadFilters.class);
        if (thisAnnotation instanceof ReadFilters) {
            final ReadFilters rfAnnotation = (ReadFilters) thisAnnotation;
            for (Class<?> filter : rfAnnotation.value()) {
                // make hashmap of simplename and url
                final HashMap<String, Object> nugget = new HashMap<String, Object>();
                nugget.put("name", filter.getSimpleName());
                nugget.put("filename", GATKDocUtils.phpFilenameForClass(filter));
                bucket.add(nugget);
            }
        }
    }
    // Look up superclasses recursively
    final Class mySuperClass = myClass.getSuperclass();
    if (mySuperClass.getSimpleName().equals("Object")) {
        return bucket;
    }
    return getReadFilters(mySuperClass, bucket);
}

From source file:com.github.gekoh.yagen.hst.CreateEntities.java

public void processBaseEntityClasses(String baseClassPackageName, Collection<Class> baseEntities) {
    Map<Class, List<AccessibleObject>> inverseFKs = getInverseFKs(baseEntities);

    for (Class baseEntity : baseEntities) {
        Class tableEntity = getTableEntityClass(baseEntity);
        if (baseEntity.isAnnotationPresent(MappedSuperclass.class)
                || (tableEntity != null && tableEntity.isAnnotationPresent(TemporalEntity.class))) {

            String className = createHistoryEntity(baseClassPackageName, baseEntity, new StringReader(template),
                    inverseFKs.get(baseEntity));

            if (baseEntity.isAnnotationPresent(MappedSuperclass.class)) {
                createdMappedSuperClasses.add(className);
            } else {
                createdEntityClasses.add(className);
            }//from w ww  .j  a  v a 2  s  .  c om
        }

        for (AccessibleObject accessibleObject : getFieldsAndMethods(baseEntity)) {
            if (accessibleObject.isAnnotationPresent(TemporalEntity.class)
                    && accessibleObject.isAnnotationPresent(JoinTable.class)) {
                String className = createHistoryEntity(baseClassPackageName, accessibleObject,
                        new StringReader(template));
                createdEntityClasses.add(className);
            }
        }
    }
}