Example usage for com.google.common.reflect ClassPath getTopLevelClassesRecursive

List of usage examples for com.google.common.reflect ClassPath getTopLevelClassesRecursive

Introduction

In this page you can find the example usage for com.google.common.reflect ClassPath getTopLevelClassesRecursive.

Prototype

public ImmutableSet<ClassInfo> getTopLevelClassesRecursive(String packageName) 

Source Link

Document

Returns all top level classes whose package name is packageName or starts with packageName followed by a '.'.

Usage

From source file:org.diqube.remote.cluster.RIntermediateAggregationResultUtil.java

private synchronized static void initialize() {
    if (whitelistedSerializableClassNames != null)
        return;/*from   w w  w  .jav a 2  s  .co  m*/

    ClassPath cp;
    try {
        cp = ClassPath.from(RIntermediateAggregationResultUtil.class.getClassLoader());
    } catch (IOException e) {
        throw new RuntimeException("Could not initialize classpath scanning!", e);
    }
    ImmutableSet<ClassInfo> classInfos = cp.getTopLevelClassesRecursive(ROOT_PKG);

    whitelistedSerializableClassNames = new HashSet<>();

    for (ClassInfo classInfo : classInfos) {
        Class<?> clazz = classInfo.load();
        if (clazz.getAnnotation(IntermediateResultSerialization.class) != null) {
            if (!IntermediateResultSerializationResolver.class.isAssignableFrom(clazz)) {
                logger.warn("Class {} has {} annotation, but does not implement {}. Ignoring.", clazz.getName(),
                        IntermediateResultSerialization.class.getSimpleName(),
                        IntermediateResultSerializationResolver.class.getName());
                continue;
            }

            try {
                IntermediateResultSerializationResolver resolver = (IntermediateResultSerializationResolver) clazz
                        .newInstance();

                resolver.resolve(cls -> {
                    whitelistedSerializableClassNames.add(cls.getName());
                    logger.debug(
                            "Whitelisted class {} for being de-/serialized for intermediate aggregation results",
                            cls);
                });
            } catch (InstantiationException | IllegalAccessException e) {
                logger.warn("Could not instantiate {}. Ignoring.", clazz.getName(), e);
            }
        }
    }
}

From source file:com.rhythm.louie.Classes.java

private static List<Class<?>> findTypesAnnotatedWith(List<String> packages,
        Class<? extends Annotation> annotation, boolean recursive, List<String> whitelist,
        List<String> blacklist) throws IOException {
    ClassPath cp = ClassPath.from(Thread.currentThread().getContextClassLoader());

    List<Class<?>> found = new ArrayList<Class<?>>();
    Set<ClassInfo> infos = new HashSet<ClassInfo>();
    if (packages == null || packages.isEmpty()) {
        infos = cp.getTopLevelClasses();
    } else if (recursive) {
        for (String pkg : packages) {
            infos.addAll(cp.getTopLevelClassesRecursive(pkg));
        }//from www .  ja  v  a 2  s.c o m
    } else {
        for (String pkg : packages) {
            infos.addAll(cp.getTopLevelClasses(pkg));
        }
    }

    for (ClassInfo info : infos) {
        if (blacklist != null && blacklist.contains(info.getPackageName())) {
            if (whitelist != null) {
                if (!whitelist.contains(info.getName())) {
                    continue; //blacklisted, but not whitelisted
                }
            } else {
                continue;
            }
        }
        try {
            Class<?> cl = info.load();
            Annotation ann = cl.getAnnotation(annotation);
            if (ann != null) {
                found.add(cl);
            }
        } catch (Exception e) {
            LoggerFactory.getLogger(Classes.class).warn("Error Checking Class: " + info.getName(), e);
        }
    }

    return found;
}

From source file:com.puppycrawl.tools.checkstyle.internal.CheckUtil.java

/**
 * Gets all checkstyle's modules./*w  ww. j a  va  2 s  .  c om*/
 * @return the set of checkstyle's module classes.
 * @throws IOException if the attempt to read class path resources failed.
 * @see #isCheckstyleModule(Class)
 */
public static Set<Class<?>> getCheckstyleModules() throws IOException {
    final Set<Class<?>> checkstyleModules = new HashSet<>();

    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    final ClassPath classpath = ClassPath.from(loader);
    final String packageName = "com.puppycrawl.tools.checkstyle";
    final ImmutableSet<ClassPath.ClassInfo> checkstyleClasses = classpath
            .getTopLevelClassesRecursive(packageName);

    for (ClassPath.ClassInfo clazz : checkstyleClasses) {
        final Class<?> loadedClass = clazz.load();
        if (isCheckstyleModule(loadedClass)) {
            checkstyleModules.add(loadedClass);
        }
    }
    return checkstyleModules;
}

From source file:com.puppycrawl.tools.checkstyle.internal.CheckUtil.java

/**
 * Gets all checkstyle's non-abstract checks.
 * @return the set of checkstyle's non-abstract check classes.
 * @throws IOException if the attempt to read class path resources failed.
 * @see #isValidCheckstyleClass(Class, String)
 * @see #isCheckstyleCheck(Class)//  w  ww  . j  av  a 2  s .c  om
 */
public static Set<Class<?>> getCheckstyleChecks() throws IOException {
    final Set<Class<?>> checkstyleChecks = new HashSet<>();

    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    final ClassPath classpath = ClassPath.from(loader);
    final String packageName = "com.puppycrawl.tools.checkstyle";
    final ImmutableSet<ClassPath.ClassInfo> checkstyleClasses = classpath
            .getTopLevelClassesRecursive(packageName);

    for (ClassPath.ClassInfo clazz : checkstyleClasses) {
        final String className = clazz.getSimpleName();
        final Class<?> loadedClass = clazz.load();
        if (isValidCheckstyleClass(loadedClass, className) && isCheckstyleCheck(loadedClass)) {
            checkstyleChecks.add(loadedClass);
        }
    }
    return checkstyleChecks;
}

From source file:ch.ifocusit.livingdoc.plugin.diagram.PlantumlClassDiagramBuilder.java

public String generate() throws MojoExecutionException {
    final ClassPath classPath = initClassPath();
    final Set<ClassInfo> allClasses = classPath.getTopLevelClassesRecursive(prefix);

    String diagram = classDiagramBuilder.addClasse(allClasses.stream()
            // apply filters
            .filter(defaultFilter()).filter(additionalClassPredicate).map(classInfo -> {
                try {
                    return classInfo.load();
                } catch (Throwable e) {
                    LOG.warn(e.toString());
                }//from  ww  w.j ava  2 s.  com
                return null;
            }).filter(Objects::nonNull).collect(Collectors.toList())).excludes(excludes).setHeader(readHeader())
            .setFooter(readFooter()).withNamesMapper(namesMapper).withLinkMaker(this)
            .withDependencies(diagramWithDependencies).build();
    return diagram;
}

From source file:org.onehippo.forge.oaipmh.provider.provider.JaxbContextProvider.java

private void includeAnnotatedTopLevelClassesFromBeansPackage(final List<Class<?>> allClasses)
        throws IOException, ClassNotFoundException {
    if (!Strings.isNullOrEmpty(beansPackage)) {
        final ClassPath classPath = ClassPath.from(getClass().getClassLoader());
        final ImmutableSet<ClassPath.ClassInfo> topLevelClasses = classPath
                .getTopLevelClassesRecursive(beansPackage);
        for (ClassPath.ClassInfo topLevelClass : topLevelClasses) {
            final String name = topLevelClass.getName();
            final Class<?> clazz = Class.forName(name);
            if (clazz.isAnnotationPresent(XmlRootElement.class)) {
                log.debug("include {}", clazz);
                allClasses.add(clazz);/*from  ww w  .ja  va  2  s.  c o  m*/
            }
        }
    }
}

From source file:rocnikovyprojekt.Conversions.java

public Conversions() {
    System.out.println("Initializing Conversions...");
    ArrayList<Class<? extends Conversion>> list = new ArrayList<>();
    try {//from  w  ww.  j av  a  2s.c o m
        ClassPath classpath = ClassPath.from(Thread.currentThread().getContextClassLoader());
        /*Naplnenie list-u triedami implementujucimi Conversion*/
        for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClassesRecursive("rocnikovyprojekt")) {
            Class<?> c = Class.forName(classInfo.getName());
            if (Conversion.class.isAssignableFrom(c) && !c.equals(Conversion.class)) {
                System.out.println("Found " + classInfo.getName());
                list.add((Class<? extends Conversion>) c);
            }
        }
        /*Naplnenie grafu*/
        graph = new Graph();
        for (Class<? extends Conversion> c : list) {
            Conversion conv = c.newInstance();
            graph.addEdge(conv);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("Initialization complete.");
}

From source file:com.mingo.convert.ConverterService.java

private Set<Class<? extends Converter>> getConvertersClasses(String converterPackage, ClassLoader classLoader) {
    Set<Class<? extends Converter>> classes = Collections.emptySet();
    try {/*from ww w . j  a va  2  s.com*/
        ClassPath classPath = ClassPath.from(classLoader);
        Set<com.google.common.reflect.ClassPath.ClassInfo> classInfos = classPath
                .getTopLevelClassesRecursive(converterPackage);
        if (CollectionUtils.isNotEmpty(classInfos)) {
            classes = Sets.newHashSet();
            for (com.google.common.reflect.ClassPath.ClassInfo classInfo : classInfos) {
                Class converterClass = Class.forName(classInfo.getName());
                if (Converter.class.isAssignableFrom(converterClass)
                        && classInfo.getName().contains(converterPackage)) {
                    classes.add(converterClass);
                }
            }
        }
    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException(format(CONVERTER_LOAD_ERROR, converterPackage), e);
    }
    return classes;
}

From source file:nl.knaw.huygens.timbuctoo.tools.util.metadata.MetaDataGeneratorTool.java

public void execute() throws IllegalArgumentException, IllegalAccessException {
    ClassPath classPath = null;
    try {//w w w  .  j a va  2  s . c  o m
        classPath = ClassPath.from(this.getClass().getClassLoader());
    } catch (IOException e) {
        LOG.error("Could not load classpath", e);
        return;
    }

    for (ClassInfo info : classPath.getTopLevelClassesRecursive("nl.knaw.huygens.timbuctoo.model")) {
        String name = info.getName();
        try {
            Class<?> type = Class.forName(name);

            createMetaData(type, null);

            // create metadata for the inner classes aswell.
            for (Class<?> declaredType : type.getDeclaredClasses()) {
                createMetaData(declaredType, type);
            }

        } catch (ClassNotFoundException e) {
            LOG.info("Could not find class {}", name);
        }
    }
}

From source file:com.itametis.jsonconverter.classpathscan.JsonMappingPackage.java

/**
 * Get all classes from class path depending on the declaration of a specific classpath.
 *
 * @param classpath the class path to investigate.
 *
 * @return the classes./*from  w  w w.  j a  va  2 s  . c  om*/
 */
private ImmutableSet<ClassInfo> getClassesFromClassPath(ClassPath classpath) {
    if (this.packageToScan == null || this.packageToScan.isEmpty()) {
        return classpath.getAllClasses();
    } else {
        return classpath.getTopLevelClassesRecursive(this.packageToScan);
    }
}