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.analog.lyric.collect.ConstructorRegistry.java

/**
 * Preloads all subclasses of declared superclass {@code T} found in registry's packages.
 * <p>/*  w w  w  .j a va2 s  . c  o  m*/
 * Searches all of the packages in {@link #getPackages()} for subclasses of {@code T} and adds
 * then to the registry.
 * <p>
 * 
 * @since 0.07
 */
public synchronized void loadAll() {
    ClassLoader loader = getClass().getClassLoader();

    ClassPath path;
    try {
        path = ClassPath.from(loader);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    for (String packageName : _packages) {
        for (ClassPath.ClassInfo info : path.getTopLevelClasses(packageName)) {
            addConstructorsFrom(info.load(), true);
        }
    }
}

From source file:com.btisystems.pronx.ems.MibEntityCompiler.java

public void importDependencies() {
    try {//from www .  j  a  v  a 2s. c o  m
        final ImmutableSet<ClassPath.ClassInfo> classes = ClassPath.from(this.getClass().getClassLoader())
                .getAllClasses();
        for (ClassPath.ClassInfo clazz : classes) {
            if (clazz.getSimpleName().equals(GeneratedIdentifiers.OID_REGISTRY_CLASSNAME)) {
                LOG.info("Adding OIDs from registry: {}", clazz.getName());
                final Class loadedClass = this.getClass().getClassLoader().loadClass(clazz.getName());
                final Field field = loadedClass.getDeclaredField("oidRegistry");
                final TreeMap<OID, Class<? extends DeviceEntity>> map = (TreeMap<OID, Class<? extends DeviceEntity>>) field
                        .get(null);
                for (Entry<OID, Class<? extends DeviceEntity>> entry : map.entrySet()) {
                    if (!oidClasses.containsKey(entry.getKey().toString())) {
                        final String fullClassName = getFullClassName(entry.getValue().getPackage().getName(),
                                entry.getValue().getSimpleName());
                        if (codeModel._getClass(fullClassName) == null) {
                            final JDefinedClass importedClass = createClass(
                                    entry.getValue().getPackage().getName(), entry.getValue().getSimpleName());
                            final ClassMetadata metadata = new ClassMetadata(importedClass);
                            final boolean isTableRow = IIndexed.class.isAssignableFrom(entry.getValue());
                            metadata.setTableRow(isTableRow);
                            importedClass.metadata = metadata;
                            oidClasses.put(entry.getKey().toString(), importedClass);
                            IMPORTED_PACKAGES.add(entry.getValue().getPackage().getName());
                            IMPORTED_SYMBOLS.add(entry.getKey().toString());
                        } else {
                            oidClasses.put(entry.getKey().toString(), codeModel._getClass(fullClassName));
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        LOG.error("Exception adding classpath OIDS.", ex);
    }
}

From source file:soottocfg.soot.SootRunner.java

/**
 * Writes all classes from the soottocfg.spec to targetDir
 * so that we can use them later when re-writing the bytecode.
 * /*from   w  w w .  j ava2 s . co  m*/
 * @param targetDir
 */
protected void writeSpecPackageToDisc(File targetDir) {
    if (!targetDir.isDirectory()) {
        if (!targetDir.mkdirs()) {
            throw new RuntimeException("Can't write to disk");
        }
    }
    try {
        ClassLoader cl = this.getClass().getClassLoader();
        ClassPath cp = ClassPath.from(cl);
        for (ClassInfo ci : cp.getTopLevelClassesRecursive("soottocfg.spec")) {

            StringBuilder sb = new StringBuilder();
            sb.append(targetDir.getAbsolutePath());
            sb.append(File.separator);
            sb.append(ci.getPackageName().replace(".", File.separator));
            File outFileDir = new File(sb.toString());
            if (!outFileDir.exists() && !outFileDir.mkdirs()) {
                throw new RuntimeException("Couldn't generate dirs for " + sb.toString());
            }
            sb.append(File.separator);
            sb.append(ci.getSimpleName());
            sb.append(".class");
            File outFile = new File(sb.toString());

            try (InputStream inputStream = cl.getResourceAsStream(ci.getResourceName());
                    OutputStream outputStream = new FileOutputStream(outFile);) {
                ByteStreams.copy(inputStream, outputStream);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.diqube.build.mojo.GenerateTsMojo.java

/**
 * Scan classpath and identify and load all transitive classes that have a {@link TypeScriptProperty} annotation on
 * one of their properties.//from   ww  w  .  j  a  va 2 s  .co m
 * 
 * @return null if no classes were scanned. Otherwise map from class name to pair of loaded class and list of other
 *         class names the class depends on (only the ones whose classname is present as key in the map!).
 */
private Map<String, Pair<Class<?>, Set<String>>> findClassesWithTypeScriptAnnotation(ClassLoader ourClassLoader)
        throws MojoExecutionException {
    ClassPath classPath;
    try {
        classPath = ClassPath.from(ourClassLoader);
    } catch (IOException e) {
        throw new MojoExecutionException("Could not scan classpath", e);
    }
    Deque<String> classNamesToVisit = new LinkedList<>();
    for (String pkg : rootPackages)
        classNamesToVisit.addAll(classPath.getTopLevelClassesRecursive(pkg).stream()
                .map(classInfo -> classInfo.getName()).collect(Collectors.toList()));

    if (classNamesToVisit.isEmpty()) {
        getLog().info("No classes found.");
        return null;
    }

    getLog().debug("Found following classes in first scan: " + classNamesToVisit);

    Map<String, Pair<Class<?>, Set<String>>> typescriptClasses = new HashMap<>();
    Set<String> classesVisited = new HashSet<>();
    while (!classNamesToVisit.isEmpty()) {
        String className = classNamesToVisit.pop();
        if (!classesVisited.add(className))
            continue;

        Class<?> clazz;
        try {
            clazz = ourClassLoader.loadClass(className);
        } catch (ClassNotFoundException e) {
            getLog().warn("Could not load class " + className);
            continue;
        }

        // check valid, since the ourClassLoader must not overwrite the STOP_CLASSES.
        if (STOP_CLASSES.contains(clazz))
            continue;

        for (Pair<Field, TypeScriptProperty> p : findTypeScriptFields(clazz)) {
            Field f = p.getLeft();

            typescriptClasses.putIfAbsent(clazz.getName(), new Pair<>(clazz, new HashSet<>()));
            Set<String> dependsSet = typescriptClasses.get(clazz.getName()).getRight();

            // check valid, since the ourClassLoader must not overwrite the STOP_CLASSES.
            if (!STOP_CLASSES.contains(f.getType())) {
                Set<Class<?>> allReferencedClasses = getAllReferencedClasses(f.getGenericType());
                Set<String> allReferencedClassNames = allReferencedClasses.stream().map(c -> c.getName())
                        .collect(Collectors.toSet());
                classNamesToVisit.addAll(allReferencedClassNames);
                dependsSet.addAll(allReferencedClassNames);
            }
            classNamesToVisit.add(clazz.getSuperclass().getName());
            dependsSet.add(clazz.getSuperclass().getName());
        }
    }

    // cleanup result map, remove all the "depends on" classes that did not contain the annotation
    for (Pair<Class<?>, Set<String>> p : typescriptClasses.values()) {
        p.getRight().retainAll(typescriptClasses.keySet());
    }

    return typescriptClasses;
}

From source file:dpfmanager.conformancechecker.tiff.TiffConformanceChecker.java

/**
 * Gets autofixes.//  w  ww . j  a va 2  s .  c o m
 *
 * @return the autofixes
 */
public static ArrayList<String> getAutofixes() {
    ArrayList<String> classes = null;

    try {
        Logger.println("Loading autofixes from JAR");
        String path = "DPF Manager-jfx.jar";
        if (new File(path).exists()) {
            ZipInputStream zip = new ZipInputStream(new FileInputStream(path));
            for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
                if (!entry.isDirectory() && entry.getName().endsWith(".class")
                        && entry.getName().contains("autofixes")
                        && !entry.getName().contains("autofix.class")) {
                    if (classes == null) {
                        classes = new ArrayList<String>();
                    }
                    classes.add(entry.getName().substring(entry.getName().lastIndexOf("/") + 1)
                            .replace(".class", ""));
                }
            }
        } else {
            Logger.println("Jar not found");
        }
    } catch (Exception ex) {
        Logger.println("Error " + ex.toString());
    }

    if (classes == null) {
        Logger.println("Loading autofixes through reflection");
        try {
            //Reflections reflections = new Reflections(TiffConformanceChecker.getAutofixesClassPath(), new SubTypesScanner(false));
            //Set<Class<? extends Object>> classesSet = reflections.getSubTypesOf(Object.class);

            Class cls = Class.forName("dpfmanager.conformancechecker.tiff.TiffConformanceChecker");
            ClassLoader cll = cls.getClassLoader();
            Set<ClassPath.ClassInfo> classesInPackage = ClassPath.from(cll)
                    .getTopLevelClassesRecursive(TiffConformanceChecker.getAutofixesClassPath());

            classes = new ArrayList<String>();
            for (ClassPath.ClassInfo cl : classesInPackage) {
                if (!cl.toString().endsWith(".autofix")) {
                    classes.add(cl.toString().substring(cl.toString().lastIndexOf(".") + 1));
                }
            }
        } catch (Exception ex) {
            Logger.println("Exception getting classes");
        }
    }

    if (classes == null) {
        Logger.println("Autofixes loaded manually");
        classes = new ArrayList<String>();
        classes.add(clearPrivateData.class.toString());
        classes.add(makeBaselineCompliant.class.toString());
    }

    Logger.println("Found " + classes.size() + " classes:");
    for (String cl : classes) {
        Logger.println(cl);
    }

    return classes;
}

From source file:com.facebook.buck.cli.Main.java

private void loadListenersFromBuckConfig(ImmutableList.Builder<BuckEventListener> eventListeners,
        ProjectFilesystem projectFilesystem, BuckConfig config) {
    final ImmutableSet<String> paths = config.getListenerJars();
    if (paths.isEmpty()) {
        return;//from  w  w  w. ja v a  2 s. c  o  m
    }

    URL[] urlsArray = new URL[paths.size()];
    try {
        int i = 0;
        for (String path : paths) {
            String urlString = "file://" + projectFilesystem.getAbsolutifier().apply(Paths.get(path));
            urlsArray[i] = new URL(urlString);
            i++;
        }
    } catch (MalformedURLException e) {
        throw new HumanReadableException(e.getMessage());
    }

    // This ClassLoader is disconnected to allow searching the JARs (and just the JARs) for classes.
    ClassLoader isolatedClassLoader = URLClassLoader.newInstance(urlsArray, null);

    ImmutableSet<ClassPath.ClassInfo> classInfos;
    try {
        ClassPath classPath = ClassPath.from(isolatedClassLoader);
        classInfos = classPath.getTopLevelClasses();
    } catch (IOException e) {
        throw new HumanReadableException(e.getMessage());
    }

    // This ClassLoader will actually work, because it is joined to the parent ClassLoader.
    URLClassLoader workingClassLoader = URLClassLoader.newInstance(urlsArray);

    for (ClassPath.ClassInfo classInfo : classInfos) {
        String className = classInfo.getName();
        try {
            Class<?> aClass = Class.forName(className, true, workingClassLoader);
            if (BuckEventListener.class.isAssignableFrom(aClass)) {
                BuckEventListener listener = aClass.asSubclass(BuckEventListener.class).newInstance();
                eventListeners.add(listener);
            }
        } catch (ReflectiveOperationException e) {
            throw new HumanReadableException("Error loading event listener class '%s': %s: %s", className,
                    e.getClass(), e.getMessage());
        }
    }
}

From source file:org.jivesoftware.openfire.XMPPServer.java

private void scanForSystemPropertyClasses() {

    try {// w  ww  . j  av  a  2  s  .co m
        final Set<ClassPath.ClassInfo> classesInPackage = ClassPath.from(getClass().getClassLoader())
                .getTopLevelClassesRecursive("org.jivesoftware.openfire");
        for (final ClassPath.ClassInfo classInfo : classesInPackage) {
            final String className = classInfo.getName();
            if (!CLASSES_TO_EXCLUDE.contains(className)) {
                try {
                    final Class<?> clazz = classInfo.load();
                    final Field[] fields = clazz.getDeclaredFields();
                    for (final Field field : fields) {
                        if (field.getType().equals(SystemProperty.class)) {
                            try {
                                field.setAccessible(true);
                                logger.info("Accessing SystemProperty field {}#{}", className, field.getName());
                                field.get(null);
                            } catch (final Throwable t) {
                                logger.warn("Unable to access field {}#{}", className, field.getName(), t);
                            }
                        }
                    }
                } catch (final Throwable t) {
                    logger.warn("Unable to load class {}", className, t);
                }
            }
        }
    } catch (final Throwable t) {
        logger.warn("Unable to scan classpath for SystemProperty classes", t);
    }
}

From source file:com.prepaird.objectgraphdb.ObjectGraphDb.java

private static Collection<Class> getClassCollection(String packageName) throws IOException {
    Collection<Class> coll = new ArrayList<>();
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    for (final ClassPath.ClassInfo classInfo : ClassPath.from(loader)
            .getTopLevelClassesRecursive(packageName)) {
        coll.add(classInfo.load());//from  w  w w.j a v  a  2s  .  c  o m
    }

    return coll;
}