Example usage for org.springframework.core.type.classreading MetadataReader getAnnotationMetadata

List of usage examples for org.springframework.core.type.classreading MetadataReader getAnnotationMetadata

Introduction

In this page you can find the example usage for org.springframework.core.type.classreading MetadataReader getAnnotationMetadata.

Prototype

AnnotationMetadata getAnnotationMetadata();

Source Link

Document

Read full annotation metadata for the underlying class, including metadata for annotated methods.

Usage

From source file:org.wallride.tools.Hbm2ddl.java

public static void main(String[] args) throws Exception {
    String locationPattern = "classpath:/org/wallride/domain/*";

    final BootstrapServiceRegistry registry = new BootstrapServiceRegistryBuilder().build();
    final MetadataSources metadataSources = new MetadataSources(registry);
    final StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder(registry);

    registryBuilder.applySetting(AvailableSettings.DIALECT,
            ExtendedMySQL5InnoDBDialect.class.getCanonicalName());
    registryBuilder.applySetting(AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, true);
    registryBuilder.applySetting(AvailableSettings.PHYSICAL_NAMING_STRATEGY,
            PhysicalNamingStrategySnakeCaseImpl.class);

    final PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    final Resource[] resources = resourcePatternResolver.getResources(locationPattern);
    final SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
    for (Resource resource : resources) {
        MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
        AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
        if (metadata.hasAnnotation(Entity.class.getName())) {
            metadataSources.addAnnotatedClass(Class.forName(metadata.getClassName()));
        }/*  w w  w .j a va2s  .  c o m*/
    }

    final StandardServiceRegistryImpl registryImpl = (StandardServiceRegistryImpl) registryBuilder.build();
    final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(registryImpl);

    new SchemaExport().setHaltOnError(true).setDelimiter(";").create(EnumSet.of(TargetType.STDOUT),
            metadataBuilder.build());
}

From source file:org.syncope.hibernate.HibernateEnhancer.java

public static void main(final String[] args) throws Exception {

    if (args.length != 1) {
        throw new IllegalArgumentException("Expecting classpath as single argument");
    }/*from  w  w w .ja v a2  s  .  com*/

    ClassPool classPool = ClassPool.getDefault();
    classPool.appendClassPath(args[0]);

    PathMatchingResourcePatternResolver resResolver = new PathMatchingResourcePatternResolver(
            classPool.getClassLoader());
    CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory();

    for (Resource resource : resResolver.getResources("classpath*:org/syncope/core/**/*.class")) {

        MetadataReader metadataReader = cachingMetadataReaderFactory.getMetadataReader(resource);
        if (metadataReader.getAnnotationMetadata().isAnnotated(Entity.class.getName())) {

            Class entity = Class.forName(metadataReader.getClassMetadata().getClassName());
            classPool.appendClassPath(new ClassClassPath(entity));
            CtClass ctClass = ClassPool.getDefault().get(entity.getName());
            if (ctClass.isFrozen()) {
                ctClass.defrost();
            }
            ClassFile classFile = ctClass.getClassFile();
            ConstPool constPool = classFile.getConstPool();

            for (Field field : entity.getDeclaredFields()) {
                if (field.isAnnotationPresent(Lob.class)) {
                    AnnotationsAttribute typeAttr = new AnnotationsAttribute(constPool,
                            AnnotationsAttribute.visibleTag);
                    Annotation typeAnnot = new Annotation("org.hibernate.annotations.Type", constPool);
                    typeAnnot.addMemberValue("type",
                            new StringMemberValue("org.hibernate.type.StringClobType", constPool));
                    typeAttr.addAnnotation(typeAnnot);

                    CtField lobField = ctClass.getDeclaredField(field.getName());
                    lobField.getFieldInfo().addAttribute(typeAttr);
                }
            }

            ctClass.writeFile(args[0]);
        }
    }
}

From source file:com.reactivetechnologies.platform.datagrid.util.EntityFinder.java

/**
 * /*w  ww .  ja  va  2 s  .  com*/
 * @param basePkg
 * @return
 * @throws ClassNotFoundException
 */
public static Collection<Class<?>> findEntityClasses(String basePkg) throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new TypeFilter() {

        @Override
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            AnnotationMetadata aMeta = metadataReader.getAnnotationMetadata();
            return aMeta.hasAnnotation(HzMapConfig.class.getName());
        }
    });
    //consider the finder class to be in the root package
    Set<BeanDefinition> beans = null;
    try {
        beans = provider.findCandidateComponents(StringUtils.hasText(basePkg) ? basePkg
                : EntityFinder.class.getName().substring(0, EntityFinder.class.getName().lastIndexOf(".")));
    } catch (Exception e) {
        throw new IllegalArgumentException("Unable to scan for entities under base package", e);
    }

    Set<Class<?>> classes = new HashSet<>();
    if (beans != null && !beans.isEmpty()) {
        classes = new HashSet<>(beans.size());
        for (BeanDefinition bd : beans) {
            classes.add(Class.forName(bd.getBeanClassName()));
        }
    } else {
        log.warn(">> Did not find any key value entities under the given base scan package [" + basePkg + "]");
    }
    return classes;

}

From source file:com.reactive.hzdfs.utils.EntityFinder.java

/**
 * /*from w  w  w  .  j  a  v a  2  s. c  om*/
 * @param basePkg
 * @return
 * @throws ClassNotFoundException
 */
public static Collection<Class<?>> findMapEntityClasses(String basePkg) throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new TypeFilter() {

        @Override
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            AnnotationMetadata aMeta = metadataReader.getAnnotationMetadata();
            return aMeta.hasAnnotation(IMapConfig.class.getName());
        }
    });

    return findComponents(provider, basePkg);

}

From source file:com.reactivetechnologies.platform.utils.EntityFinder.java

/**
 * /*from  ww  w. ja v a 2  s .  c om*/
 * @param basePkg
 * @return
 * @throws ClassNotFoundException
 */
public static Collection<Class<?>> findMapEntityClasses(String basePkg) throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new TypeFilter() {

        @Override
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            AnnotationMetadata aMeta = metadataReader.getAnnotationMetadata();
            return aMeta.hasAnnotation(HzMapConfig.class.getName());
        }
    });
    //consider the finder class to be in the root package
    Set<BeanDefinition> beans = null;
    try {
        beans = provider.findCandidateComponents(StringUtils.hasText(basePkg) ? basePkg
                : EntityFinder.class.getName().substring(0, EntityFinder.class.getName().lastIndexOf(".")));
    } catch (Exception e) {
        throw new IllegalArgumentException("Unable to scan for entities under base package", e);
    }

    Set<Class<?>> classes = new HashSet<>();
    if (beans != null && !beans.isEmpty()) {
        classes = new HashSet<>(beans.size());
        for (BeanDefinition bd : beans) {
            classes.add(Class.forName(bd.getBeanClassName()));
        }
    } else {
        log.warn(">> Did not find any key value entities under the given base scan package [" + basePkg + "]");
    }
    return classes;

}

From source file:com.reactivetechnologies.platform.utils.EntityFinder.java

/**
 * Scans for JAX RS classes under given (comma delimited) packages
 * @param basePkg/*from   ww  w  .j  a va  2 s.  c  o m*/
 * @return
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 */
public static List<Class<?>> findJaxRsClasses(String basePkg)
        throws ClassNotFoundException, IllegalAccessException {
    if (basePkg.contains(",")) {
        List<Class<?>> allPkgClasses = new ArrayList<>();
        String[] pkgs = basePkg.split(",");
        for (String pkg : pkgs) {
            allPkgClasses.addAll(findJaxRsClasses(pkg));
        }
        return allPkgClasses;
    }
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new TypeFilter() {

        @Override
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            AnnotationMetadata aMeta = metadataReader.getAnnotationMetadata();
            return aMeta.hasAnnotation(Path.class.getName()) || (aMeta.hasAnnotatedMethods(GET.class.getName())
                    || aMeta.hasAnnotatedMethods(POST.class.getName())
                    || aMeta.hasAnnotatedMethods(DELETE.class.getName())
                    || aMeta.hasAnnotatedMethods(Path.class.getName()));
        }
    });

    Set<BeanDefinition> beans = null;
    try {
        beans = provider.findCandidateComponents(StringUtils.hasText(basePkg) ? basePkg
                : EntityFinder.class.getName().substring(0, EntityFinder.class.getName().lastIndexOf(".")));
    } catch (Exception e) {
        throw new BeanInitializationException("Unable to scan for JAX-RS annotated classes under base package",
                e);
    }
    List<Class<?>> classes = new ArrayList<Class<?>>();
    if (beans != null && !beans.isEmpty()) {
        Class<?> restletClass;
        for (BeanDefinition bd : beans) {
            restletClass = Class.forName(bd.getBeanClassName());
            classes.add(restletClass);
        }
    } else {
        log.warn("** Did not find any JAX-RS annotated classes under the given base scan package [" + basePkg
                + "]. No REST requests will be served **");
    }
    return classes;

}

From source file:com.github.yulechen.springannotation.test.ConfigurationClassUtils.java

/**
 * Check whether the given bean definition is a candidate for a
 * configuration class (or a nested component class declared within a
 * configuration/component class, to be auto-registered as well), and mark
 * it accordingly./*from  w w  w  .ja  va  2 s .  c  om*/
 * 
 * @param beanDef
 *            the bean definition to check
 * @param metadataReaderFactory
 *            the current factory in use by the caller
 * @return whether the candidate qualifies as (any kind of) configuration
 *         class
 */
public static boolean checkConfigurationClassCandidate(BeanDefinition beanDef,
        MetadataReaderFactory metadataReaderFactory) {
    String className = beanDef.getBeanClassName();
    if (className == null) {
        return false;
    }

    AnnotationMetadata metadata;
    if (beanDef instanceof AnnotatedBeanDefinition
            && className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) {
        // Can reuse the pre-parsed metadata from the given
        // BeanDefinition...
        metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata();
    } else if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
        // Check already loaded Class if present...
        // since we possibly can't even load the class file for this Class.
        Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass();
        metadata = new StandardAnnotationMetadata(beanClass, true);
    } else {
        try {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
            metadata = metadataReader.getAnnotationMetadata();
        } catch (IOException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Could not find class file for introspecting configuration annotations: " + className,
                        ex);
            }
            return false;
        }
    }

    if (isFullConfigurationCandidate(metadata)) {
        beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
    } else if (isLiteConfigurationCandidate(metadata)) {
        beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
    } else {
        return false;
    }

    // It's a full or lite configuration candidate... Let's determine the
    // order value, if any.
    Map<String, Object> orderAttributes = metadata.getAnnotationAttributes(Order.class.getName());
    if (orderAttributes != null) {
        beanDef.setAttribute(ORDER_ATTRIBUTE, orderAttributes.get(AnnotationUtils.VALUE));
    }

    return true;
}

From source file:br.com.caelum.vraptor.ioc.spring.ComponentTypeFilter.java

public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
        throws IOException {
    AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
    for (Class<? extends Annotation> annotationType : annotationTypes) {
        if (metadata.hasAnnotation(annotationType.getName())) {
            return true;
        }//from w w w .  ja v a  2s .c  o m
    }
    return metadata.hasMetaAnnotation(Stereotype.class.getName());
}

From source file:org.syncope.core.util.SpringPersistenceUnitPostProcessor.java

@Override
public void postProcessPersistenceUnitInfo(final MutablePersistenceUnitInfo mpui) {

    if (locations.length == 0) {
        LOG.warn("No locations provided");
    }//from w ww.  j a  v  a  2s .c o m

    CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory();

    try {
        for (String location : locations) {
            for (Resource resource : resResolver.getResources(location)) {
                MetadataReader metadataReader = cachingMetadataReaderFactory.getMetadataReader(resource);
                if (metadataReader.getAnnotationMetadata().isAnnotated(Entity.class.getName())) {

                    mpui.addManagedClassName(metadataReader.getClassMetadata().getClassName());
                }
            }
        }
        mpui.setExcludeUnlistedClasses(true);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.fishwife.jrugged.spring.AnnotatedMethodFilter.java

/**
 * {@inheritDoc}/* w  w w .jav a2 s .c om*/
 */
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
        throws IOException {
    AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
    Set<MethodMetadata> annotatedMethods = annotationMetadata
            .getAnnotatedMethods(annotatedClass.getCanonicalName());
    return !annotatedMethods.isEmpty();
}