public String generate() throws MojoExecutionException { final ClassPath classPath = initClassPath(); final Set<ClassInfo> allClasses = classPath.getTopLevelClassesRecursive(prefix); String diagram = classDiagramBuilder .addClasse(allClasses.stream() // apply filters .filter(defaultFilter()) .filter(additionalClassPredicate) .map(ClassInfo::load).collect(Collectors.toList())) .excludes(excludes) .setHeader(readHeader()) .setFooter(readFooter()) .withNamesMapper(namesMapper) .withLinkMaker(this) .withDependencies(diagramWithDependencies) .build(); return diagram; }
private List<Class<?>> loadClassesInPackage() throws IOException { List<Class<?>> classes = Lists.newArrayList(); String packageName = getClass().getPackage().getName(); for (ClassPath.ClassInfo classInfo : ClassPath.from(getClass().getClassLoader()).getTopLevelClasses(packageName)) { Class<?> cls; try { cls = classInfo.load(); } catch (NoClassDefFoundError e) { // In case there were linking problems, this is probably not a class we care to test anyway. logger.log(Level.SEVERE, "Cannot load class " + classInfo + ", skipping...", e); continue; } if (!cls.isInterface()) { classes.add(cls); } } return classes; }
public static Set<Class<?>> getAnnotatedClasses(final Class[] annotations, final String... packages) { Set<String> annotationsToScan = Stream.of(annotations).map(Class::getSimpleName).collect(toSet()); ClassLoader cl = AnnotationScanner.class.getClassLoader(); try { ClassPath cp = ClassPath.from(cl); return Stream.of(packages) .flatMap(packageName -> cp.getTopLevelClassesRecursive(packageName).stream()) .filter(isClassAnnotatedByScannedAnnotations(annotationsToScan)) .map(ClassPath.ClassInfo::load) .collect(toSet()); } catch (IOException e) { log.error("Failed to get annotated classes", e); return Collections.emptySet(); } }
boolean hasAccessibleConstructor(ClassPath.ClassInfo info, String fromPackage) { Class<?> load = info.load(); boolean isPublicClass = Modifier.isPublic(load.getModifiers()), isSamePackage = fromPackage.equals(info.getPackageName()); for (Constructor<?> candidate : load.getDeclaredConstructors()) { int modifiers = candidate.getModifiers(); if (isPublicClass && Modifier.isPublic(modifiers)) return true; else if (isSamePackage && !Modifier.isPrivate(modifiers) && !Modifier.isProtected(modifiers)) return true; } return false; }
@SuppressWarnings("unchecked") private Iterable<Class<? extends AbstractMessage>> findMessageClasses() { try { List<Class<? extends AbstractMessage>> result = new ArrayList<>(); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); ClassPath classpath = ClassPath.from(classloader); ImmutableSet<ClassInfo> xx = classpath.getTopLevelClassesRecursive("net.wizardsoflua.testenv.net"); Iterable<ClassInfo> yy = Iterables.filter(xx, input -> { Class<?> cls = input.load(); return AbstractMessage.class.isAssignableFrom(cls) && !Modifier.isAbstract(cls.getModifiers()); }); for (ClassInfo classInfo : yy) { result.add((Class<? extends AbstractMessage>) classInfo.load()); } return result; } catch (IOException e) { throw new UndeclaredThrowableException(e); } }
private void setClassesInProject(URLClassLoader urlClassLoader) { classesInProject = new HashSet<>(); Set<String> topLevelPackages = getTopLevelPackages(); if (topLevelPackages == null) return; for (String packageInProject : topLevelPackages) { try { Set<ClassPath.ClassInfo> classesInCurrentPackage = ClassPath.from(urlClassLoader).getTopLevelClassesRecursive(packageInProject); for (ClassPath.ClassInfo classInfo : classesInCurrentPackage) { classesInProject.add(classInfo.load()); } } catch (Exception e) { e.printStackTrace(); } } }
@API public static List<Class<?>> getClasses(String path) { try { ClassPath classPath = ClassPath.from(ClassUtil.class.getClassLoader()); Set<ClassInfo> classInfo = classPath.getTopLevelClassesRecursive(path); Iterator<ClassInfo> iterator = classInfo.iterator(); List<Class<?>> classes = new ArrayList<>(); while(iterator.hasNext()) { ClassInfo ci = iterator.next(); Optional<Class<?>> classOptional = getClass(ci.getName()); classOptional.ifPresent(classes::add); } return classes; } catch(IOException e) { throw new UncheckedIOException(e); } }
public static void unpackDummyResources(String prefix, Path output) throws IOException { ClassPath classPath = ClassPath.from(TestData.class.getClassLoader()); Map<String, URL> files = classPath.getResources().stream() .filter(info -> info.getResourceName().startsWith(prefix)) .collect(Collectors.toMap( info -> info.getResourceName().substring(prefix.length()), ClassPath.ResourceInfo::url) ); files.forEach((name, url) -> { Path file = output.resolve(name); try (InputStream is = url.openStream()) { Files.copy(is, file); } catch (IOException e) { throw new RuntimeException(String.format("name: %s, url: %s", name, url), e); } }); }
/** * Gets checkstyle's modules in the given package recursively. * @param packageName the package name to use * @param loader the class loader used to load Checkstyle package name * @return the set of checkstyle's module classes * @throws IOException if the attempt to read class path resources failed * @see ModuleReflectionUtils#isCheckstyleModule(Class) */ private static Set<Class<?>> getCheckstyleModulesRecursive( String packageName, ClassLoader loader) throws IOException { final ClassPath classPath = ClassPath.from(loader); final Set<Class<?>> result = new HashSet<Class<?>>(); for (ClassInfo clsInfo : classPath.getTopLevelClassesRecursive(packageName)) { final Class<?> cls = clsInfo.load(); if (ModuleReflectionUtils.isCheckstyleModule(cls) && !cls.getName().endsWith("Stub") && !cls.getCanonicalName() .startsWith("com.puppycrawl.tools.checkstyle.internal.testmodules") && !cls.getCanonicalName() .startsWith("com.puppycrawl.tools.checkstyle.packageobjectfactory")) { result.add(cls); } } return result; }
/** * @param basePackage base package for the factory to avoid scanning the whole classpath * @return list of factories */ @SuppressWarnings("unchecked") public List<Class<? extends FactoryBase>> get(String basePackage) { List<Class<? extends FactoryBase>> result = new ArrayList<>(); try { for (ClassPath.ClassInfo classInfo : ClassPath.from(ClasspathBasedFactoryProvider.class.getClassLoader()).getAllClasses()) { if (classInfo.getName().startsWith(basePackage)) { Class<?> clazz = classInfo.load(); if (FactoryBase.class.isAssignableFrom(clazz) && clazz != FactoryBase.class) { result.add((Class<FactoryBase>) clazz); } } } } catch (IOException e) { throw new RuntimeException(e); } return result; }
@Unsafe(Unsafe.ASM_API) private static void loadAllProvider() throws Exception { ClassPath path = ClassPath.from(AlchemyTransformerManager.class.getClassLoader()); for (ClassInfo info : path.getAllClasses()) if (info.getName().startsWith(MOD_PACKAGE)) { ClassReader reader = new ClassReader(info.url().openStream()); ClassNode node = new ClassNode(ASM5); reader.accept(node, 0); if (checkSideOnly(node)) { loadPatch(node); loadField(node); loadProxy(node); loadHook(node); loadTransform(node, info); } } }
public <T> List<Class<? extends T>> getClasses(Class<T> superType) throws IOException { classPath = ClassPath.from(this.getClass().getClassLoader()); ImmutableSet<ClassPath.ClassInfo> classInfos = classPath.getTopLevelClasses(packageName); List<Class<? extends T>> classes = new ArrayList<>(); for (ClassPath.ClassInfo classInfo : classInfos) { if (classInfo.load().isAnnotationPresent(annotationType)) { try { classes.add(classInfo.load().asSubclass(superType)); } catch (ClassCastException ex) { //Checks that the class is castable before casring it. } } } return classes; }
/** * Gets the set of all non-abstract classes implementing the {@link Command} interface (abstract * class and interface subtypes of Command aren't expected to have cli commands). Note that this * also filters out HelpCommand, which has special handling in {@link RegistryCli} and isn't in * the command map. * * @throws IOException if reading the classpath resources fails. */ @SuppressWarnings("unchecked") private ImmutableSet<Class<? extends Command>> getAllCommandClasses() throws IOException { ImmutableSet.Builder<Class<? extends Command>> builder = new ImmutableSet.Builder<>(); for (ClassInfo classInfo : ClassPath .from(getClass().getClassLoader()) .getTopLevelClassesRecursive(getPackageName(getClass()))) { Class<?> clazz = classInfo.load(); if (Command.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers()) && !Modifier.isInterface(clazz.getModifiers()) && !clazz.equals(HelpCommand.class)) { builder.add((Class<? extends Command>) clazz); } } return builder.build(); }
public Collection<Class> getAllModels() throws IOException { Class<Charge> chargeClass = Charge.class; ClassPath classPath = ClassPath.from(chargeClass.getClassLoader()); ImmutableSet<ClassPath.ClassInfo> topLevelClasses = classPath.getTopLevelClasses(chargeClass.getPackage().getName()); List<Class> classList = Lists.newArrayListWithExpectedSize(topLevelClasses.size()); for (ClassPath.ClassInfo classInfo : topLevelClasses) { Class c = classInfo.load(); // Skip things that aren't APIResources if (!APIResource.class.isAssignableFrom(c)) { continue; } // Skip the APIResource itself if (APIResource.class == c) { continue; } classList.add(classInfo.load()); } return classList; }
@Test public void serializableClassesMustDefineSerialVersionUID() throws IOException { List<Class<?>> serializableClassesWithoutSerialVersionUID = ClassPath .from(SerializableClassesTest.class.getClassLoader()) .getTopLevelClassesRecursive("no.digipost") .stream().map(ClassInfo::load) .flatMap(c -> Stream.concat(Stream.of(c), Stream.of(c.getDeclaredClasses()))) .filter(c -> !c.getName().contains("Test")) .filter(c -> !Enum.class.isAssignableFrom(c)) .filter(Serializable.class::isAssignableFrom) .filter(c -> { try { c.getDeclaredField("serialVersionUID"); return false; } catch (NoSuchFieldException e) { return true; } }).collect(toList()); assertThat(serializableClassesWithoutSerialVersionUID, empty()); }
@Listener public void onGameStart(GameAboutToStartServerEvent event) throws Exception { ClassPath.from(Thread.currentThread().getContextClassLoader()) .getTopLevelClassesRecursive("cz.neumimto.dei.listeners") .stream().map(ClassPath.ClassInfo::load) .filter(aClass -> aClass.isAnnotationPresent(ListenerClass.class)) .forEach(a -> { try { Sponge.getGame().getEventManager().registerListeners(this, a.newInstance()); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } }); jobRunner = new Thread(this::startScheduler); jobRunner.start(); CommandSpec myCommandSpec = CommandSpec.builder() .description(Text.of("Hello World Command")) .permission("myplugin.command.helloworld") //.executor() .build(); //Sponge.getCommandManager().register(plugin, myCommandSpec, "helloworld", "hello", "test"); }
public void registerHandlers(String packageName) { try { Set<ClassPath.ClassInfo> classes = ClassPath.from(MinecraftProtocol.class.getClassLoader()).getTopLevelClasses(packageName); for (ClassPath.ClassInfo classInfo : classes) { Class<?> clazz = classInfo.load(); if (!Handler.class.isAssignableFrom(clazz)) continue; this.registerHandler(((Class<? extends Handler>) clazz)); } } catch (IOException e) { throw new RuntimeException("Failed to register the handlers for package: \'" + packageName + "\'"); } }
private Set<ClassInfo> allClasses() { ClassPath cpScanner; try { cpScanner = ClassPath.from(ClasspathConstantScanner.class.getClassLoader()); } catch (IOException e) { LOGGER.warn("Cannot scan classes. No Constants will be returned."); return Collections.emptySet(); } return cpScanner.getTopLevelClasses().stream().filter(ci -> { if (basePackages.isEmpty()) { return true; } else { return basePackages.stream().anyMatch(p -> ci.getPackageName().startsWith(p)); } }).collect(Collectors.toSet()); }
/** * Main entrypoint for raml generation * @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(); }
protected void scanPack(String pack, ClassPath classPath) throws MojoExecutionException, IOException { this.getLog().info("Scanning package " + pack); if (Strings.isNullOrEmpty(pack)) { ClassLoaderUtils.restoreOriginalClassLoader(); throw new MojoExecutionException("Invalid target package: " + pack); } for (ClassPath.ClassInfo classInfo : classPath.getTopLevelClasses(pack)) { try { Class<?> c = classInfo.load(); if (!ignoredList.contains(c.getPackage().getName()) && !ignoredList.contains(c.getName())) { scanClass(c); } } catch (Throwable ex) { this.getLog().warn("Skipping Class: Unable to load" + classInfo.getName(), ex); } } }
@PostConstruct public void initialize() { annotationByServiceInterface = new HashMap<>(); ImmutableSet<ClassInfo> classInfos; try { classInfos = ClassPath.from(DiqubeThriftServiceInfoManager.class.getClassLoader()).getTopLevelClassesRecursive(BASE_PKG); } catch (IOException e) { throw new RuntimeException("Could not parse ClassPath."); } for (ClassInfo classInfo : classInfos) { Class<?> clazz = classInfo.load(); DiqubeThriftService annotation = clazz.getAnnotation(DiqubeThriftService.class); if (annotation != null) annotationByServiceInterface.put(annotation.serviceInterface(), new DiqubeThriftServiceInfo<>(annotation)); } logger.info("Found {} diqube services in {} scanned classes.", annotationByServiceInterface.size(), classInfos.size()); }
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); } } new Tool(toolFunctions).execute(args); }
private Map<String, Pair<AbstractActualIdentityToolFunction, IsActualIdentityToolFunction>> loadActualFunctions() { try { Collection<ClassInfo> classInfos = ClassPath.from(getClass().getClassLoader()).getTopLevelClassesRecursive(BASE_PKG); Map<String, Pair<AbstractActualIdentityToolFunction, IsActualIdentityToolFunction>> toolFunctions = new HashMap<>(); for (ClassInfo classInfo : classInfos) { Class<?> clazz = classInfo.load(); IsActualIdentityToolFunction isActualIdentityToolFunctionAnnotation = clazz.getAnnotation(IsActualIdentityToolFunction.class); if (isActualIdentityToolFunctionAnnotation != null) { AbstractActualIdentityToolFunction functionInstance = (AbstractActualIdentityToolFunction) clazz.newInstance(); toolFunctions.put(isActualIdentityToolFunctionAnnotation.identityFunctionName(), new Pair<>(functionInstance, isActualIdentityToolFunctionAnnotation)); } } return toolFunctions; } catch (IOException | InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } }
private static Map<CukesComponent, Multimap<StepType, StepDefinition>> collectSteps() throws IOException, ClassNotFoundException { Map<CukesComponent, Multimap<StepType, StepDefinition>> steps = createStepsStubs(); ClassPath classPath = ClassPath.from(DocumentationGenerator.class.getClassLoader()); ImmutableSet<ClassPath.ClassInfo> classes = classPath.getTopLevelClassesRecursive("lv.ctco.cukes"); for (ClassPath.ClassInfo classInfo : classes) { String className = classInfo.getName(); Class<?> aClass = Class.forName(className); Method[] methods = aClass.getMethods(); for (Method method : methods) { StepType type = StepType.getTypeForMethod(method); if (type != null) { CukesComponent component = CukesComponent.findByClassName(className); steps.get(component).put(type, new StepDefinition(type.getPattern(method), type.getDescription(method))); } } } return steps; }
static ImmutableList<TestResource> list() { if (cachedTestResources != null) { return cachedTestResources; } try { ImmutableList.Builder<TestResource> result = ImmutableList.builder(); ClassPath classPath = ClassPath.from(TestResource.class.getClassLoader()); for (ClassPath.ResourceInfo resource : classPath.getResources()) { String resourceName = resource.getResourceName(); if (resourceName.endsWith(DOC_COMMENT_EXTENSION)) { String resourceNameWithoutExtension = resourceName.substring(0, resourceName.length() - DOC_COMMENT_EXTENSION.length()); result.add(new TestResource(resourceNameWithoutExtension)); } } cachedTestResources = result.build(); return cachedTestResources; } catch (IOException e) { throw new RuntimeException(e); } }
@SuppressWarnings("unchecked") private List<OperationMetaData> createBasicOperations() { try { ClassPath cp = ClassPath.from(getClass().getClassLoader()); return cp.getAllClasses().stream() .filter(ci -> ci.getName().startsWith("edu.wpi.grip.core.operations")) .map(ClassPath.ClassInfo::load) .filter(Operation.class::isAssignableFrom) .map(c -> (Class<? extends Operation>) c) .filter(c -> c.isAnnotationPresent(Description.class)) .map(c -> new OperationMetaData(descriptionFor(c), () -> injector.getInstance(c))) .collect(Collectors.toList()); } catch (IOException e) { logger.log(Level.WARNING, "Could not discover operations", e); return ImmutableList.of(); } }
/** * Finds all subclasses of {@link Publishable} in {@code edu.wpi.grip.core.operation}. */ @SuppressWarnings("unchecked") private List<Class<Publishable>> findPublishables() { if (publishableTypes == null) { // Only need to search once try { ClassPath cp = ClassPath.from(getClass().getClassLoader()); publishableTypes = cp.getAllClasses().stream() // only look in our namespace (don't want to wade through tens of thousands of classes) .filter(ci -> ci.getName().startsWith("edu.wpi.grip.core.operation")) .map(ClassPath.ClassInfo::load) .filter(Publishable.class::isAssignableFrom) // only accept concrete top-level subclasses .filter(c -> !c.isAnonymousClass() && !c.isInterface() && !c.isLocalClass() && !c.isMemberClass()) .filter(c -> Modifier.isPublic(c.getModifiers())) .map(c -> (Class<Publishable>) c) .collect(Collectors.toList()); } catch (IOException e) { logger.log(Level.WARNING, "Could not find the publishable types.", e); publishableTypes = ImmutableList.of(); } } return publishableTypes; }
public static List<WTSPlugin> allWTSPlugins() { try { return allPlugins.get("all", () -> { final List<WTSPlugin> found = new ArrayList<WTSPlugin>(); final ClassLoader loader = currentThread().getContextClassLoader(); for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) { if (info.getName().startsWith("se.softhouse")) { final Class<?> clazz = info.load(); if (WTSPlugin.class.isAssignableFrom(clazz) && !clazz.isAssignableFrom(WTSPlugin.class)) { final WTSPlugin plugin = (WTSPlugin) clazz.newInstance(); found.add(plugin); } } } found.forEach((it) -> it.init()); return found; }); } catch (final Exception e) { propagate(e); return null; } }
public void tesstByteBuf() throws InterruptedException, IOException { ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); ClassPath from = ClassPath.from(systemClassLoader); StdInstantiatorStrategy instantiator = new StdInstantiatorStrategy(); Class<Request> requestClazz = Request.class; for (ClassPath.ClassInfo clazz : from.getAllClasses()) { Class<?> load; try { load = clazz.load(); } catch (NoClassDefFoundError e) { continue; } for (Class<?> aClass : load.getInterfaces()) { if (aClass.equals(requestClazz)) { Object o = instantiator.newInstantiatorOf(aClass).newInstance(); testByteBuf((Request) o); } } } }
@Test public void testCopy() throws IOException { // We use top level classes to ignore node types defined as inner classes for tests. ImmutableSet<ClassInfo> topLevelClasses = ClassPath.from(ClassLoader.getSystemClassLoader()).getTopLevelClasses(); Set<String> errors = new LinkedHashSet<>(); for (ClassInfo clazz : topLevelClasses) { if (clazz.getPackageName().startsWith("com.google.template.soy")) { Class<?> cls = clazz.load(); if (Node.class.isAssignableFrom(cls)) { if (cls.isInterface()) { continue; } if (Modifier.isAbstract(cls.getModifiers())) { checkAbstractNode(cls, errors); } else { checkConcreteNode(cls, errors); } } } } if (!errors.isEmpty()) { fail("Copy policy failure:\n" + Joiner.on('\n').join(errors)); } }
private Set<ClassPath.ClassInfo> getRecognizedClasses(ClassLoader classLoader, List<String> packages) { Set<ClassPath.ClassInfo> result = new HashSet<>(); try { ClassPath classPath = ClassPath.from(classLoader); for (ClassPath.ClassInfo classInfo : classPath.getAllClasses()) { String packageName = classInfo.getPackageName(); for (String aPackage : packages) { if (packageName.startsWith(aPackage)) { result.add(classInfo); } } } } catch (IOException e) { logger.severe("Cannot create ClassPath: " + e); } return result; }
/** Finds all classes that live in or below the given package. */ public static Set<Class<?>> findClasses(String packageName) throws ClassPathException { Set<Class<?>> result = new LinkedHashSet<>(); String packagePrefix = (packageName + '.').replace('/', '.'); try { for (ClassInfo ci : ClassPath.from(Classpath.class.getClassLoader()).getAllClasses()) { if (ci.getName().startsWith(packagePrefix)) { try { result.add(ci.load()); } catch (UnsatisfiedLinkError | NoClassDefFoundError unused) { // Ignore: we're most likely running on a different platform. } } } } catch (IOException e) { throw new ClassPathException(e.getMessage()); } return result; }
public static Set< String > determineInstrumentableClasses() throws Throwable { TaxonomyLoader loader = new AgentTaxonomyLoader(); Set< ResourceInfo > resources = ClassPath.from( loader.getClassLoader() ).getResources(); Set< Class< ? > > viewedClasses = new HashSet< Class< ? > >(); resources.stream() .filter( resourceInfo -> resourceInfo.getResourceName().endsWith( ".tax" ) ) .map( resourceInfo -> getTaxonomy( loader, resourceInfo.getResourceName() ) ) .filter( taxonomy -> taxonomy != null ) .forEach( taxonomy -> viewedClasses.addAll( getViewedClasses( taxonomy ) ) ); Set< String > instrumentableClassNames = viewedClasses.stream() .filter( viewedClass -> isTopLevelClass( viewedClass, viewedClasses ) ) .map( viewedClass -> viewedClass.getName() ) .collect( Collectors.toSet() ); return instrumentableClassNames; }
@Override public ImmutableSet<String> resolve(ProjectFilesystem filesystem, Path relativeClassPath) { ImmutableSet.Builder<String> topLevelSymbolsBuilder = ImmutableSet.builder(); try { Path classPath = filesystem.getFileForRelativePath(relativeClassPath).toPath(); ClassLoader loader = URLClassLoader.newInstance( new URL[]{classPath.toUri().toURL()}, /* parent */ null); // For every class contained in that jar, check to see if the package name // (e.g. com.facebook.foo), the simple name (e.g. ImmutableSet) or the name // (e.g com.google.common.collect.ImmutableSet) is one of the missing symbols. for (ClassPath.ClassInfo classInfo : ClassPath.from(loader).getTopLevelClasses()) { topLevelSymbolsBuilder.add(classInfo.getPackageName(), classInfo.getSimpleName(), classInfo.getName()); } } catch (IOException e) { // Since this simply is a heuristic, return an empty set if we fail to load a jar. return topLevelSymbolsBuilder.build(); } return topLevelSymbolsBuilder.build(); }
/** * Javadoc. */ @Parameters(name = "class={0}") public static Collection<Object[]> params() throws Exception { ClassLoader loader = ChannelAndServerBuilderTest.class.getClassLoader(); List<Object[]> classes = new ArrayList<Object[]>(); for (ClassInfo classInfo : ClassPath.from(loader).getTopLevelClassesRecursive("io.grpc")) { Class<?> clazz = Class.forName(classInfo.getName(), false /*initialize*/, loader); if (ServerBuilder.class.isAssignableFrom(clazz) && clazz != ServerBuilder.class) { classes.add(new Object[]{clazz}); } else if (ManagedChannelBuilder.class.isAssignableFrom(clazz) && clazz != ManagedChannelBuilder.class ) { classes.add(new Object[]{clazz}); } } Truth.assertWithMessage("Unable to find any builder classes").that(classes).isNotEmpty(); return classes; }
private static Set<TypeToken<?>> getPackageClassesFromClasspathJars(String packageName, ClassLoader classLoader) throws IOException { ImmutableSet<ClassInfo> classesInfo = ClassPath.from(classLoader).getTopLevelClassesRecursive(packageName); Set<TypeToken<?>> classesInPackage = new HashSet<>(); for (ClassInfo classInfo : classesInfo) { classesInPackage.add(TypeToken.of(classInfo.load())); } Set<TypeToken<?>> filteredClassesInPackage = new HashSet<>(); for (TypeToken<?> classFromJar : classesInPackage) { if (isClassCandidateToAssertionsGeneration(classFromJar)) { filteredClassesInPackage.add(classFromJar); } } return filteredClassesInPackage; }