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:org.jiemamy.entity.io.meta.impl.EntityMetaReaderImpl.java

public List<EntityMeta> read() throws IOException, EntityClassNotFoundException {
    final EntityMetaFactory factory = entityMetaReaderContext.getEntityMetaFactory();
    try {//from w  ww  . j a va 2  s.  com
        final List<EntityMeta> entityMetas = CollectionsUtil.newArrayList();
        final String entityFullPackageName = entityMetaReaderContext.getPackageName();
        final ClassLoader classLoader = createClassLoader();
        for (File classPathDir : entityMetaReaderContext.getClassPathDirs()) {

            try {
                ClassTraversal.forEach(classPathDir, new ClassHandler() {

                    public void processClass(String packageName, String shortClassName)
                            throws TraversalHandlerException {
                        if (packageName.equals(entityFullPackageName) == false) {
                            return;
                        }
                        if (isIgnoreShortClassName(shortClassName)) {
                            return;
                        }
                        if (isShortClassName(shortClassName) == false) {
                            return;
                        }
                        try {
                            String entityClassName = ClassUtil.concatName(packageName, shortClassName);
                            Class<?> entityClass = ClassLoaderUtil.loadClass(classLoader, entityClassName);
                            if (entityClass.isAnnotationPresent(Entity.class)) {
                                EntityMeta entityMeta = factory.getEntityMeta(entityClass);
                                LOG.debug(LogMarker.DETAIL, entityClassName);
                                entityMetas.add(entityMeta);
                            }
                        } catch (ClassNotFoundException e) {
                            throw new TraversalHandlerException(e);
                        } catch (NonEntityException e) {
                            throw new TraversalHandlerException(e);
                        }
                    }
                });
            } catch (TraversalHandlerException e) {
                throw new IOException();
            }
        }
        if (entityMetas.isEmpty()) {
            throw new EntityClassNotFoundException();
        }
        if (entityMetaReaderContext.isReadComment()) {
            readComment(entityMetas);
        }
        return entityMetas;
    } finally {
        factory.dispose();
    }
}

From source file:com.impetus.kundera.metadata.validator.EntityValidatorImpl.java

/**
 * Checks the validity of a class for Cassandra entity.
 * /*from   w  w  w  .  ja  v  a  2  s  .  c  om*/
 * @param clazz
 *            validates this class
 * 
 * @return returns 'true' if valid
 */
@Override
// TODO: reduce Cyclomatic complexity
public final void validate(final Class<?> clazz) {

    if (classes.contains(clazz)) {
        return;
    }

    log.debug("Validating " + clazz.getName());

    // Is Entity?
    if (!clazz.isAnnotationPresent(Entity.class)) {
        throw new InvalidEntityDefinitionException(clazz.getName() + " is not annotated with @Entity");
    }

    // must have a default no-argument constructor
    try {
        clazz.getConstructor();
    } catch (NoSuchMethodException nsme) {
        throw new InvalidEntityDefinitionException(
                clazz.getName() + " must have a default no-argument constructor.");
    }

    // Must be annotated with @Table
    if (!clazz.isAnnotationPresent(Table.class)) {
        throw new InvalidEntityDefinitionException(clazz.getName() + " must be annotated with @Table");
    }

    // Check for @Key and ensure that there is just 1 @Key field of String
    // type.
    List<Field> keys = new ArrayList<Field>();
    for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(Id.class)) {
            keys.add(field);
        }
    }

    if (keys.size() == 0) {
        throw new InvalidEntityDefinitionException(clazz.getName() + " must have an @Id field.");
    } else if (keys.size() > 1) {
        throw new InvalidEntityDefinitionException(clazz.getName() + " can only have 1 @Id field.");
    }

    // if (!keys.get(0).getType().equals(String.class))
    // {
    // throw new PersistenceException(clazz.getName() +
    // " @Id must be of String type.");
    // }

    // save in cache

    classes.add(clazz);
}

From source file:org.glassfish.jersey.server.spring.SpringComponentProvider.java

@Override
public boolean bind(Class<?> component, Set<Class<?>> providerContracts) {

    if (ctx == null) {
        return false;
    }/*  www  .  j  a v  a 2s. c o m*/

    if (component.isAnnotationPresent(Component.class)) {
        DynamicConfiguration c = Injections.getConfiguration(locator);
        String[] beanNames = ctx.getBeanNamesForType(component);
        if (beanNames == null || beanNames.length != 1) {
            LOGGER.severe(LocalizationMessages.NONE_OR_MULTIPLE_BEANS_AVAILABLE(component));
            return false;
        }
        String beanName = beanNames[0];

        ServiceBindingBuilder bb = Injections
                .newFactoryBinder(new SpringComponentProvider.SpringManagedBeanFactory(ctx, locator, beanName));
        bb.to(component);
        Injections.addBinding(bb, c);
        c.commit();

        LOGGER.config(LocalizationMessages.BEAN_REGISTERED(beanName));
        return true;
    }
    return false;
}

From source file:org.alfresco.rad.test.AlfrescoTestRunner.java

/**
 * Check the @Remote config on the test class to see where the
 * Alfresco Repo is running//from   w  ww.  ja  v a  2s . c  o m
 *
 * @param method
 * @return
 */
protected String getContextRoot(FrameworkMethod method) {
    Class<?> declaringClass = method.getMethod().getDeclaringClass();
    boolean annotationPresent = declaringClass.isAnnotationPresent(Remote.class);
    if (annotationPresent) {
        Remote annotation = declaringClass.getAnnotation(Remote.class);
        return annotation.endpoint();
    }

    return "http://localhost:8080/alfresco";
}

From source file:org.compass.gps.device.jpa.entities.DefaultJpaEntitiesLocator.java

/**
 * Return <code>true</code> if the entity should be filtered out from the index operation.
 * <p/>//from  www  .ja  v  a2 s.  co m
 * Implementation filters out classes that one of the super classes has the {@link javax.persistence.Inheritance}
 * annotation and the super class has compass mappings.
 *
 * @param entityInformation The entity information to check if it should be filtered
 * @param device            The Jpa gps device
 * @return <code>true</code> if the entity should be filtered from the index process
 */
protected boolean shouldFilter(EntityInformation entityInformation, JpaGpsDevice device) {
    Class<?> clazz = entityInformation.getEntityClass().getSuperclass();
    while (true) {
        if (clazz == null || clazz.equals(Object.class)) {
            break;
        }
        if (clazz.isAnnotationPresent(Inheritance.class)
                && ((CompassGpsInterfaceDevice) device.getGps()).hasMappingForEntityForIndex(clazz)) {
            if (log.isDebugEnabled()) {
                log.debug("Entity [" + entityInformation.getName() + "] is inherited and super class [" + clazz
                        + "] has compass mapping, filtering it out");
            }
            return true;
        }
        clazz = clazz.getSuperclass();
    }
    return false;
}

From source file:com.github.gekoh.yagen.api.DefaultNamingStrategy.java

@Override
public String classToTableShortName(String className) {
    try {//from   w  w  w . j  a  v a  2s  . co  m
        Class<?> aClass = Class.forName(className);
        String tableShortName = null;
        if (aClass.isAnnotationPresent(Table.class)) {
            tableShortName = aClass.getAnnotation(Table.class).shortName();
        }
        if (StringUtils.isEmpty(tableShortName)) {
            try {
                Field tblShortNameField = aClass.getDeclaredField("TABLE_NAME_SHORT");
                if (tblShortNameField != null) {
                    tableShortName = tblShortNameField.get(null).toString();
                }
            } catch (Exception ignore) {
            }
        }
        if (StringUtils.isEmpty(tableShortName)) {
            tableShortName = tableShortNameFromTableName(classToTableName(className));
        }
        return tableShortName(tableShortName);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("cannot get table short name from class " + className, e);
    }
}

From source file:com.emc.ecs.sync.config.ConfigWrapper.java

public ConfigWrapper(Class<C> targetClass) {
    try {/*from  w  w  w .ja  v a 2 s. c o m*/
        this.targetClass = targetClass;
        if (targetClass.isAnnotationPresent(StorageConfig.class))
            this.uriPrefix = targetClass.getAnnotation(StorageConfig.class).uriPrefix();
        if (targetClass.isAnnotationPresent(FilterConfig.class))
            this.cliName = targetClass.getAnnotation(FilterConfig.class).cliName();
        if (targetClass.isAnnotationPresent(Label.class))
            this.label = targetClass.getAnnotation(Label.class).value();
        if (targetClass.isAnnotationPresent(Documentation.class))
            this.documentation = targetClass.getAnnotation(Documentation.class).value();
        BeanInfo beanInfo = Introspector.getBeanInfo(targetClass);
        for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            if (descriptor.getReadMethod().isAnnotationPresent(Option.class)) {
                propertyMap.put(descriptor.getName(), new ConfigPropertyWrapper(descriptor));
            }
        }
        for (MethodDescriptor descriptor : beanInfo.getMethodDescriptors()) {
            Method method = descriptor.getMethod();
            if (method.isAnnotationPresent(UriParser.class)) {
                if (method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length == 1
                        && method.getParameterTypes()[0].equals(String.class)) {
                    uriParser = method;
                } else {
                    log.warn("illegal signature for @UriParser method {}.{}", targetClass.getSimpleName(),
                            method.getName());
                }
            } else if (method.isAnnotationPresent(UriGenerator.class)) {
                if (method.getReturnType().equals(String.class) && method.getParameterTypes().length == 0) {
                    uriGenerator = method;
                } else {
                    log.warn("illegal signature for @UriGenerator method {}.{}", targetClass.getSimpleName(),
                            method.getName());
                }
            }
        }
        if (propertyMap.isEmpty())
            log.info("no @Option annotations found in {}", targetClass.getSimpleName());
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.rifidi.edge.configuration.RifidiService.java

/**
 * Constructor.//  w w  w  . j av a  2  s .c  om
 */
public RifidiService() {
    this.nameToProperty = new HashMap<String, Property>();
    this.nameToOperation = new HashMap<String, Operation>();
    this.nameToMethod = new HashMap<String, Method>();
    Class<?> clazz = this.getClass();
    if (clazz.isAnnotationPresent(JMXMBean.class)) {
        // check method annotations
        for (Method method : clazz.getMethods()) {
            // scan for operations annotation
            if (method.isAnnotationPresent(Operation.class)) {
                nameToOperation.put(method.getName(), (Operation) method.getAnnotation(Operation.class));
            }
            // scan for property annotation
            if (method.isAnnotationPresent(Property.class)) {
                nameToProperty.put(method.getName().substring(3),
                        (Property) method.getAnnotation(Property.class));
                nameToMethod.put(method.getName().substring(3), method);
            }
        }
    }
}

From source file:org.yestech.maven.HibernateSearchBuildIndexesMojo.java

@SuppressWarnings({ "unchecked" })
private FullTextSession processObjects(FullTextSession fullTextSession, Connection con,
        Configuration configuration) {
    SessionFactory sessionFactory = configuration.buildSessionFactory();
    Session session = sessionFactory.openSession(con);
    fullTextSession = Search.getFullTextSession(session);

    Map<String, ClassMetadata> metadata = sessionFactory.getAllClassMetadata();

    for (Map.Entry<String, ClassMetadata> entry : metadata.entrySet()) {

        Class clazz = entry.getValue().getMappedClass(EntityMode.POJO);

        if (clazz.isAnnotationPresent(Indexed.class)) {
            getLog().info("Indexing " + entry);

            Transaction tx = fullTextSession.beginTransaction();
            Criteria criteria = fullTextSession.createCriteria(clazz);
            criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

            DirectoryProvider[] providers = fullTextSession.getSearchFactory().getDirectoryProviders(clazz);
            for (DirectoryProvider provider : providers) {
                getLog().info("Index directory: " + provider.getDirectory());
            }/*from   w  w w . j  a v  a  2s  .  c o m*/

            List<?> list = criteria.list();
            for (Object o : list) {
                fullTextSession.index(o);
            }
            fullTextSession.flushToIndexes();
            tx.commit();
        }
    }

    return fullTextSession;
}

From source file:com.google.code.struts.annotations.plugin.StrutsAnnotationConfigLoaderPlugIn.java

/**
 * Process all the classes within the specified packages that are annotated
 * with the {@link Form @Form} annotation 
 * @param moduleConfig The Struts configuration object
 * @throws Exception On any error//from  www. j  ava2s .  c o  m
 */
private void processAnnotatedForms(ModuleConfig moduleConfig) throws Exception {
    StringTokenizer tokenizer = new StringTokenizer(annotatedFormsPackages, ",");
    while (tokenizer.hasMoreTokens()) {
        String pkg = tokenizer.nextToken();
        logger.debug("Processing annotated forms from package: " + pkg);
        List<Class<?>> classes = PackageIntrospector.getClasses(pkg);
        for (Class<?> c : classes) {
            if (c.isAnnotationPresent(Form.class)) {
                FormBeanConfig formBeanConfig = (FormBeanConfig) RequestUtils
                        .applicationInstance(moduleConfig.getActionFormBeanClass());
                // Process "type"
                formBeanConfig.setType(c.getName());
                // Process "name"
                String name = c.getAnnotation(Form.class).name();
                if (Strings.isEmpty(name)) {
                    name = Strings.lowerCamelCase(c);
                }
                formBeanConfig.setName(name);
                // Process properties for dynamic forms
                if (c.isAnnotationPresent(FormProperties.class)) {
                    FormProperties formPropertiesAnnotation = c.getAnnotation(FormProperties.class);
                    for (FormProperty fp : formPropertiesAnnotation.properties()) {
                        FormPropertyConfig formPropertyConfig = new FormPropertyConfig();
                        formPropertyConfig.setName(fp.name());
                        formPropertyConfig.setType(fp.type().getName());
                        formBeanConfig.addFormPropertyConfig(formPropertyConfig);
                    }
                }
                moduleConfig.addFormBeanConfig(formBeanConfig);
                logger.debug("Added annotated configuration for form: " + c.getName());
            }
        }
    }
}