List of usage examples for com.google.common.reflect ClassPath getTopLevelClassesRecursive
public ImmutableSet<ClassInfo> getTopLevelClassesRecursive(String packageName)
From source file:org.jmingo.mapping.convert.ConverterService.java
private Set<Class<?>> getConvertersClasses(String converterPackage, ClassLoader classLoader) { Set<Class<?>> classes = Collections.emptySet(); try {/*from w ww . ja v a2 s . c o m*/ ClassPath classPath = ClassPath.from(classLoader); Set<com.google.common.reflect.ClassPath.ClassInfo> classInfos = classPath .getTopLevelClassesRecursive(converterPackage); if (CollectionUtils.isNotEmpty(classInfos)) { classes = Sets.newHashSet(); for (com.google.common.reflect.ClassPath.ClassInfo classInfo : classInfos) { Class<?> converterClass = Class.forName(classInfo.getName()); if (Converter.class.isAssignableFrom(converterClass) && classInfo.getName().contains(converterPackage)) { classes.add(converterClass); } } } } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(format(CONVERTER_LOAD_ERROR, converterPackage), e); } return classes; }
From source file:edu.pitt.dbmi.deepphe.summarization.orm.i2b2meta.I2b2MetaDataSourceManager.java
public void addAnnotatedClsesForPackage() { logger.debug("Entered addAnnotatedClsesForPackage for " + getClass().getName()); try {/* w ww .ja v a 2 s . c o m*/ 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:nl.knaw.huygens.timbuctoo.config.TypeRegistry.java
private Set<ClassInfo> getClassInfoSet(ClassPath classPath, String packageName) { if (packageName.endsWith(".*")) { return classPath.getTopLevelClassesRecursive(StringUtils.chomp(packageName, ".*")); } else {/* www . ja v a2 s .c o m*/ return classPath.getTopLevelClasses(packageName); } }
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 w w . j a v a2s. c o 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.px100systems.data.core.DatabaseStorage.java
@Override @SuppressWarnings("unchecked") public void afterPropertiesSet() throws Exception { if (tenantLoader != null) tenantLoader.setDatabase(this); configuredEntities = new HashMap<String, Class<? extends Entity>>(); try {/*from ww w . ja v a 2s. co m*/ ClassPath cp = ClassPath.from(getClass().getClassLoader()); for (String p : baseEntityPackages) for (ClassPath.ClassInfo cli : cp.getTopLevelClassesRecursive(p)) { Class<?> eClass = Class.forName(cli.getName()); if (!Modifier.isAbstract(eClass.getModifiers()) && Entity.class.isAssignableFrom(eClass)) { Class<? extends Entity> entityClass = (Class<? extends Entity>) eClass; String name = entityClass.getSimpleName(); Class<? extends Entity> cls = configuredEntities.get(name); if (cls != null) { if (cls.getName().equals(entityClass.getName())) continue; throw new RuntimeException("Duplicate entities in different packages: " + name); } configuredEntities.put(name, entityClass); SerializationDefinition.register(entityClass); } } } catch (Exception e1) { throw new RuntimeException(e1); } SerializationDefinition.lock(); runtimeStorage.getProvider().start(); List<BaseTenantConfig> tenants = new ArrayList<BaseTenantConfig>(); if (tenantLoader != null) tenants = tenantLoader.load(); List<EntityInfo> entities = new ArrayList<>(); for (Class<? extends Entity> entityClass : getConfiguredEntities().values()) { Map<String, Class<?>> indexes = Entity.indexes(entityClass); List<CompoundIndexDescriptor> compoundIndexes = Entity.compoundIndexes(entityClass); if (tenants.isEmpty()) entities.add(new EntityInfo(entityClass, 0, Entity.unitFromClass(entityClass, 0), indexes, compoundIndexes)); else for (BaseTenantConfig tenant : tenants) entities.add(new EntityInfo(entityClass, tenant.getId(), Entity.unitFromClass(entityClass, tenant.getId()), indexes, compoundIndexes)); } init(entities, initializer != null); if (initializer != null) { initializer.initialize(new Transaction(this, 0)); log.info("Initialized the database"); } }
From source file:graphene.introspect.Introspector.java
public void introspect() { // TODO Auto-generated method stub ClassPath classPath = null; System.out.println("Starting introspection"); try {/*w w w. j a va 2 s . c o m*/ 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:soottocfg.soot.SootRunner.java
/** * Writes all classes from the soottocfg.spec to targetDir * so that we can use them later when re-writing the bytecode. * //from w w w . j a v a 2 s .c om * @param targetDir */ protected void writeSpecPackageToDisc(File targetDir) { if (!targetDir.isDirectory()) { if (!targetDir.mkdirs()) { throw new RuntimeException("Can't write to disk"); } } try { ClassLoader cl = this.getClass().getClassLoader(); ClassPath cp = ClassPath.from(cl); for (ClassInfo ci : cp.getTopLevelClassesRecursive("soottocfg.spec")) { StringBuilder sb = new StringBuilder(); sb.append(targetDir.getAbsolutePath()); sb.append(File.separator); sb.append(ci.getPackageName().replace(".", File.separator)); File outFileDir = new File(sb.toString()); if (!outFileDir.exists() && !outFileDir.mkdirs()) { throw new RuntimeException("Couldn't generate dirs for " + sb.toString()); } sb.append(File.separator); sb.append(ci.getSimpleName()); sb.append(".class"); File outFile = new File(sb.toString()); try (InputStream inputStream = cl.getResourceAsStream(ci.getResourceName()); OutputStream outputStream = new FileOutputStream(outFile);) { ByteStreams.copy(inputStream, outputStream); } catch (Throwable e) { e.printStackTrace(); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
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 ww . j ava2 s . c om*/ */ 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:org.diqube.build.mojo.GenerateTsMojo.java
/** * Scan classpath and identify and load all transitive classes that have a {@link TypeScriptProperty} annotation on * one of their properties./*from w w w. j ava2s.c om*/ * * @return null if no classes were scanned. Otherwise map from class name to pair of loaded class and list of other * class names the class depends on (only the ones whose classname is present as key in the map!). */ private Map<String, Pair<Class<?>, Set<String>>> findClassesWithTypeScriptAnnotation(ClassLoader ourClassLoader) throws MojoExecutionException { ClassPath classPath; try { classPath = ClassPath.from(ourClassLoader); } catch (IOException e) { throw new MojoExecutionException("Could not scan classpath", e); } Deque<String> classNamesToVisit = new LinkedList<>(); for (String pkg : rootPackages) classNamesToVisit.addAll(classPath.getTopLevelClassesRecursive(pkg).stream() .map(classInfo -> classInfo.getName()).collect(Collectors.toList())); if (classNamesToVisit.isEmpty()) { getLog().info("No classes found."); return null; } getLog().debug("Found following classes in first scan: " + classNamesToVisit); Map<String, Pair<Class<?>, Set<String>>> typescriptClasses = new HashMap<>(); Set<String> classesVisited = new HashSet<>(); while (!classNamesToVisit.isEmpty()) { String className = classNamesToVisit.pop(); if (!classesVisited.add(className)) continue; Class<?> clazz; try { clazz = ourClassLoader.loadClass(className); } catch (ClassNotFoundException e) { getLog().warn("Could not load class " + className); continue; } // check valid, since the ourClassLoader must not overwrite the STOP_CLASSES. if (STOP_CLASSES.contains(clazz)) continue; for (Pair<Field, TypeScriptProperty> p : findTypeScriptFields(clazz)) { Field f = p.getLeft(); typescriptClasses.putIfAbsent(clazz.getName(), new Pair<>(clazz, new HashSet<>())); Set<String> dependsSet = typescriptClasses.get(clazz.getName()).getRight(); // check valid, since the ourClassLoader must not overwrite the STOP_CLASSES. if (!STOP_CLASSES.contains(f.getType())) { Set<Class<?>> allReferencedClasses = getAllReferencedClasses(f.getGenericType()); Set<String> allReferencedClassNames = allReferencedClasses.stream().map(c -> c.getName()) .collect(Collectors.toSet()); classNamesToVisit.addAll(allReferencedClassNames); dependsSet.addAll(allReferencedClassNames); } classNamesToVisit.add(clazz.getSuperclass().getName()); dependsSet.add(clazz.getSuperclass().getName()); } } // cleanup result map, remove all the "depends on" classes that did not contain the annotation for (Pair<Class<?>, Set<String>> p : typescriptClasses.values()) { p.getRight().retainAll(typescriptClasses.keySet()); } return typescriptClasses; }
From source file:org.apache.beam.sdk.util.ApiSurface.java
/** * Returns an {@link ApiSurface} like this one, but also including the named package and all of * its subpackages./* w ww. j a va 2 s . c o m*/ */ public ApiSurface includingPackage(String packageName, ClassLoader classLoader) throws IOException { ClassPath classPath = ClassPath.from(classLoader); Set<Class<?>> newRootClasses = Sets.newHashSet(); for (ClassPath.ClassInfo classInfo : classPath.getTopLevelClassesRecursive(packageName)) { Class clazz = null; try { clazz = classInfo.load(); } catch (NoClassDefFoundError e) { // TODO: Ignore any NoClassDefFoundError errors as a workaround. (BEAM-2231) LOG.warn("Failed to load class: {}", classInfo.toString(), e); continue; } if (exposed(clazz.getModifiers())) { newRootClasses.add(clazz); } } LOG.debug("Including package {} and subpackages: {}", packageName, newRootClasses); newRootClasses.addAll(rootClasses); return new ApiSurface(newRootClasses, patternsToPrune); }