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:edu.sdsc.scigraph.services.MainApplication.java

void addWriters(JerseyEnvironment environment) throws Exception {
    for (ClassInfo classInfo : ClassPath.from(getClass().getClassLoader())
            .getTopLevelClasses("edu.sdsc.scigraph.services.jersey.writers")) {
        if (!Modifier.isAbstract(classInfo.load().getModifiers())) {
            environment.register(classInfo.load().newInstance());
        }//from   w  w  w. ja v a2  s.  c  o  m
    }
}

From source file:de.scoopgmbh.copper.monitoring.client.doc.DocGeneratorMain.java

void run() {
    System.setProperty("concordion.output.dir", "documentation");
    deleteReportFolder();/* w w w .  j  a  va2  s  . c  o m*/
    new Thread() {
        @Override
        public void run() {
            ApplicationFixture.launchWorkaround();
        }
    }.start();
    try {
        Thread.sleep(SHORT_WAIT_TIME);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    scene = new SceneDock();

    ArrayList<IntegrationtestBase> tests = new ArrayList<IntegrationtestBase>();
    try {
        for (ClassInfo classInfo : ClassPath.from(getClass().getClassLoader())
                .getTopLevelClassesRecursive(DocGeneratorMain.class.getPackage().getName())) {
            if (IntegrationtestBase.class.isAssignableFrom(classInfo.load())
                    && !IntegrationtestBase.class.equals(classInfo.load())) {
                try {
                    final IntegrationtestBase test = (IntegrationtestBase) classInfo.load().newInstance();
                    tests.add(test);
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    ConcordionExtension screenshotExtension = new ScreenshotExtension().setScreenshotTaker(camera)
            .setScreenshotOnAssertionSuccess(false).setScreenshotOnThrowable(false).setMaxWidth(400);

    BreadcrumbCssRemovedConcordionBuilder concordionBuilder = new BreadcrumbCssRemovedConcordionBuilder();
    concordionBuilder.withEmbeddedCSS("");
    screenshotExtension.addTo(concordionBuilder);
    new BootsrapCssExtension().addTo(concordionBuilder);
    new StaticRessourceExtension().addTo(concordionBuilder);

    for (final IntegrationtestBase integrationtestBase : tests) {
        ResultSummary resultSummary;
        try {
            before(integrationtestBase);
            resultSummary = concordionBuilder.build().process(integrationtestBase);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        resultSummary.print(System.out, this);
        resultSummary.assertIsSatisfied(this);
        after();
    }

    File summary = writeSummary(tests);
    afterAll(summary);
    // resultSummary.getFailureCount()
}

From source file:io.macgyver.cli.CLI.java

List<Class<? extends Command>> findCommands() {
    try {// w  w w  . j a va  2  s. c  o  m
        List<Class<? extends Command>> classList = Lists.newArrayList();

        List<ClassInfo> classInfoList = Lists.newArrayList();

        for (String packageName : findPackageNamesToSearch()) {
            logger.info("Searching pacakge {} for CLI commands", packageName);
            classInfoList.addAll(ClassPath.from(Thread.currentThread().getContextClassLoader())
                    .getTopLevelClasses(packageName));
        }

        classInfoList.forEach(it -> {
            try {
                logger.info("attempting to load: {}", it.getName());
                Class clazz = Class.forName(it.getName());

                if (Command.class.isAssignableFrom(clazz)) {
                    if (Modifier.isAbstract(clazz.getModifiers())) {
                        logger.debug("{} is abstract", clazz);
                    } else {
                        logger.debug("adding {}", clazz);
                        classList.add((Class<? extends Command>) clazz);
                    }

                }
            } catch (ClassNotFoundException | NoClassDefFoundError e) {
                logger.warn("", e);
            }
        });
        return classList;
    } catch (IOException e) {
        throw new CLIException(e);
    }
}

From source file:org.diqube.function.FunctionFactory.java

@PostConstruct
private void initialize() {
    ImmutableSet<ClassInfo> classInfos;
    try {//from   www.  jav  a  2 s .  co  m
        classInfos = ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive(BASE_PKG);
    } catch (IOException e) {
        throw new RuntimeException("Could not parse ClassPath.");
    }

    projectionFunctionFactories = new HashMap<>();
    aggregationFunctionFactories = new HashMap<>();

    for (ClassInfo classInfo : classInfos) {
        Class<?> clazz = classInfo.load();
        Function funcAnnotation = clazz.getAnnotation(Function.class);
        if (funcAnnotation != null) {
            String funcName = funcAnnotation.name();
            if (ProjectionFunction.class.isAssignableFrom(clazz)) {
                if (!projectionFunctionFactories.containsKey(funcName))
                    projectionFunctionFactories.put(funcName, new HashMap<>());

                Supplier<ProjectionFunction<?, ?>> supplier = () -> {
                    try {
                        return (ProjectionFunction<?, ?>) clazz.newInstance();
                    } catch (Exception e) {
                        throw new RuntimeException("Could not instantiate " + clazz.getName(), e);
                    }
                };

                ProjectionFunction<?, ?> tempInstance = supplier.get();

                if (projectionFunctionFactories.get(funcName).put(tempInstance.getInputType(),
                        supplier) != null)
                    throw new RuntimeException("There are multiple ProjectionFunctions with name '" + funcName
                            + "' and input data type " + tempInstance.getInputType());

            } else if (AggregationFunction.class.isAssignableFrom(clazz)) {
                if (!aggregationFunctionFactories.containsKey(funcName))
                    aggregationFunctionFactories.put(funcName, new HashMap<>());

                Supplier<AggregationFunction<?, ?>> supplier = () -> {
                    try {
                        return (AggregationFunction<?, ?>) clazz.newInstance();
                    } catch (Exception e) {
                        throw new RuntimeException("Could not instantiate " + clazz.getName());
                    }
                };

                AggregationFunction<?, ?> tempInstance = supplier.get();

                aggregationFunctionFactories.get(funcName).put(tempInstance.getInputType(), supplier);
            }
        }
    }
}

From source file:org.apache.servicecomb.it.junit.ITJUnitUtils.java

public static Class<?>[] findAllClassInPackage(String packageName) {
    try {/* w w  w  . j  a  va 2 s.c o  m*/
        return ClassPath.from(classLoader).getTopLevelClassesRecursive(packageName).stream()
                .map(clsInfo -> clsInfo.load()).toArray(Class[]::new);
    } catch (IOException e) {
        throw new IllegalStateException("failed to find all classes in package " + packageName, e);
    }
}

From source file:com.google.cloud.crypto.tink.tinkey.TinkeyUtil.java

/**
 * Finds and loads {@code className}.// w  w w .j a v a 2s .co  m
 */
public static Class<?> loadClass(String className) throws IOException {
    ImmutableSet<ClassInfo> classInfos = ClassPath.from(TinkeyUtil.class.getClassLoader()).getAllClasses();
    for (ClassInfo classInfo : classInfos) {
        if (classInfo.getName().toLowerCase().endsWith(className.toLowerCase())) {
            return classInfo.load();
        }
    }
    throw new IOException("class not found: " + className);
}

From source file:com.google.cloud.dataflow.sdk.util.ApiSurface.java

/**
 * Returns an {@link ApiSurface} like this one, but also including the named
 * package and all of its subpackages.//  w  w w.  j  a  va 2 s. com
 */
public ApiSurface includingPackage(String packageName) throws IOException {
    ClassPath classPath = ClassPath.from(ClassLoader.getSystemClassLoader());

    Set<Class<?>> newRootClasses = Sets.newHashSet();
    for (ClassInfo classInfo : classPath.getTopLevelClassesRecursive(packageName)) {
        Class clazz = classInfo.load();
        if (exposed(clazz.getModifiers())) {
            newRootClasses.add(clazz);
        }
    }
    logger.debug("Including package {} and subpackages: {}", packageName, newRootClasses);
    newRootClasses.addAll(rootClasses);

    return new ApiSurface(newRootClasses, patternsToPrune);
}

From source file:com.phoenixnap.oss.ramlapisync.plugin.CommonApiSyncMojo.java

/**
 * Main entrypoint for raml generation/*from  ww w.  ja  va  2 s.co  m*/
 * @throws MojoExecutionException Kaboom.
 * @throws MojoFailureException Kaboom.
 * @throws IOException Kaboom.
 */
protected void prepareRaml() throws MojoExecutionException, MojoFailureException, IOException {
    ClassLoaderUtils.addLocationsToClassLoader(project);
    List<String> targetPacks = ClassLoaderUtils.loadPackages(project);
    if (dependencyPackagesList != null && !dependencyPackagesList.isEmpty()) {
        targetPacks.addAll(dependencyPackagesList);
    }

    ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
    for (String pack : targetPacks) {
        scanPack(pack, classPath);
    }

    for (ClassPath.ResourceInfo resourceInfo : classPath.getResources()) {
        if (resourceInfo.getResourceName().endsWith(documentationSuffix)) {
            try {
                documents.add(new ApiDocumentMetadata(resourceInfo, documentationSuffix));
                this.getLog().info("Adding Documentation File " + resourceInfo.getResourceName());
            } catch (Throwable ex) {
                this.getLog().warn("Skipping Resource: Unable to load" + resourceInfo.getResourceName(), ex);
            }
        }
    }

    ClassLoaderUtils.restoreOriginalClassLoader();
}

From source file:graphene.introspect.Introspector.java

public void introspect() {
    // TODO Auto-generated method stub
    ClassPath classPath = null;/*from  w ww.  j  ava 2 s . com*/
    System.out.println("Starting introspection");
    try {
        classPath = ClassPath.from(Introspector.class.getClassLoader());
        System.out.println("Starting introspection for " + classPath.toString());
        for (ClassPath.ClassInfo classInfo : classPath.getTopLevelClassesRecursive(beanPackageName)) {
            Class<?> c = classInfo.load();
            System.out.println("Loading fields for class " + c.getSimpleName());
            for (Field f : c.getFields()) {
                if (!Modifier.isStatic(f.getModifiers())) {
                    System.out.println(c.getName() + "." + f.getName());
                }
            }
            if (c.getSimpleName().startsWith("Q")) {
                queryClasses.put(c.getSimpleName(), c);
            } else {
                domainClasses.put(c.getSimpleName(), c);
            }
            // learnAboutClass(c);
        }
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
    for (String s : domainClasses.keySet()) {
        Class q = queryClasses.get("Q" + s);
        if (q != null) {

            learnAbout(domainClasses.get(s), q);
        } else {
            // tablename might start with a q?
            logger.error("Could not find query class for " + s);
        }
    }

}

From source file:org.gbif.api.util.VocabularyUtils.java

/**
 * Utility method to get a map of all enumerations within a package.
 * The map will use the enumeration class simple name as key and the enum itself as value.
 *
 * @return a map of all enumeration within the package or an empty map in all other cases.
 *//*from w  ww.j a va2  s . c  o  m*/
public static Map<String, Enum<?>[]> listEnumerations(String packageName) {
    try {
        ClassPath cp = ClassPath.from(VocabularyUtils.class.getClassLoader());
        ImmutableMap.Builder<String, Enum<?>[]> builder = ImmutableMap.builder();

        List<ClassPath.ClassInfo> infos = cp.getTopLevelClasses(packageName).asList();
        for (ClassPath.ClassInfo info : infos) {
            Class<? extends Enum<?>> vocab = lookupVocabulary(info.getName());
            // verify that it is an Enumeration
            if (vocab != null && vocab.getEnumConstants() != null) {
                builder.put(info.getSimpleName(), vocab.getEnumConstants());
            }
        }
        return builder.build();
    } catch (Exception e) {
        LOG.error("Unable to read the classpath for enumerations", e);
        return ImmutableMap.<String, Enum<?>[]>of(); // empty
    }
}