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:luca.plugins.cmd.utils.CmdListGenerator.java

public static void main(String[] args) {
    List<CustomCommand> commands = new ArrayList<>();
    try {//w ww  .  j  a  v a 2s .  c o  m
        for (ClassPath.ClassInfo info : ClassPath.from(ClassLoader.getSystemClassLoader())
                .getTopLevelClasses("luca.plugins.cmd.commands")) {
            CustomCommand cmd = (CustomCommand) info.load().getConstructor().newInstance();
            commands.add(cmd);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    StringBuilder sb = new StringBuilder(HEADER);
    commands.forEach(c -> sb.append(String.format(ROW,
            c.getName() + (c.getUsage().isEmpty() ? "" : " " + c.getUsage().replace("<", "\\<")),
            c.getDescription(), c.getPermission(),
            c.getAliases().length == 0 ? "" : Joiner.on(", ").join(c.getAliases()))));
    System.out.print(sb.toString());
}

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;
            }//from ww  w .java2  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:org.diqube.tool.Tool.java

public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException {
    Collection<ClassInfo> classInfos = ClassPath.from(Tool.class.getClassLoader())
            .getTopLevelClassesRecursive(BASE_PKG);

    Map<String, ToolFunction> toolFunctions = new HashMap<>();

    for (ClassInfo classInfo : classInfos) {
        Class<?> clazz = classInfo.load();
        ToolFunctionName toolFunctionName = clazz.getAnnotation(ToolFunctionName.class);
        if (toolFunctionName != null) {
            ToolFunction functionInstance = (ToolFunction) clazz.newInstance();
            toolFunctions.put(toolFunctionName.value(), functionInstance);
        }//from   w  w w  . j  a va 2  s .c  o  m
    }

    new Tool(toolFunctions).execute(args);
}

From source file:com.google.cloud.dataflow.sdk.testing.DataflowJUnitTestRunner.java

public static void main(String... args) throws Exception {
    PipelineOptionsFactory.register(Options.class);
    Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
    Set<ClassPath.ClassInfo> classes = ClassPath.from(ClassLoader.getSystemClassLoader()).getAllClasses();

    // Build a list of requested test targets
    List<Request> requests = new ArrayList<>();
    for (String testTarget : options.getTest()) {
        if (testTarget.contains("#")) {
            String[] parts = testTarget.split("#", 2);
            Class<?> klass = findClass(parts[0], classes);
            requests.add(Request.method(klass, parts[1]));
        } else {//from  w w  w  .j  a  v a  2  s  . co m
            requests.add(Request.aClass(findClass(testTarget, classes)));
        }
    }

    // Set system properties required by TestPipeline so that it is able to execute tests
    // on the service.
    String dataflowPipelineOptions = new ObjectMapper().writeValueAsString(args);
    System.setProperty("runIntegrationTestOnService", "true");
    System.setProperty("dataflowOptions", dataflowPipelineOptions);

    // Run the set of tests
    boolean success = true;
    JUnitCore core = new JUnitCore();
    for (Request request : requests) {
        Result result = core.run(request);
        if (!result.wasSuccessful()) {
            for (Failure failure : result.getFailures()) {
                LOG.error(failure.getTestHeader(), failure.getException());
            }
            success = false;
        }
    }
    if (!success) {
        throw new IllegalStateException("Tests failed, check output logs for details.");
    }
}

From source file:org.apache.beam.sdk.testing.DataflowJUnitTestRunner.java

public static void main(String... args) throws Exception {
    PipelineOptionsFactory.register(Options.class);
    Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
    Set<ClassPath.ClassInfo> classes = ClassPath.from(ClassLoader.getSystemClassLoader()).getAllClasses();

    // Build a list of requested test targets
    List<Request> requests = new ArrayList<>();
    for (String testTarget : options.getTest()) {
        if (testTarget.contains("#")) {
            String[] parts = testTarget.split("#", 2);
            Class<?> klass = findClass(parts[0], classes);
            requests.add(Request.method(klass, parts[1]));
        } else {/*  ww  w.ja v a  2  s  . co m*/
            requests.add(Request.aClass(findClass(testTarget, classes)));
        }
    }

    // Set system properties required by TestPipeline so that it is able to execute tests
    // on the service.
    String beamTestPipelineOptions = new ObjectMapper().writeValueAsString(args);
    System.setProperty("beamTestPipelineOptions", beamTestPipelineOptions);

    // Run the set of tests
    boolean success = true;
    JUnitCore core = new JUnitCore();
    for (Request request : requests) {
        Result result = core.run(request);
        if (!result.wasSuccessful()) {
            for (Failure failure : result.getFailures()) {
                LOG.error(failure.getTestHeader(), failure.getException());
            }
            success = false;
        }
    }
    if (!success) {
        throw new IllegalStateException("Tests failed, check output logs for details.");
    }
}

From source file:com.jensfendler.ebeanng.ReflectionsHelper.java

static public Set<String> findAllClassesInPackage(String packageName) {
    try {//  ww  w.j  a  va 2  s.c  om
        ClassPath cp = ClassPath.from(ReflectionsHelper.class.getClassLoader());
        ImmutableSet<ClassPath.ClassInfo> classes = cp.getTopLevelClasses(packageName);

        Set<String> classNames = new LinkedHashSet<>();

        for (ClassPath.ClassInfo ci : classes) {
            classNames.add(ci.getName());
        }

        return classNames;
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

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 a 2 s.co m
    return classInfos;
}

From source file:l2server.util.ClassPathUtil.java

public static <T> List<Class<T>> getAllClassesExtending(Class<T> targetClass) throws IOException {
    final ClassPath classPath = ClassPath.from(ClassLoader.getSystemClassLoader());
    //@formatter:off
    return classPath.getTopLevelClasses().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:org.opendaylight.odlparent.featuretest.ReflectionUtil.java

/**
 * Returns all classes in the named package, and its sub-packages.
 *///w ww  . jav  a2  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:uk.co.drnaylor.quickstart.modulecontainers.discoverystrategies.GoogleStrategy.java

@Override
public Set<Class<?>> discover(String topPackage, ClassLoader classLoader) throws Exception {
    Set<ClassPath.ClassInfo> ci = ClassPath.from(classLoader).getTopLevelClassesRecursive(topPackage);
    return ci.stream().map(ClassPath.ClassInfo::load).collect(Collectors.toSet());
}