Search in sources :

Example 16 with ClassPath

use of com.google.common.reflect.ClassPath in project spf4j by zolyfarkas.

the class Scanner method findUsages.

public static List<Invocation> findUsages(final String packageName, final Set<Method> invokedMethods) throws IOException {
    final ClassLoader cl = ClassLoader.getSystemClassLoader();
    ClassPath cp = ClassPath.from(cl);
    ImmutableSet<ClassPath.ClassInfo> classes = cp.getAllClasses();
    List<Invocation> result = new ArrayList();
    for (ClassPath.ClassInfo info : classes) {
        if (info.getName().startsWith(packageName)) {
            result.addAll(findUsages(cl, info.getResourceName(), invokedMethods));
        }
    }
    return result;
}
Also used : ClassPath(com.google.common.reflect.ClassPath) ArrayList(java.util.ArrayList)

Example 17 with ClassPath

use of com.google.common.reflect.ClassPath in project buck by facebook.

the class Main method loadListenersFromBuckConfig.

private void loadListenersFromBuckConfig(ImmutableList.Builder<BuckEventListener> eventListeners, ProjectFilesystem projectFilesystem, BuckConfig config) {
    final ImmutableSet<String> paths = config.getListenerJars();
    if (paths.isEmpty()) {
        return;
    }
    URL[] urlsArray = new URL[paths.size()];
    try {
        int i = 0;
        for (String path : paths) {
            String urlString = "file://" + projectFilesystem.resolve(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());
        }
    }
}
Also used : ClassPath(com.google.common.reflect.ClassPath) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) BuckEventListener(com.facebook.buck.event.BuckEventListener) URL(java.net.URL) HumanReadableException(com.facebook.buck.util.HumanReadableException) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader)

Example 18 with ClassPath

use of com.google.common.reflect.ClassPath in project checkstyle by checkstyle.

the class CheckUtil method getCheckstyleChecks.

/**
     * 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)
     */
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;
}
Also used : ClassPath(com.google.common.reflect.ClassPath) HashSet(java.util.HashSet)

Example 19 with ClassPath

use of com.google.common.reflect.ClassPath in project atlas-checks by osmlab.

the class CheckResourceLoader method loadChecks.

/**
 * Loads checks that are enabled by some other means, defined by {@code isEnabled}
 *
 * @param isEnabled
 *            {@link Predicate} used to determine if a check is enabled
 * @param configuration
 *            {@link Configuration} used to loadChecks {@link CheckResourceLoader}
 * @param <T>
 *            check type
 * @return a {@link Set} of checks
 */
@SuppressWarnings("unchecked")
public <T extends Check> Set<T> loadChecks(final Predicate<Class> isEnabled, final Configuration configuration) {
    final Set<T> checks = new HashSet<>();
    final Time time = Time.now();
    try {
        final ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
        packages.forEach(packageName -> classPath.getTopLevelClassesRecursive(packageName).forEach(classInfo -> {
            final Class<?> checkClass = classInfo.load();
            if (checkType.isAssignableFrom(checkClass) && !Modifier.isAbstract(checkClass.getModifiers()) && isEnabled.test(checkClass)) {
                try {
                    Object check;
                    try {
                        check = checkClass.getConstructor(Configuration.class).newInstance(configuration);
                    } catch (final InvocationTargetException oops) {
                        throw new CoreException("Unable to create a configurable instance of {}", checkClass.getSimpleName(), oops);
                    } catch (final NoSuchMethodException oops) {
                        check = checkClass.newInstance();
                    }
                    if (check != null) {
                        checks.add((T) check);
                    }
                } catch (final ClassCastException | InstantiationException | IllegalAccessException oops) {
                    logger.error("Failed to instantiate {}, ignoring. Reason: {}", checkClass.getName(), oops.getMessage());
                }
            }
        }));
    } catch (final IOException oops) {
        throw new CoreException("Failed to discover {} classes on classpath", checkType.getSimpleName());
    }
    logger.info("Loaded {} {} in {}", checks.size(), checkType.getSimpleName(), time.elapsedSince());
    return checks;
}
Also used : Logger(org.slf4j.Logger) Predicate(java.util.function.Predicate) CoreException(org.openstreetmap.atlas.exception.CoreException) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) HashSet(java.util.HashSet) List(java.util.List) Iterables(org.openstreetmap.atlas.utilities.collections.Iterables) Configuration(org.openstreetmap.atlas.utilities.configuration.Configuration) Modifier(java.lang.reflect.Modifier) Map(java.util.Map) Time(org.openstreetmap.atlas.utilities.time.Time) ClassPath(com.google.common.reflect.ClassPath) Collections(java.util.Collections) MultiMap(org.openstreetmap.atlas.utilities.maps.MultiMap) ClassPath(com.google.common.reflect.ClassPath) Configuration(org.openstreetmap.atlas.utilities.configuration.Configuration) Time(org.openstreetmap.atlas.utilities.time.Time) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) CoreException(org.openstreetmap.atlas.exception.CoreException) HashSet(java.util.HashSet)

Example 20 with ClassPath

use of com.google.common.reflect.ClassPath in project java-common-lib by sosy-lab.

the class OptionCollector method collectOptions.

/**
 * This function collects options from all classes and writes them to the output.
 */
private void collectOptions(PrintStream out) {
    ClassPath classPath;
    try {
        classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
    } catch (IOException e) {
        errorMessages.add("INFO: Could not scan class path for getting Option annotations: " + e.getMessage());
        return;
    }
    if (includeLibraryOptions) {
        copyOptionFilesToOutput(classPath, out);
    }
    // We want a deterministic ordering for cases where the same option is declared multiple times.
    Comparator<AnnotationInfo> annotationComparator = Comparator.comparing(a -> a.owningClass().getName());
    OptionPlainTextWriter outputWriter = new OptionPlainTextWriter(verbose, out);
    // Collect and dump all options
    getClassesWithOptions(classPath).flatMap(this::collectOptions).collect(groupingBySorted(AnnotationInfo::name, Ordering.natural(), annotationComparator)).values().forEach(outputWriter::writeOption);
}
Also used : ClassPath(com.google.common.reflect.ClassPath) IOException(java.io.IOException)

Aggregations

ClassPath (com.google.common.reflect.ClassPath)26 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 HashSet (java.util.HashSet)8 ClassInfo (com.google.common.reflect.ClassPath.ClassInfo)5 URL (java.net.URL)3 List (java.util.List)3 ReflectionException (io.openems.api.exception.ReflectionException)2 URLClassLoader (java.net.URLClassLoader)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Set (java.util.Set)2 Predicate (java.util.function.Predicate)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 BuckEventListener (com.facebook.buck.event.BuckEventListener)1 HumanReadableException (com.facebook.buck.util.HumanReadableException)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Function (com.google.common.base.Function)1 Collections2 (com.google.common.collect.Collections2)1