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

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

Introduction

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

Prototype

ClassMetadata getClassMetadata();

Source Link

Document

Read basic class metadata for the underlying class.

Usage

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");
    }//ww  w.  j  ava2  s.c  om

    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:Main.java

private static Class getClassOrNull(MetadataReaderFactory readerFactory, Resource resource) {
    try {/*  w w  w  .ja v  a2s .  co  m*/
        MetadataReader metadataReader = readerFactory.getMetadataReader(resource);
        return Class.forName(metadataReader.getClassMetadata().getClassName());
    } catch (Exception e) {
        return null;
    }
}

From source file:com.fantasy.Application.java

private static boolean isCandidate(MetadataReader metadataReader) throws ClassNotFoundException {
    try {//  ww  w  . j  a va  2  s . com
        Class c = Class.forName(metadataReader.getClassMetadata().getClassName());
        if (c.getAnnotation(TaskRunner.class) != null) {
            return true;
        }
    } catch (Throwable e) {
    }
    return false;
}

From source file:com.fantasy.Application.java

private static List<Class> findTypes(String basePackage) throws IOException, ClassNotFoundException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class> candidates = new ArrayList();
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
            + resolveBasePackage(basePackage) + "/" + "**/*.class";
    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (isCandidate(metadataReader)) {
                candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            }//from www . ja v a  2 s  .  c  o m
        }
    }
    return candidates;
}

From source file:org.javelin.sws.ext.bind.SweJaxbContextFactory.java

/**
 * <p>Determines mapped classes in the context path and invokes {@link #createContext(Class[], Map)}</p>
 * <p>JAXB-RI uses {@code ObjectFactory} class and/or {@code jaxb.index} file</p>
 * <p>see: com.sun.xml.bind.v2.ContextFactory.createContext(String, ClassLoader, Map<String, Object>)</p>
 * /* ww w.j a v  a  2  s . co m*/
 * @param contextPath
 * @param classLoader
 * @param properties
 * @return
 * @throws IOException 
 */
public static JAXBContext createContext(String contextPath, ClassLoader classLoader, Map<String, ?> properties)
        throws IOException {
    Assert.notNull(contextPath, "The contextPath should not be null");

    PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(
            classLoader);
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class<?>> classes = new LinkedList<Class<?>>();
    // scan the package(s)
    String[] packages = StringUtils.tokenizeToStringArray(contextPath, ":");
    for (String pkg : packages) {
        log.trace("Scanning package: {}", pkg);
        Resource[] resources = resourcePatternResolver
                .getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                        + ClassUtils.convertClassNameToResourcePath(pkg) + "/*.class");
        for (Resource classResource : resources) {
            MetadataReader mdReader = metadataReaderFactory.getMetadataReader(classResource);
            Class<?> cls = ClassUtils.resolveClassName(mdReader.getClassMetadata().getClassName(), classLoader);
            if (cls.getSimpleName().equals("package-info")) {
                XmlSchema xmlSchema = AnnotationUtils.getAnnotation(cls.getPackage(), XmlSchema.class);
                String namespace = xmlSchema == null || xmlSchema.namespace() == null
                        ? NamespaceUtils.packageNameToNamespace(cls.getPackage())
                        : xmlSchema.namespace();
                log.trace(" - found package-info: {}, namespace: {}", cls.getPackage().getName(), namespace);
            } else {
                log.trace(" - found class: {}", mdReader.getClassMetadata().getClassName());
                classes.add(cls);
            }
        }
    }

    return createContext(classes.toArray(new Class[0]), properties);
}

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

/**
 * Find implementation classes for the given interface.
 * @param <T>//from w  w  w. ja v  a2  s .  c o  m
 * @param basePkg
 * @param baseInterface
 * @return
 * @throws ClassNotFoundException
 */
@SuppressWarnings("unchecked")
public static <T> List<Class<T>> findImplementationClasses(String basePkg, final Class<T> baseInterface)
        throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new TypeFilter() {

        @Override
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            ClassMetadata aMeta = metadataReader.getClassMetadata();
            String[] intf = aMeta.getInterfaceNames();
            Arrays.sort(intf);
            return Arrays.binarySearch(intf, baseInterface.getName()) >= 0;
        }
    });

    Set<Class<?>> collection = findComponents(provider, basePkg);
    List<Class<T>> list = new ArrayList<>(collection.size());
    for (Class<?> c : collection) {
        list.add((Class<T>) c);
    }
    return list;

}

From source file:com.foilen.smalltools.tools.Hibernate4Tools.java

/**
 * Generate the SQL file. This is based on the code in {@link LocalSessionFactoryBuilder#scanPackages(String...)}
 *
 * @param dialect//from   w  ww  . ja v  a2 s  . c om
 *            the dialect (e.g: org.hibernate.dialect.MySQL5InnoDBDialect )
 * @param outputSqlFile
 *            where to put the generated SQL file
 * @param useUnderscore
 *            true: to have tables names like "employe_manager" ; false: to have tables names like "employeManager"
 * @param packagesToScan
 *            the packages where your entities are
 */
@SuppressWarnings("deprecation")
public static void generateSqlSchema(Class<? extends Dialect> dialect, String outputSqlFile,
        boolean useUnderscore, String... packagesToScan) {

    // Configuration
    Configuration configuration = new Configuration();
    if (useUnderscore) {
        configuration.setNamingStrategy(new ImprovedNamingStrategy());
    }

    Properties properties = new Properties();
    properties.setProperty(AvailableSettings.DIALECT, dialect.getName());

    // Scan packages
    Set<String> classNames = new TreeSet<String>();
    Set<String> packageNames = new TreeSet<String>();
    try {
        for (String pkg : packagesToScan) {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                    + ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
            Resource[] resources = resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader reader = readerFactory.getMetadataReader(resource);
                    String className = reader.getClassMetadata().getClassName();
                    if (matchesEntityTypeFilter(reader, readerFactory)) {
                        classNames.add(className);
                    } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
                        packageNames
                                .add(className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
                    }
                }
            }
        }
    } catch (IOException ex) {
        throw new MappingException("Failed to scan classpath for unlisted classes", ex);
    }
    try {
        for (String className : classNames) {
            configuration.addAnnotatedClass(resourcePatternResolver.getClassLoader().loadClass(className));
        }
        for (String packageName : packageNames) {
            configuration.addPackage(packageName);
        }
    } catch (ClassNotFoundException ex) {
        throw new MappingException("Failed to load annotated classes from classpath", ex);
    }

    // Exportation
    SchemaExport schemaExport = new SchemaExport(configuration, properties);
    schemaExport.setOutputFile(outputSqlFile);
    schemaExport.setDelimiter(";");
    schemaExport.setFormat(true);
    schemaExport.execute(true, false, false, true);
}

From source file:com.crudetech.junit.categories.Categories.java

static Class<?>[] allTestClassesInClassPathMatchingPattern(String pattern) throws InitializationError {
    List<Class<?>> classes = new ArrayList<Class<?>>();

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metaDataReaderFactory = new CachingMetadataReaderFactory();
    try {//from w ww. j ava  2  s .  c om
        String classPattern = "classpath:" + pattern.replace('.', '/') + ".class";
        Resource[] res = resolver.getResources(classPattern);
        for (Resource r : res) {
            if (!r.isReadable()) {
                continue;
            }
            MetadataReader reader = metaDataReaderFactory.getMetadataReader(r);
            Class<?> c = Class.forName(reader.getClassMetadata().getClassName());

            if (Modifier.isAbstract(c.getModifiers())) {
                continue;
            }
            classes.add(c);
        }
        return classes.toArray(new Class<?>[classes.size()]);
    } catch (Exception e) {
        throw new InitializationError(e);
    }
}

From source file:com.baomidou.framework.spring.SpringScanPackage.java

/**
 * <p>/*from w  w  w .  j  a v  a 2  s  .  co  m*/
 * ???,?
 * </p>
 *
 * @param scanPackages
 *            ??package
 * @return
 */
public static Set<String> findPackageClass(String scanPackages) {
    Set<String> clazzSet = new HashSet<String>();
    ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
    String pkg = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
            + ClassUtils.convertClassNameToResourcePath(scanPackages) + "/**/*.class";
    /*
     * ??Resource
     * ClassLoader.getResource("META-INF")?????????
     */
    try {
        Resource[] resources = resolver.getResources(pkg);
        if (resources != null && resources.length > 0) {
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    if (metadataReader != null) {
                        clazzSet.add(metadataReader.getClassMetadata().getClassName());
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return clazzSet;
}

From source file:com.baomidou.mybatisplus.toolkit.PackageHelper.java

/**
 * <p>/*from  ww w  .j  av  a  2s  .  co m*/
 * ???
 * </p>
 * <p>
 * <property name="typeAliasesPackage" value="com.baomidou.*.entity"/>
 * </p>
 * 
 * @param typeAliasesPackage
 *            ??
 * @return
 */
public static String[] convertTypeAliasesPackage(String typeAliasesPackage) {
    ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
    String pkg = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
            + ClassUtils.convertClassNameToResourcePath(typeAliasesPackage) + "/*.class";

    /*
     * ??Resource
     * ClassLoader.getResource("META-INF")?????????
     */
    try {
        Set<String> set = new HashSet<String>();
        Resource[] resources = resolver.getResources(pkg);
        if (resources != null && resources.length > 0) {
            MetadataReader metadataReader = null;
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    set.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage()
                            .getName());
                }
            }
        }
        if (!set.isEmpty()) {
            return set.toArray(new String[] {});
        } else {
            throw new MybatisPlusException("not find typeAliasesPackage:" + pkg);
        }
    } catch (Exception e) {
        throw new MybatisPlusException("not find typeAliasesPackage:" + pkg, e);
    }
}