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:io.macgyver.core.cli.ClientPackager.java

private synchronized File buildCli() throws IOException, net.lingala.zip4j.exception.ZipException {

    File tempDir = Files.createTempDir();

    File f = new File(tempDir, "collected-cli-classes.jar");

    ZipFile z = new ZipFile(f);

    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    for (String packageName : CLI.findPackageNamesToSearch()) {

        logger.info("searching pacakge for CLI commands: {}", packageName);
        ClassPath.from(cl).getTopLevelClasses(packageName).forEach(it -> {

            if (isToBePackaged(it)) {
                logger.info("adding command class: {}", it);
                try (InputStream input = it.url().openStream()) {
                    byte[] b = ByteStreams.toByteArray(input);

                    ZipParameters zp = new ZipParameters();
                    zp.setSourceExternalStream(true);
                    zp.setFileNameInZip(it.getName().replace(".", "/") + ".class");
                    z.addStream(new ByteArrayInputStream(b), zp);
                } catch (IOException | net.lingala.zip4j.exception.ZipException e) {
                    throw new RuntimeException(e);
                }/*  ww w  .jav  a2s.c o m*/
            }

        });
    }

    File generatedJar = new File(tempDir, "macgyver-capsule-with-extensions.jar");

    try (InputStream in = cl.getResourceAsStream("cli/macgyver-cli-capsule.jar")) {
        Preconditions.checkNotNull(in,
                "resource cli/macgyver-cli-capsule.jar could not be loaded.  Did you run gradle install in macgyver-cli?");
        try (FileOutputStream out = new FileOutputStream(generatedJar)) {

            ByteStreams.copy(in, out);
        }
    }

    ZipFile mj = new ZipFile(generatedJar);
    ZipParameters zp = new ZipParameters();
    zp.setFileNameInZip("collected-cli-classes.jar");

    try {
        mj.removeFile("collected-cli-classes.jar");
    } catch (Exception e) {
    }
    mj.addFile(f, zp);

    targetDir.mkdirs();
    File executable = new File(targetDir, "macgyver");
    executable.delete();

    PrintWriter bw = new PrintWriter(new FileWriter(executable));

    org.springframework.core.io.Resource resource = Kernel.getApplicationContext()
            .getResource("classpath:cli/cli-jar-header.sh");
    try (InputStreamReader isr = new InputStreamReader(resource.getInputStream())) {
        String script = CharStreams.toString(isr);
        bw.println(script);
    }
    // bw.println("#!/bin/bash");
    // bw.println("exec java -Dcli.exe=\"$0\" -Dcli.launch=true -jar $0
    // \"$@\"");

    bw.close();

    try (FileInputStream fis = new FileInputStream(generatedJar)) {
        try (FileOutputStream fos = new FileOutputStream(executable, true)) {
            ByteStreams.copy(fis, fos);
        }
    }
    executable.setExecutable(true);

    return executable;
}

From source file:org.monarchinitiative.owlsim.services.OwlSimServiceApplication.java

@Override
public void run(ApplicationConfiguration configuration, Environment environment) throws Exception {
    environment.getApplicationContext().setContextPath("/api");
    configureSwagger(environment);//from   w ww.j  a v  a  2  s . co m

    Injector i = Guice.createInjector(
            new KnowledgeBaseModule(configuration.getOntologyUris(), configuration.getOntologyDataUris()),
            new MatcherMapModule());

    //Add resources
    Set<ClassInfo> resourceClasses = ClassPath.from(getClass().getClassLoader())
            .getTopLevelClasses("org.monarchinitiative.owlsim.services.resources");
    for (ClassInfo resourceClass : resourceClasses) {
        environment.jersey().register(i.getInstance(resourceClass.load()));
    }

}

From source file:nl.knaw.huygens.timbuctoo.vre.PackageScope.java

private final void addPackage(String name) throws IOException {
    ClassPath classPath = ClassPath.from(PackageScope.class.getClassLoader());
    String packageName = name.replaceFirst("^timbuctoo", "nl.knaw.huygens.timbuctoo");
    for (ClassInfo info : classPath.getTopLevelClasses(packageName)) {
        addClass(info.load());/*ww  w  . ja va  2  s  . c  om*/
    }
}

From source file:edu.pitt.dbmi.deepphe.summarization.orm.i2b2meta.I2b2MetaDataSourceManager.java

public void addAnnotatedClsesForPackage() {
    logger.debug("Entered addAnnotatedClsesForPackage for " + getClass().getName());
    try {/*from  w  w w . j ava2s.  com*/
        String pkgName = getClass().getPackage().getName();
        ClassPath classPath = ClassPath.from(getClass().getClassLoader());
        final ArrayList<Class<?>> clses = new ArrayList<>();
        Set<ClassInfo> clsInfos = classPath.getTopLevelClassesRecursive(pkgName);
        for (ClassInfo clsInfo : clsInfos) {
            if (!clsInfo.getName().equals(getClass().getName())) {
                clses.add(clsInfo.load());
            }
        }
        if (clses.isEmpty()) {
            logger.error("Failed to load hibernate clses");
        } else {
            for (Class<?> cls : clses) {
                System.err.println("Configuring " + cls.getName() + " into Hibernate");
                logger.info("Configuring " + cls.getName() + " into Hibernate");
                configuration.addAnnotatedClass(cls);
            }
        }
    } catch (IOException e) {
    }
    logger.debug("Exited addAnnotatedClsesForPackage for " + getClass().getName());
}

From source file:ch.ifocusit.plantuml.classdiagram.ClassDiagramBuilder.java

public void addPackages() {
    packages.stream().forEach(pkg -> {
        try {/*from  ww w .  ja va2  s  .co  m*/
            ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
            Clazz[] classes = classPath.getTopLevelClasses(pkg.getName()).stream()
                    .map(ClassPath.ClassInfo::load).map(this::createJavaClass).sorted().toArray(Clazz[]::new);
            builder.addPackage(Package.from(pkg), classes);
        } catch (IOException e) {
            throw new IllegalStateException("Cannot load classesRepository from package " + pkg, e);
        }

    });
}

From source file:org.eclipse.milo.opcua.stack.core.serialization.DelegateRegistry.java

private static void loadGeneratedClasses(ClassLoader classLoader) throws IOException, ClassNotFoundException {
    ClassPath classPath = ClassPath.from(classLoader);

    ImmutableSet<ClassInfo> structures = classPath
            .getTopLevelClasses("org.eclipse.milo.opcua.stack.core.types.structured");

    ImmutableSet<ClassInfo> enumerations = classPath
            .getTopLevelClasses("org.eclipse.milo.opcua.stack.core.types.enumerated");

    for (ClassInfo classInfo : Sets.union(structures, enumerations)) {
        Class<?> clazz = classInfo.load();
        Class.forName(clazz.getName(), true, classLoader);
    }//ww  w.ja  va2  s.  c  om
}

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 MigrateDuringDeployment} annotation and record the necessary
 * upgrade information./*from   w  w w . j a  v a 2 s.com*/
 *
 * @return list of {@link DeploymentMigrationInformation} objects describing each service document that needs to be
 * migrated during deployment.
 */
@SuppressWarnings("unchecked")
public static List<DeploymentMigrationInformation> findAllMigrationServices() {
    List<DeploymentMigrationInformation> 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() == MigrateDuringDeployment.class) {
                        MigrateDuringDeployment u = (MigrateDuringDeployment) a;

                        DeploymentMigrationInformation info = new DeploymentMigrationInformation(
                                u.factoryServicePath(), u.serviceName(),
                                (Class<? extends ServiceDocument>) type);

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

From source file:org.syncany.plugins.Plugins.java

/**
 * Loads all plugins in the classpath./*from ww w.j  a v a 2  s . c om*/
 *
 * <p>First loads all classes in the 'org.syncany.plugins' package.
 * For all classes ending with the 'Plugin' suffix, it tries to load
 * them, checks whether they inherit from {@link Plugin} and whether
 * they can be instantiated.
 */
private static void loadPlugins() {
    try {
        ImmutableSet<ClassInfo> pluginPackageSubclasses = ClassPath
                .from(Thread.currentThread().getContextClassLoader())
                .getTopLevelClassesRecursive(PLUGIN_PACKAGE_NAME);

        for (ClassInfo classInfo : pluginPackageSubclasses) {
            boolean classNameEndWithPluginSuffix = classInfo.getName().endsWith(PLUGIN_CLASS_SUFFIX);

            if (classNameEndWithPluginSuffix) {
                Class<?> pluginClass = classInfo.load();

                String camelCasePluginId = pluginClass.getSimpleName().replace(Plugin.class.getSimpleName(),
                        "");
                String pluginId = StringUtil.toSnakeCase(camelCasePluginId);

                boolean isSubclassOfPlugin = Plugin.class.isAssignableFrom(pluginClass);
                boolean canInstantiate = !Modifier.isAbstract(pluginClass.getModifiers());
                boolean pluginAlreadyLoaded = plugins.containsKey(pluginId);

                if (isSubclassOfPlugin && canInstantiate && !pluginAlreadyLoaded) {
                    logger.log(Level.INFO, "- " + pluginClass.getName());

                    try {
                        Plugin plugin = (Plugin) pluginClass.newInstance();
                        plugins.put(plugin.getId(), plugin);
                    } catch (Exception e) {
                        logger.log(Level.WARNING, "Could not load plugin (2): " + pluginClass.getName(), e);
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Unable to load plugins.", e);
    }
}

From source file:com.itametis.jsonconverter.classpathscan.JsonMappingPackage.java

/**
 * Scan the classes in the declared package (full class path otherwise) to find classes with Json annotations.
 * Get them in memory.//w w  w. ja  va2s.  c om
 *
 * @throws IOException
 */
public final void scanClassesInPackage() throws IOException {
    this.jsonnableClasses.clear();

    //Get current class loader.
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    //Get Classpath.
    ClassPath classpath = ClassPath.from(classLoader);

    //Get Classes.
    ImmutableSet<ClassInfo> classes = this.getClassesFromClassPath(classpath);

    this.getJsonnableInformation(classes);
}

From source file:ch.ifocusit.livingdoc.plugin.diagram.AbstractClassDiagramBuilder.java

protected ClassPath initClassPath() throws MojoExecutionException {
    try {//from  w w w .ja v a  2  s.  c o m
        return ClassPath.from(ClassLoaderUtil.getRuntimeClassLoader(project));
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to initialize classPath !", e);
    }
}