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.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtils.java

/**
 * Gets checkstyle's modules (directly, not recursively) in the given packages.
 * @param packages the collection of package names to use
 * @param loader the class loader used to load Checkstyle package names
 * @return the set of checkstyle's module classes
 * @throws IOException if the attempt to read class path resources failed
 * @see #isCheckstyleModule(Class)/*from   w w  w . j  av a 2s.c o m*/
 */
public static Set<Class<?>> getCheckstyleModules(Collection<String> packages, ClassLoader loader)
        throws IOException {
    final ClassPath classPath = ClassPath.from(loader);
    return packages.stream().flatMap(pkg -> classPath.getTopLevelClasses(pkg).stream())
            .map(ClassPath.ClassInfo::load).filter(ModuleReflectionUtils::isCheckstyleModule)
            .collect(Collectors.toSet());
}

From source file:com.vmware.photon.controller.common.xenon.migration.MigrationUtils.java

/**
 * This method searches the class path to identify each class definition that extends {@link ServiceDocument}
 * that is part of the Photon Controller code base.
 * It selects all {@link ServiceDocument} with the {@link MigrateDuringUpgrade} annotation and record the necessary
 * upgrade information./*w  w w. j av  a 2s .c  om*/
 *
 * @return list of {@link UpgradeInfromation} objects describing each service document that needs to be migrated
 * during upgrade.
 */
@SuppressWarnings("unchecked")
public static List<UpgradeInformation> findAllUpgradeServices() {
    if (cachedList != null) {
        return cachedList;
    }
    List<UpgradeInformation> infoEntries = new ArrayList<>();
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    ClassPath classPath;
    try {
        classPath = ClassPath.from(cl);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    for (ClassInfo classFile : classPath.getAllClasses()) {
        if (classFile.getName().contains(PHOTON_CONTROLLER_PACKAGE)) {
            Class<?> type = classFile.load();
            if (type.getSuperclass() != null && type.getSuperclass() == ServiceDocument.class) {
                for (Annotation a : type.getAnnotations()) {
                    if (a.annotationType() == MigrateDuringUpgrade.class) {
                        MigrateDuringUpgrade u = (MigrateDuringUpgrade) a;

                        UpgradeInformation info = new UpgradeInformation(u.sourceFactoryServicePath(),
                                u.destinationFactoryServicePath(), u.serviceName(),
                                u.transformationServicePath(), (Class<? extends ServiceDocument>) type);

                        infoEntries.add(info);
                    }
                }
            }
        }
    }
    cachedList = infoEntries;
    return infoEntries;
}

From source file:com.art4ul.jcoon.handlers.AnnotationProcessor.java

private AnnotationProcessor() {
    try {/*  w  ww .  j av a2s  .c  o m*/
        ClassPath classPath = ClassPath.from(AnnotationProcessor.class.getClassLoader());
        Set<ClassPath.ClassInfo> classInfo = classPath
                .getTopLevelClasses(AnnotationProcessor.class.getPackage().getName());
        for (ClassPath.ClassInfo info : classInfo) {
            Class<?> clazz = info.load();
            if (ParamAnnotationHandler.class.isAssignableFrom(clazz) && !clazz.isInterface()) {
                Class<? extends ParamAnnotationHandler> handlerClass = (Class<? extends ParamAnnotationHandler>) clazz;
                ProcessAnnotation annotationHandler = handlerClass.getAnnotation(ProcessAnnotation.class);
                if (annotationHandler != null) {
                    if (handlerClass.isAnnotationPresent(Before.class)) {
                        paramAnnotationBeforeHandlerMap.put(annotationHandler.value(),
                                handlerClass.newInstance());
                    } else if (handlerClass.isAnnotationPresent(After.class)) {
                        paramAnnotationAfterHandlerMap.put(annotationHandler.value(),
                                handlerClass.newInstance());
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new InitializationException("Exception during creating new instance of ParamAnnotationHandler");
    }
}

From source file:org.jmingo.el.ELEngineFactory.java

private static ELEngine getElEngineFromPackage(String packageName) throws ELException {
    ELEngine elEngine;//from   ww w. j av a 2 s  . co m
    Class<?> elClass = null;
    Set<Class<?>> candidates = Sets.newHashSet();
    try {
        Set<ClassPath.ClassInfo> classes = ClassPath.from(ELEngine.class.getClassLoader())
                .getTopLevelClassesRecursive(packageName);
        classes.forEach(classInfo -> {
            try {
                if (!CLASS_EXCLUDE.contains(classInfo.getName())) {
                    Class<?> clazz = Class.forName(classInfo.getName());
                    if (ELEngine.class.isAssignableFrom(clazz)) {
                        candidates.add(clazz);
                    }
                }
            } catch (ClassNotFoundException | NoClassDefFoundError e) {
                throw new ELException(e);
            }

        });
        if (candidates.size() == 0) {
            return null;
        }
        if (candidates.size() > 1) {
            throw new ELException(
                    "ELEngine implementations conflict: there are multiple ELEngine implementations in the application classpath, but must be only one. "
                            + Iterables.transform(candidates, Class::getName));
        }

        elClass = candidates.iterator().next();
        return (ELEngine) elClass.newInstance();

    } catch (IOException e) {
        throw new ELException("failed to read classes from the package: " + packageName, e);
    } catch (InstantiationException e) {
        throw new ELException("failed to create instance of " + elClass, e);
    } catch (IllegalAccessException e) {
        throw new ELException("Security error", e);
    }
}

From source file:me.finalchild.nashornbukkit.util.BukkitImporter.java

public static Map<String, ClassPath.ClassInfo> getTypes(boolean cache) {
    if (typesCache != null) {
        return typesCache;
    }//from  w  w w  . j a  va  2s  .c  o m

    ClassPath classpath;
    try {
        classpath = ClassPath.from(NashornBukkit.class.getClassLoader());
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    ImmutableSet<ClassPath.ClassInfo> result = classpath.getTopLevelClassesRecursive("org.bukkit");
    Map<String, ClassPath.ClassInfo> types = result.stream()
            .filter(e -> !(e.getName().startsWith("org.bukkit.craftbukkit")))
            .filter(e -> !(e.getSimpleName().equals("package-info")))
            .collect(Collectors.toMap(ClassPath.ClassInfo::getSimpleName, Function.identity(), (a, b) -> {
                NashornBukkit.getInstance().getLogger()
                        .info("Duplicate class name: " + a.getName() + " and " + b.getName());
                return a;
            }));

    if (cache) {
        typesCache = types;
    }
    return Collections.unmodifiableMap(types);
}

From source file:com.softwarewerke.htdbc.App.java

@Override
public Set getSingletons() {

    Logger log = Logger.getLogger(getClass());

    Set set = new HashSet();

    ClassPath cp;//from   w  ww.j  a v  a 2  s  .  c o  m
    try {
        cp = ClassPath.from(getClass().getClassLoader());
    } catch (IOException ex) {
        log.fatal(ex);
        return set;
    }
    String p = getClass().getPackage().getName();

    for (ClassPath.ClassInfo n : cp.getAllClasses()) {
        if (!n.getPackageName().startsWith(p)) {
            continue;
        }
        try {
            Class cl = n.load();

            if (cl.getAnnotation(Path.class) == null) {
                continue;
            }
            if (cl.getAnnotation(Singleton.class) == null) {
                continue;
            }
            if (!Main.isDevelopment() && cl.getAnnotation(IsDev.class) != null) {
                continue;
            }
            set.add(cl.newInstance());
        } catch (ClassFormatError ignore) {
        } catch (Exception ex) {
            log.error(ex);
        }
    }

    set.add(new AppException());

    return set;
}

From source file:org.diqube.thrift.base.services.DiqubeThriftServiceInfoManager.java

@PostConstruct
public void initialize() {
    annotationByServiceInterface = new HashMap<>();

    ImmutableSet<ClassInfo> classInfos;
    try {/*from  www  .  jav a2  s  . c  o  m*/
        classInfos = ClassPath.from(DiqubeThriftServiceInfoManager.class.getClassLoader())
                .getTopLevelClassesRecursive(BASE_PKG);
    } catch (IOException e) {
        throw new RuntimeException("Could not parse ClassPath.");
    }

    for (ClassInfo classInfo : classInfos) {
        Class<?> clazz = classInfo.load();

        DiqubeThriftService annotation = clazz.getAnnotation(DiqubeThriftService.class);
        if (annotation != null)
            annotationByServiceInterface.put(annotation.serviceInterface(),
                    new DiqubeThriftServiceInfo<>(annotation));
    }
    logger.info("Found {} diqube services in {} scanned classes.", annotationByServiceInterface.size(),
            classInfos.size());
}

From source file:hellfirepvp.astralsorcery.core.transform.AstralPatchTransformer.java

private int loadClassPatches() throws IOException {
    ImmutableSet<ClassPath.ClassInfo> classes = ClassPath.from(Thread.currentThread().getContextClassLoader())
            .getTopLevelClassesRecursive(PATCH_PACKAGE);
    List<Class> patchClasses = new LinkedList<>();
    for (ClassPath.ClassInfo info : classes) {
        if (info.getName().startsWith(PATCH_PACKAGE)) {
            patchClasses.add(info.load());
        }//from  ww  w.j a  va2 s .c  o  m
    }
    int load = 0;
    for (Class patchClass : patchClasses) {
        if (ClassPatch.class.isAssignableFrom(patchClass) && !Modifier.isAbstract(patchClass.getModifiers())) {
            try {
                ClassPatch patch = (ClassPatch) patchClass.newInstance();
                if (!availablePatches.containsKey(patch.getClassName())) {
                    availablePatches.put(patch.getClassName(), new LinkedList<>());
                }
                availablePatches.get(patch.getClassName()).add(patch);
                load++;
            } catch (Exception exc) {
                throw new IllegalStateException("Could not load ClassPatch: " + patchClass.getSimpleName(),
                        exc);
            }
        }
    }
    return load;
}

From source file:tk.vigaro.helix.config.ConfigurationEsperNet.java

public ConfigurationEsperNet() throws IllegalAccessException, InstantiationException, IOException {
    this.setName("true".equals(System.getProperty("helix.isDebug"))
            ? Helix.properties.getProperty("irc.nickname") + "|debug"
            : Helix.properties.getProperty("irc.nickname"));
    this.setFinger("VBot");
    this.setVersion("VBot");
    this.setRealName("VBot");
    this.setAutoNickChange(true);
    this.setLogin(Helix.properties.getProperty("irc.nickserv.login"));
    this.setNickservPassword(Helix.properties.getProperty("irc.nickserv.pw"));
    this.setServer("irc.esper.net", 6697);
    this.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates());
    this.setAutoReconnect(true);
    JSONArray chans = new JSONArray(Helix.properties.getProperty("irc.channels"));
    for (int i = 0; i < chans.length(); i++)
        this.addAutoJoinChannel(chans.getString(i));
    this.setListenerManager(Helix.backgroundListenerManager);
    ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
    for (ClassPath.ClassInfo classInfo : classPath.getTopLevelClasses("tk.vigaro.helix.listener")) {
        this.addListener(((Class<? extends ListenerAdapter>) classInfo.load()).newInstance());
    }/*from   w  w  w  .  j a  va2 s.c o m*/
    for (ClassPath.ClassInfo classInfo : classPath.getTopLevelClasses("tk.vigaro.helix.backgroundlistener")) {
        Helix.backgroundListenerManager
                .addListener(((Class<? extends ListenerAdapter>) classInfo.load()).newInstance(), true);
    }
}

From source file:l2server.util.ClassPathUtil.java

public static List<Method> getAllMethodsAnnotatedWith(String packageName,
        Class<? extends Annotation> annotationClass) throws IOException {
    final ClassPath classPath = ClassPath.from(ClassLoader.getSystemClassLoader());
    //@formatter:off
    return classPath.getTopLevelClassesRecursive(packageName).stream().map(ClassInfo::load)
            .flatMap(clazz -> Arrays.stream(clazz.getDeclaredMethods()))
            .filter(method -> method.isAnnotationPresent(annotationClass)).collect(Collectors.toList());
    //@formatter:on
}