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

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

Introduction

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

Prototype

public static ClassPath from(ClassLoader classloader) throws IOException 

Source Link

Document

Returns a ClassPath representing all classes and resources loadable from classloader and its parent class loaders.

Usage

From source file:com.google.cloud.crypto.tink.KeysetManager.java

private static Class<?> loadClass(String className) throws GeneralSecurityException {
    try {//from  ww w  . j a v a2 s . c o  m
        ImmutableSet<ClassInfo> classInfos = ClassPath.from(KeysetManager.class.getClassLoader())
                .getAllClasses();
        for (ClassInfo classInfo : classInfos) {
            if (classInfo.getName().toLowerCase().endsWith(className.toLowerCase())) {
                return classInfo.load();
            }
        }
    } catch (Exception e) {
        throw new GeneralSecurityException("Class not found: " + className, e);
    }
    throw new GeneralSecurityException("Class not found: " + className);
}

From source file:com.google.devtools.build.lib.skyframe.serialization.CodecScanner.java

/** Return the {@link ClassInfo} objects matching {@code packagePrefix} sorted by name. */
private static Stream<ClassInfo> getClassInfos(String packagePrefix) throws IOException {
    return ClassPath.from(ClassLoader.getSystemClassLoader()).getResources().stream()
            .filter(r -> r instanceof ClassInfo).map(r -> (ClassInfo) r)
            .filter(c -> c.getPackageName().startsWith(packagePrefix))
            .sorted(Comparator.comparing(ClassInfo::getName));
}

From source file:org.jmingo.mapping.convert.ConverterService.java

private Set<Class<?>> getConvertersClasses(String converterPackage, ClassLoader classLoader) {
    Set<Class<?>> classes = Collections.emptySet();
    try {//from ww w.j a v a2s.  c o  m
        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:org.copperengine.ext.wfrepo.classpath.ClasspathWorkflowRepository.java

static Set<Class<?>> findWorkflowClasses(final List<String> wfPackages, final ClassLoader cl) throws Exception {
    final ClassPath cp = ClassPath.from(cl);
    final Set<Class<?>> set = new HashSet<Class<?>>();
    for (String wfPackage : wfPackages) {
        final ImmutableSet<com.google.common.reflect.ClassPath.ClassInfo> x = cp
                .getTopLevelClassesRecursive(wfPackage);
        for (com.google.common.reflect.ClassPath.ClassInfo ci : x) {
            final Class<?> c = cl.loadClass(ci.getName());
            set.add(c);/*from   w ww.  ja  v  a  2 s .  c o  m*/
            set.addAll(Arrays.asList(c.getDeclaredClasses()));
            loadAnonymousInnerClasses(cl, set, c);
        }
    }
    return set;
}

From source file:org.sosy_lab.cpachecker.cmdline.CPASelfCheck.java

private static List<Class<ConfigurableProgramAnalysis>> getCPAs() throws ClassNotFoundException, IOException {
    Set<ClassInfo> cpaCandidates = ClassPath.from(Thread.currentThread().getContextClassLoader())
            .getTopLevelClasses("org.sosy_lab.cpachecker.cpa");

    List<Class<ConfigurableProgramAnalysis>> cpas = new ArrayList<>();

    Class<ConfigurableProgramAnalysis> targetType = null;

    for (ClassInfo candidateInfo : cpaCandidates) {
        Class<?> candidate = candidateInfo.load();
        if (!Modifier.isAbstract(candidate.getModifiers()) && !Modifier.isInterface(candidate.getModifiers())
                && ConfigurableProgramAnalysis.class.isAssignableFrom(candidate)) {

            // candidate is non-abstract implementation of CPA interface
            cpas.add(uncheckedGenericCast(candidate, targetType));
        }//from w  ww . ja  v a  2s. c  om
    }

    return cpas;
}

From source file:org.transitime.applications.SchemaGenerator.java

/**
 * Utility method used to fetch Class list based on a package name.
 * /* w  ww  . j  a  v a 2  s.c o  m*/
 * @param packageName
 *            (should be the package containing your annotated beans.
 */
@SuppressWarnings("rawtypes")
private List<Class> getClasses(String packageName) throws Exception {

    logger.debug("Start: Classes in " + packageName);
    List<Class> classes = new ArrayList<Class>();
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();

    for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) {
        if (info.getName().startsWith(packageName)) {
            final Class<?> clazz = info.load();
            logger.debug(info.getName());
            classes.add(clazz);
        }
    }
    logger.debug("End: Classes in " + packageName);

    return classes;
}

From source file:net.revelc.code.apilyzer.maven.plugin.AnalyzeMojo.java

private ClassPath getClassPath() throws DependencyResolutionRequiredException, IOException {
    ClassLoader cl;/*from   w w  w .  ja  v  a2 s  .  c  o m*/
    List<URL> urls = Lists.transform(project.getCompileClasspathElements(), new Function<String, URL>() {
        @Override
        public URL apply(String input) {
            try {
                return new File(input).toURI().toURL();
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException("Unable to convert string (" + input + ") to URL", e);
            }
        }
    });
    cl = new URLClassLoader(urls.toArray(new URL[0]));
    return ClassPath.from(cl);
}

From source file:org.diqube.ui.websocket.request.JsonRequestDeserializer.java

@SuppressWarnings("unchecked")
@PostConstruct/* www .  j  av  a  2  s.  c  o  m*/
public void initialize() throws IOException {
    commandClasses = new HashMap<>();
    Set<ClassInfo> classInfos = ClassPath.from(getClass().getClassLoader())
            .getTopLevelClassesRecursive("org.diqube.ui");
    for (ClassInfo classInfo : classInfos) {
        Class<?> clazz = classInfo.load();
        if (clazz.isAnnotationPresent(CommandInformation.class) && JsonCommand.class.isAssignableFrom(clazz)) {
            CommandInformation annotation = clazz.getAnnotation(CommandInformation.class);

            commandClasses.put(annotation.name(), (Class<? extends JsonCommand>) clazz);
        }
    }
}

From source file:org.eclipse.m2e.editor.xml.mojo.PlexusConfigHelper.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public List<Class> getCandidateClasses(ClassRealm realm, Class enclosingClass, Class paramClass) {

    String name = enclosingClass.getName();
    int dot = name.lastIndexOf('.');
    if (dot > 0) {
        String pkg = name.substring(0, dot);

        List<Class> candidateClasses = null;

        ClassPath cp;//from ww w .  j  a v a 2s . co m
        try {
            cp = ClassPath.from(realm);
        } catch (IOException e) {
            log.error(e.getMessage());
            return Collections.singletonList(enclosingClass);
        }

        for (ClassInfo ci : cp.getTopLevelClasses(pkg)) {
            Class clazz;
            try {
                clazz = realm.loadClass(ci.getName());
            } catch (ClassNotFoundException e) {
                log.error(e.getMessage(), e);
                continue;
            }

            if ((clazz.getModifiers() & (Modifier.ABSTRACT)) != 0) {
                continue;
            }

            if (!paramClass.isAssignableFrom(clazz)) {
                continue;
            }

            // skip classes without no-arg constructors
            try {
                clazz.getConstructor(new Class[0]);
            } catch (NoSuchMethodException ex) {
                continue;
            }

            if (candidateClasses == null) {
                candidateClasses = new ArrayList<Class>();
            }
            candidateClasses.add(clazz);

        }

        if (candidateClasses != null) {
            return candidateClasses;
        }
    }

    return Collections.singletonList(paramClass);
}

From source file:sparkjni.utils.SparkJni.java

/**
 * @TO-DO Find faster solution and enable it.
 *//*from   w  w w  .j  a va  2s  . c  om*/
public void loadAnnotatedClasses() {
    ClassLoader sparkJniClassloader = SparkJni.class.getClassLoader();
    try {
        Set<ClassPath.ClassInfo> classesInPackage = ClassPath.from(sparkJniClassloader).getTopLevelClasses();
        for (ClassPath.ClassInfo classInfo : classesInPackage) {
            try {
                Class candidate = Class.forName(classInfo.getName());
                if (loadJNIContainersAnnotatedClass(candidate))
                    continue;
                if (loadJNIfuncsAnnotatedClass(candidate))
                    continue;
            } catch (Error err) {
                System.err.println("Error");
            }
        }
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}