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

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

Introduction

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

Prototype

public ImmutableSet<ClassInfo> getTopLevelClassesRecursive(String packageName) 

Source Link

Document

Returns all top level classes whose package name is packageName or starts with packageName followed by a '.'.

Usage

From source file:io.fabric8.kubernetes.codegen.GenerateKindToClassMap.java

public static void main(String[] args) throws Exception {
    ClassPath classPath = ClassPath.from(GenerateKindToClassMap.class.getClassLoader());
    SortedMap<String, String> sortedMap = new TreeMap<>();
    String[] topLevelPackages = { "io.fabric8.kubernetes.api.model", "io.fabric8.openshift.api.model" };
    for (String topLevelPackage : topLevelPackages) {
        ImmutableSet<ClassPath.ClassInfo> classInfos = classPath.getTopLevelClassesRecursive(topLevelPackage);
        for (ClassPath.ClassInfo classInfo : classInfos) {
            String simpleName = classInfo.getSimpleName();
            if (simpleName.endsWith("Builder") || simpleName.endsWith("Fluent")) {
                continue;
            }/* ww  w . j  ava  2 s  .  c o  m*/
            sortedMap.put(simpleName, classInfo.getName());
        }
    }
    String basedir = System.getProperty("basedir", ".");
    File file = new File(basedir,
            "../kubernetes-api/src/main/java/io/fabric8/kubernetes/api/support/KindToClassMapping.java");
    file.getParentFile().mkdirs();
    System.out.println("Generating " + file);

    SortedSet<String> classNames = new TreeSet<>(sortedMap.values());
    try (PrintWriter writer = new PrintWriter(new FileWriter(file))) {
        Set<Map.Entry<String, String>> entries = sortedMap.entrySet();
        writer.println("/**\n" + " * Licensed to the Apache Software Foundation (ASF) under one or more\n"
                + " * contributor license agreements.  See the NOTICE file distributed with\n"
                + " * this work for additional information regarding copyright ownership.\n"
                + " * The ASF licenses this file to You under the Apache License, Version 2.0\n"
                + " * (the \"License\"); you may not use this file except in compliance with\n"
                + " * the License.  You may obtain a copy of the License at\n" + " * <p/>\n"
                + " * http://www.apache.org/licenses/LICENSE-2.0\n" + " * <p/>\n"
                + " * Unless required by applicable law or agreed to in writing, software\n"
                + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
                + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
                + " * See the License for the specific language governing permissions and\n"
                + " * limitations under the License.\n" + " */\n"
                + "package io.fabric8.kubernetes.api.support;\n" + "\n");
        for (String className : classNames) {
            writer.println("import " + className + ";");
        }

        writer.println("\n" + "import java.util.HashMap;\n" + "import java.util.Map;\n" + "\n" + "/**\n"
                + " * Maps the Kubernetes kinds to the Jackson DTO classes\n" + " */\n"
                + "public class KindToClassMapping {\n"
                + "    private static Map<String,Class<?>> map = new HashMap<>();\n" + "\n" + "    static {");

        for (Map.Entry<String, String> entry : entries) {
            String kind = entry.getKey();
            String className = entry.getValue();
            writer.println("        map.put(\"" + kind + "\", " + kind + ".class);");
        }

        writer.println("    }\n" + "\n" + "    public static Map<String,Class<?>> getKindToClassMap() {\n"
                + "        return map;\n" + "    }\n" + "}\n");
    }
}

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
}

From source file:l2server.util.ClassPathUtil.java

public static <T> List<Class<T>> getAllClassesExtending(String packageName, Class<T> targetClass)
        throws IOException {
    final ClassPath classPath = ClassPath.from(ClassLoader.getSystemClassLoader());
    //@formatter:off
    return classPath.getTopLevelClassesRecursive(packageName).stream().map(ClassInfo::load)
            .filter(clazz -> targetClass.isAssignableFrom(clazz))
            .filter(clazz -> !Modifier.isAbstract(clazz.getModifiers()))
            .filter(clazz -> !Modifier.isInterface(clazz.getModifiers())).map(clazz -> (Class<T>) clazz)
            .collect(Collectors.toList());
    //@formatter:on
}

From source file:com.flipkart.poseidon.helper.ClassPathHelper.java

public static Set<ClassPath.ClassInfo> getPackageClasses(ClassLoader classLoader, List<String> packagesToScan)
        throws IOException {
    ClassPath classpath = ClassPath.from(classLoader);
    Set<ClassPath.ClassInfo> classInfos = new HashSet<>();
    for (String basePackage : packagesToScan) {
        classInfos.addAll(classpath.getTopLevelClassesRecursive(basePackage));
    }//from  w w w  .j  av a2  s  .co m
    return classInfos;
}

From source file:org.opendaylight.odlparent.featuretest.ReflectionUtil.java

/**
 * Returns all classes in the named package, and its sub-packages.
 *//*w w  w . j a va2  s . c  o m*/
public static Stream<Class<?>> getClasses(ClassLoader classLoader, String packageName) {
    try {
        ClassPath classPath = ClassPath.from(classLoader);
        // inspired by https://github.com/vorburger/ch.vorburger.minecraft.osgi/blob/master/ch.vorburger.minecraft.osgi/src/main/java/ch/vorburger/osgi/embedded/PackagesBuilder.java
        return classPath.getTopLevelClassesRecursive(packageName).stream().map(ClassPath.ClassInfo::load)
                // to include all inner classes, including anonymous inner classes:
                .flatMap(ReflectionUtil::getDeclaredAndAnonymousInnerClass);
    } catch (IOException e) {
        throw new IllegalStateException("ClassPath.from(classLoader) failed", e);
    }
}

From source file:org.apache.ambari.server.cleanup.ClasspathScannerUtils.java

/**
 * Scans the classpath for classes based on the provided arguments
 *
 * @param packageName the package to be scanned
 * @param exclusions  a list with classes excluded from the result
 * @param selectors   a list with annotation and interface classes that identify classes to be found (lookup criteria)
 * @return a list of classes from the classpath that match the lookup criteria
 *//*w  ww .ja  v a2 s .c o  m*/
public static Set<Class> findOnClassPath(String packageName, List<Class> exclusions, List<Class> selectors) {

    Set<Class> bindingSet = new HashSet<>();
    try {
        ClassPath classpath = ClassPath.from(ClasspathScannerUtils.class.getClassLoader());
        LOGGER.info("Checking package [{}] for binding candidates.", packageName);

        for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClassesRecursive(packageName)) {
            Class candidate = classInfo.load();

            if (exclusions.contains(candidate)) {
                LOGGER.debug("Candidate [{}] is excluded excluded.", candidate);
                continue;
            }

            if (isEligible(candidate, selectors)) {
                LOGGER.info("Found class [{}]", candidate);
                bindingSet.add(candidate);
            } else {
                LOGGER.debug("Candidate [{}] doesn't match.", candidate);
            }
        }

    } catch (IOException e) {
        LOGGER.error("Failure during configuring JUICE bindings.", e);
        throw new IllegalArgumentException(e);
    }
    return bindingSet;
}

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  w w w .j  a  va  2  s .c om*/
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.flipkart.masquerade.util.Helper.java

public static Set<ClassPath.ClassInfo> getPackageClasses(ClassLoader classLoader, List<String> packagesToScan)
        throws IOException {
    ClassPath classpath = ClassPath.from(classLoader);
    Set<ClassPath.ClassInfo> classDescriptions = new HashSet<>();
    for (String basePackage : packagesToScan) {
        classDescriptions.addAll(classpath.getTopLevelClassesRecursive(basePackage));
    }/*from w  ww. j av a  2 s.co  m*/
    return classDescriptions;
}

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

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

    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: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 w w  . ja va2 s .c  om
            set.addAll(Arrays.asList(c.getDeclaredClasses()));
            loadAnonymousInnerClasses(cl, set, c);
        }
    }
    return set;
}