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.axelor.common.reflections.ClassScanner.java

private void scan() throws IOException {
    ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    List<Future<?>> futures = Lists.newArrayList();
    Set<ClassInfo> infos = Sets.newHashSet();

    if (packages.isEmpty()) {
        infos = ClassPath.from(loader).getTopLevelClasses();
    } else {//from w  ww .j a  va 2  s .  c  o m
        for (String pkg : packages) {
            infos.addAll(ClassPath.from(loader).getTopLevelClassesRecursive(pkg));
        }
    }

    try {
        for (final ClassInfo info : infos) {
            futures.add(executor.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    scan(info.getName());
                    return info.getName();
                }
            }));
        }

        for (Future<?> future : futures) {
            try {
                future.get();
            } catch (Exception e) {
            }
        }
    } finally {
        executor.shutdown();
    }
}

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

private synchronized static void initialize() {
    if (whitelistedSerializableClassNames != null)
        return;/*from   ww w. j av 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.avatarproject.core.ability.BaseAbilityProvider.java

/**
 * Register all the abilities//from   www.j  a  va 2  s  .  c o  m
 * @param plugin JavaPlugin that the abilities belong to
 * @param packageName Package that the plugin belongs in
 */
public static void registerAbilities(JavaPlugin plugin, String packageName) {
    ABILITIES.clear();
    ClassLoader loader = plugin.getClass().getClassLoader();
    try {
        ClassPath.from(loader).getAllClasses().stream().filter(info -> {
            if (!info.getPackageName().startsWith(packageName)) {
                return false;
            }
            Class<?> c = info.load();
            if (!AbilityProvider.class.isAssignableFrom(c) || c.isInterface()
                    || Modifier.isAbstract(c.getModifiers())) {
                return false;
            }
            return true;
        }).forEach(info -> {
            Class<?> c = info.load();
            try {
                AbilityAPI.get().getRegistry().register((AbilityProvider<?>) c.newInstance());
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.diqube.tool.im.IdentityToolFunction.java

private Map<String, Pair<AbstractActualIdentityToolFunction, IsActualIdentityToolFunction>> loadActualFunctions() {
    try {/*from  ww w  .  ja v a  2  s .  co  m*/
        Collection<ClassInfo> classInfos = ClassPath.from(getClass().getClassLoader())
                .getTopLevelClassesRecursive(BASE_PKG);

        Map<String, Pair<AbstractActualIdentityToolFunction, IsActualIdentityToolFunction>> toolFunctions = new HashMap<>();

        for (ClassInfo classInfo : classInfos) {
            Class<?> clazz = classInfo.load();
            IsActualIdentityToolFunction isActualIdentityToolFunctionAnnotation = clazz
                    .getAnnotation(IsActualIdentityToolFunction.class);
            if (isActualIdentityToolFunctionAnnotation != null) {
                AbstractActualIdentityToolFunction functionInstance = (AbstractActualIdentityToolFunction) clazz
                        .newInstance();

                toolFunctions.put(isActualIdentityToolFunctionAnnotation.identityFunctionName(),
                        new Pair<>(functionInstance, isActualIdentityToolFunctionAnnotation));
            }
        }

        return toolFunctions;
    } catch (IOException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wisdom.test.internals.ProbeBundleMaker.java

private static Jar[] computeClassPath() throws IOException {
    List<Jar> list = new ArrayList<>();
    File tests = new File(TEST_CLASSES);

    if (tests.isDirectory()) {
        list.add(new Jar(".", tests));
    }//from w  w w.ja  va 2  s  .  co m

    ClassPath classpath = ClassPath.from(ProbeBundleMaker.class.getClassLoader());
    list.add(new JarFromClassloader(classpath));

    Jar[] cp = new Jar[list.size()];
    list.toArray(cp);

    return cp;

}

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

/**
 * Gets checkstyle's modules in the given package recursively.
 * @param packageName the package name to use
 * @param loader the class loader used to load Checkstyle package name
 * @return the set of checkstyle's module classes
 * @throws IOException if the attempt to read class path resources failed
 * @see ModuleReflectionUtils#isCheckstyleModule(Class)
 *///from ww  w  .ja v  a2  s .  c  o m
private static Set<Class<?>> getCheckstyleModulesRecursive(String packageName, ClassLoader loader)
        throws IOException {
    final ClassPath classPath = ClassPath.from(loader);
    return classPath.getTopLevelClassesRecursive(packageName).stream().map(ClassPath.ClassInfo::load)
            .filter(ModuleReflectionUtils::isCheckstyleModule)
            .filter(cls -> !cls.getCanonicalName()
                    .startsWith("com.puppycrawl.tools.checkstyle.internal.testmodules"))
            .filter(cls -> !cls.getCanonicalName()
                    .startsWith("com.puppycrawl.tools.checkstyle.packageobjectfactory"))
            .collect(Collectors.toSet());
}

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 {// w  w  w  . ja  v a2 s. co 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:com.puppycrawl.tools.checkstyle.internal.CheckUtil.java

/**
 * Gets all checkstyle's modules./*w ww.j  a v a 2 s  .c o  m*/
 * @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:org.linagora.linshare.core.notifications.emails.impl.EmailBuilder.java

private void initSupportedTypes() {
    Date date_before = new Date();
    if (supportedClass == null) {
        supportedClass = Lists.newArrayList();
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {/*from  w w  w  .  j a  va  2  s. c o  m*/
            for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) {
                if (info.getName().startsWith(MAIL_DTO_PATH)) {
                    final Class<?> clazz = info.load();
                    supportedClass.add(clazz.getCanonicalName());
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    if (logger.isTraceEnabled()) {
        Date date_after = new Date();
        logger.trace("diff : " + String.valueOf(date_after.getTime() - date_before.getTime()));
    }
}

From source file:com.px100systems.data.core.DatabaseStorage.java

@Override
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
    if (tenantLoader != null)
        tenantLoader.setDatabase(this);

    configuredEntities = new HashMap<String, Class<? extends Entity>>();

    try {/* w  w  w . j  ava 2s .co  m*/
        ClassPath cp = ClassPath.from(getClass().getClassLoader());
        for (String p : baseEntityPackages)
            for (ClassPath.ClassInfo cli : cp.getTopLevelClassesRecursive(p)) {
                Class<?> eClass = Class.forName(cli.getName());
                if (!Modifier.isAbstract(eClass.getModifiers()) && Entity.class.isAssignableFrom(eClass)) {
                    Class<? extends Entity> entityClass = (Class<? extends Entity>) eClass;
                    String name = entityClass.getSimpleName();
                    Class<? extends Entity> cls = configuredEntities.get(name);
                    if (cls != null) {
                        if (cls.getName().equals(entityClass.getName()))
                            continue;
                        throw new RuntimeException("Duplicate entities in different packages: " + name);
                    }
                    configuredEntities.put(name, entityClass);
                    SerializationDefinition.register(entityClass);
                }
            }
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }

    SerializationDefinition.lock();

    runtimeStorage.getProvider().start();

    List<BaseTenantConfig> tenants = new ArrayList<BaseTenantConfig>();
    if (tenantLoader != null)
        tenants = tenantLoader.load();

    List<EntityInfo> entities = new ArrayList<>();
    for (Class<? extends Entity> entityClass : getConfiguredEntities().values()) {
        Map<String, Class<?>> indexes = Entity.indexes(entityClass);
        List<CompoundIndexDescriptor> compoundIndexes = Entity.compoundIndexes(entityClass);
        if (tenants.isEmpty())
            entities.add(new EntityInfo(entityClass, 0, Entity.unitFromClass(entityClass, 0), indexes,
                    compoundIndexes));
        else
            for (BaseTenantConfig tenant : tenants)
                entities.add(new EntityInfo(entityClass, tenant.getId(),
                        Entity.unitFromClass(entityClass, tenant.getId()), indexes, compoundIndexes));
    }

    init(entities, initializer != null);

    if (initializer != null) {
        initializer.initialize(new Transaction(this, 0));
        log.info("Initialized the database");
    }
}