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:net.pravian.aero.command.handler.SimpleCommandHandler.java

@Override
@SuppressWarnings("unchecked")
public void loadFrom(Package pack) {
    ClassPath classPath;//from  w w  w  . jav a  2s . co  m
    try {
        classPath = ClassPath.from(plugin.getClass().getClassLoader());
    } catch (Exception ex) {
        plugin.logger.severe("Could not load commands from package: " + pack.getName());
        plugin.logger.severe(ex);
        return;
    }

    for (ClassInfo info : classPath.getTopLevelClasses(pack.getName())) {

        if (!info.getSimpleName().startsWith(commandClassPrefix)) {
            logger.debug("Skipping class in command package: " + info.getSimpleName()
                    + ". Class does not have required prefix.");
            continue;
        }

        final String name = info.getSimpleName().substring(commandClassPrefix.length()).toLowerCase();

        if (commands.containsKey(name)) {
            logger.warning(
                    "Skipping class in command package: " + info.getSimpleName() + ". Command name conflict!");
            continue;
        }

        final Class<?> clazz = info.load();

        if (!AeroCommandBase.class.isAssignableFrom(clazz)) {
            logger.debug("Skipping class in command package: " + info.getSimpleName()
                    + ". Class does can not be assigned to CommandBase.");
            continue;
        }

        AeroCommandBase<T> command;
        try {
            command = (AeroCommandBase<T>) clazz.newInstance();
        } catch (Exception ex) {
            plugin.handleException("Could not instantiate command class: " + info.getSimpleName(), ex);
            continue;
        }

        try {
            command.register(this);
        } catch (Exception ex) {
            plugin.handleException("Could not register command: " + name, ex);
            return;
        }

        commands.put(name, getExecutorFactory().newExecutor(this, name, command));
    }
}

From source file:com.github.bpark.vertx.pico.ApplicationContext.java

public ApplicationContext build() {
    try {/*from  w  ww .  ja  va2  s .c  o  m*/
        if (injectAnnotation != null) {
            pico = new PicoBuilder().withAnnotatedFieldInjection(injectAnnotation).build();
        } else {
            pico = new PicoBuilder().withAnnotatedFieldInjection().build();
        }
        for (String scan : scans) {
            ClassPath classpath = ClassPath.from(ApplicationContext.class.getClassLoader());
            for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClasses(scan)) {
                Class<?> loadedClass = classInfo.load();
                classes.add(loadedClass);
            }
        }
        for (Class<?> aClass : classes) {
            pico.addComponent(aClass);
        }
        pico.addComponent(this);
        pico.addAdapter(new ContextInjector(vertx, container));
        pico.addAdapter(new VertxInjector(vertx));
        pico.addAdapter(new ContainerInjector(container));
        pico.addAdapter(new LoggerInjector(container.logger()));
        pico.addAdapter(new EventBusInjector(vertx.eventBus()));
        pico.addAdapter(new BusModInjector(container));
        for (ComponentAdapter<?> componentAdapter : componentAdapters) {
            pico.addAdapter(componentAdapter);
        }
        return this;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.adamjak.thomas.graph.library.utils.ClassFinder.java

/**
 * Find all classes in package and subpackages.
 *
 * @param packageNames {@link Set} of package name with annoted classes
 * @return {@link Set}&lt;{@link Class}&lt;?&gt;&gt; found classes.
 *///w  w  w .java2  s.  c  o m
public Set<Class<?>> findClasses(Set<String> packageNames) {
    Set<Class<?>> classes = new LinkedHashSet<Class<?>>();

    try {
        for (String packageName : packageNames) {
            Set<ClassPath.ClassInfo> classesInPackage = ClassPath.from(this.classLoader)
                    .getTopLevelClassesRecursive(packageName);
            for (ClassPath.ClassInfo ci : classesInPackage) {
                classes.add(ci.load());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return classes;
}

From source file:org.copperengine.monitoring.client.screenshotgen.ScreenshotGeneratorMain.java

void run() {
    deleteOutputFolder();//from  ww  w .  j  a  v  a2 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 = ApplicationFixture.getStage().getScene();

    ArrayList<ScreenshotPageBase> tests = new ArrayList<ScreenshotPageBase>();
    try {
        for (ClassInfo classInfo : ClassPath.from(getClass().getClassLoader())
                .getTopLevelClassesRecursive(ScreenshotGeneratorMain.class.getPackage().getName())) {
            if (ScreenshotPageBase.class.isAssignableFrom(classInfo.load())
                    && !ScreenshotPageBase.class.equals(classInfo.load())) {
                try {
                    final ScreenshotPageBase test = (ScreenshotPageBase) 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);
    }

    for (final ScreenshotPageBase screenshotPageBase : tests) {
        before(screenshotPageBase);
        writeScreenshotTo(new File(OUTPUT_FOLDER + "/" + screenshotPageBase.getTitle() + ".png"));
    }

}

From source file:com.axelor.common.reflections.ResourceFinder.java

private static ImmutableList<URL> getResources(Pattern pattern, ClassLoader loader, boolean partial) {
    final ImmutableList.Builder<URL> builder = ImmutableList.builder();
    final ClassLoader classLoader = loader == null ? Thread.currentThread().getContextClassLoader() : loader;
    try {//  w ww.  j  a v a 2s. c o m
        for (ResourceInfo info : ClassPath.from(classLoader).getResources()) {
            String name = info.getResourceName();
            Matcher matcher = pattern.matcher(name);
            boolean matched = partial ? matcher.find() : matcher.matches();
            if (matched) {
                Enumeration<URL> urls = classLoader.getResources(name);
                while (urls.hasMoreElements()) {
                    builder.add(urls.nextElement());
                }
            }
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    return builder.build();
}

From source file:org.onehippo.forge.oaipmh.provider.provider.JaxbContextProvider.java

private void includeAnnotatedTopLevelClassesFromBeansPackage(final List<Class<?>> allClasses)
        throws IOException, ClassNotFoundException {
    if (!Strings.isNullOrEmpty(beansPackage)) {
        final ClassPath classPath = ClassPath.from(getClass().getClassLoader());
        final ImmutableSet<ClassPath.ClassInfo> topLevelClasses = classPath
                .getTopLevelClassesRecursive(beansPackage);
        for (ClassPath.ClassInfo topLevelClass : topLevelClasses) {
            final String name = topLevelClass.getName();
            final Class<?> clazz = Class.forName(name);
            if (clazz.isAnnotationPresent(XmlRootElement.class)) {
                log.debug("include {}", clazz);
                allClasses.add(clazz);/*from   www  . ja  v a  2s .c o  m*/
            }
        }
    }
}

From source file:com.zuppelli.living.docs.DiagramMojo.java

public void generateDiagram() throws Exception {
    final ClassPath classPath = ClassPath.from(getClassLoader(this.getProject()));

    final String prefix = getPrefix();
    final ImmutableSet<ClassPath.ClassInfo> allClasses = classPath.getTopLevelClassesRecursive(prefix);

    final DotGraph.Digraph digraph = graph.getDigraph();
    digraph.setOptions("rankdir=LR");

    Stream<ClassPath.ClassInfo> pkFilter = allClasses.stream().filter(new PackageInfoPedicate());

    pkFilter.forEach(new Consumer<ClassPath.ClassInfo>() {
        public void accept(ClassPath.ClassInfo ci) {
            Class clazz = ci.load();

            Annotation annotation = clazz.getAnnotation(DomainContext.class);
            if (null != annotation) {
                packages.put(clazz.getPackage().getName(), ((DomainContext) annotation).name());
            }/*from   w ww  . ja  v a  2  s . co  m*/
        }
    });

    Stream<ClassPath.ClassInfo> domain = allClasses.stream().filter(filter(prefix, "domain"));
    // Todo create cluster from bounded context
    final DotGraph.Cluster core = digraph.addCluster("hexagon");
    // Todo retireve label from bounded context
    core.setLabel("Core Domain");

    // add all domain model elements first
    domain.forEach(new Consumer<ClassPath.ClassInfo>() {
        public void accept(ClassPath.ClassInfo ci) {
            final Class clazz = ci.load();
            core.addNode(clazz.getName()).setLabel(clazz.getSimpleName()).setComment(clazz.getSimpleName());
        }
    });

    Stream<ClassPath.ClassInfo> infra = allClasses.stream().filter(filterNot(prefix, "domain"));
    infra.forEach(new Consumer<ClassPath.ClassInfo>() {
        public void accept(ClassPath.ClassInfo ci) {
            final Class clazz = ci.load();
            digraph.addNode(clazz.getName()).setLabel(clazz.getSimpleName()).setComment(clazz.getSimpleName());
        }
    });

    infra = allClasses.stream().filter(filterNot(prefix, "domain"));
    infra.forEach(new Consumer<ClassPath.ClassInfo>() {
        public void accept(ClassPath.ClassInfo ci) {
            final Class clazz = ci.load();
            // API
            for (Field field : clazz.getDeclaredFields()) {
                final Class<?> type = field.getType();
                if (!type.isPrimitive()) {
                    digraph.addExistingAssociation(clazz.getName(), type.getName(), null, null,
                            DotStyles.ASSOCIATION_EDGE_STYLE);
                }
            }

            // SPI
            for (Class intf : clazz.getInterfaces()) {
                digraph.addExistingAssociation(intf.getName(), clazz.getName(), null, null,
                        DotStyles.IMPLEMENTS_EDGE_STYLE);
            }
        }
    });

    // then wire them together
    domain = allClasses.stream().filter(filter(prefix, "domain"));
    domain.forEach(new Consumer<ClassPath.ClassInfo>() {
        public void accept(ClassPath.ClassInfo ci) {
            final Class clazz = ci.load();
            for (Field field : clazz.getDeclaredFields()) {
                final Class<?> type = field.getType();
                if (!type.isPrimitive()) {
                    digraph.addExistingAssociation(clazz.getName(), type.getName(), null, null,
                            DotStyles.ASSOCIATION_EDGE_STYLE);
                }
            }

            for (Class intf : clazz.getInterfaces()) {
                digraph.addExistingAssociation(intf.getName(), clazz.getName(), null, null,
                        DotStyles.IMPLEMENTS_EDGE_STYLE);
            }
        }
    });

    String title = "Living Diagram";
    final String content = graph.render().trim();

    this.content.put("content", graph.render().trim());
    this.content.put("title", title);
    Template template = initializeFreeMarker();
    Writer writer = new PrintWriter("diagrama.html");
    try {
        template.process(this.content, writer);
    } finally {
        writer.close();
    }
}

From source file:com.softwarewerke.htdbc.App.java

@Override
public Set<Class<?>> getClasses() {
    Logger log = Logger.getLogger(getClass());

    Set set = new HashSet();

    ClassPath cp;//ww w  . java 2s  .com
    try {
        cp = ClassPath.from(getClass().getClassLoader());
    } catch (IOException ex) {
        log.fatal(ex);
        return set;
    }

    String p = getClass().getPackage().getName();

    for (ClassPath.ClassInfo n : cp.getAllClasses()) {
        if (!n.getPackageName().startsWith(p)) {
            continue;
        }
        try {
            Class cl = n.load();

            if (cl.getAnnotation(Path.class) == null) {
                continue;
            }
            if (cl.getAnnotation(Singleton.class) != null) {
                continue;
            }
            if (!Main.isDevelopment() && cl.getAnnotation(IsDev.class) != null) {
                continue;
            }
            set.add(cl);
        } catch (ClassFormatError ignore) {
        } catch (Exception ex) {
            log.error(ex);
        }
    }

    return set;
}

From source file:com.github.easyjsonapi.core.EasyJsonApiConfig.java

/**
 * Set the packages to search//from  w  w w . java  2 s .c  o  m
 * 
 * @param packages
 *            the packages needs to be search and parsing
 * @throws EasyJsonApiInvalidPackageException
 */
public void setPackagesToSearch(String... packages) throws EasyJsonApiInvalidPackageException {

    this.packagesSearched = packages;

    for (String packageToSearch : packages) {
        try {
            ClassPath classpath = ClassPath.from(getClass().getClassLoader());

            List<Class<?>> attrClasses = new ArrayList<>();
            List<Class<?>> metaClasses = new ArrayList<>();
            List<Class<?>> metaRelationshipsClasses = new ArrayList<>();

            for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClasses(packageToSearch)) {

                Class<?> clazz = classInfo.load();

                if (Assert.notNull(clazz.getAnnotation(Attributes.class))) {
                    attrClasses.add(clazz);
                } else if (Assert.notNull(clazz.getAnnotation(Meta.class))) {
                    metaClasses.add(clazz);
                } else if (Assert.notNull(clazz.getAnnotation(MetaRelationship.class))) {
                    metaRelationshipsClasses.add(clazz);
                }
            }

            this.classesParsed.put(EasyJsonApiTypeToken.TOKEN_ATTR, attrClasses);
            this.classesParsed.put(EasyJsonApiTypeToken.TOKEN_META, metaClasses);
            this.classesParsed.put(EasyJsonApiTypeToken.TOKEN_META_RELATIONSHIP, metaRelationshipsClasses);

        } catch (IOException ex) {
            throw new EasyJsonApiInvalidPackageException("Invalid packages inserted!", ex);
        }
    }
}

From source file:com.intel.podm.DbSchemaCreator.java

private static List<Class<?>> getDomainObjects() throws IOException {
    return ClassPath.from(ClassLoader.getSystemClassLoader()).getTopLevelClasses().stream()
            .filter(classInfo -> classInfo.getName().contains("com.intel")).map(ClassPath.ClassInfo::load)
            .filter(DomainObject.class::isAssignableFrom).filter(byNonAbstractEntities()).collect(toList());
}