public List<String> getGeneratedProtoClasses(String serviceName) { FastClasspathScanner cpScanner = new FastClasspathScanner(); ScanResult scanResult = cpScanner.scan(); List<String> oldProtobuf = scanResult.getNamesOfSubclassesOf(GeneratedMessage.class); List<String> newProtobuf = scanResult.getNamesOfSubclassesOf(GeneratedMessageV3.class); List<String> retval = Stream.concat(oldProtobuf.stream(), newProtobuf.stream()).collect(Collectors.toList()); String[] packageTokens = serviceName.split("\\."); return retval.stream().filter(s -> protoFilePackageMatches(s, packageTokens)).collect(Collectors.toList()); }
public ClassPathSearch(Class<?>... classesOfInterest) { this.classesOfInterestInfos = Stream.of(classesOfInterest) .map(c -> c.getName().replace('.', '/')) .map(this::getClassInfo) .toArray(ClassInfo[]::new); for (String rn : new FastClasspathScanner().scan().getNamesOfAllClasses()) { classes.putIfAbsent(rn, new ClassInfo(rn)); } unprocessed.addAll(classes.keySet()); }
private Object findPlugin(Injector injector) { Object retval = null; ServiceProperties serviceProperties = injector.getInstance(ServiceProperties.class); String pluginName = serviceProperties.getProperty("metricsReporter"); if (StringUtils.isBlank(pluginName)) { return null; } if (plugins == null) { // only scan if not already set plugins = new FastClasspathScanner().scan().getNamesOfClassesWithAnnotation(MetricsReporterPlugin.class); } boolean found = false; for (String plugin : plugins) { try { @SuppressWarnings("unchecked") Class<? extends MetricsReporterPlugin> pluginClass = (Class<? extends MetricsReporterPlugin>) Class.forName(plugin); MetricsReporterPlugin anno = pluginClass.getAnnotation(MetricsReporterPlugin.class); if (anno != null && pluginName.equals(anno.name())) { retval = injector.getInstance(pluginClass); found = true; break; } } catch (ClassNotFoundException e) { logger.error("MetricsReporterPlugin not found", e); } } if (! found) { logger.warn("Metrics reporting plugin '{}' was not found in the class path", pluginName); } return retval; }
/** Return a set of sub types for the given super type. Scans the full classpath. */ @SuppressWarnings("unchecked") public static <T> Set<Class<? extends T>> getSubTypes(Class<T> superType) { if (scanResult == null) { getInstance(); } List<String> classNames; if (superType.isInterface()) { classNames = scanResult.getNamesOfClassesImplementing(superType); } else { classNames = scanResult.getNamesOfSubclassesOf(superType); } Set<Class<? extends T>> ret = new HashSet<>(); scanResult.classNamesToClassRefs(classNames).forEach(c -> ret.add((Class<? extends T>) c)); return ret; }
result.getNamesOfClassesWithAnnotation(Path.class) .stream() .filter(once) result.getNamesOfSubclassesOf(Jooby.class) .stream() .filter(once) .forEach(a -> result.getNamesOfClassesWithAnnotation(a) .stream() .filter(once) .filter(I) .filter(type -> type != Jooby.Module.class && type != Module.class && type != Service.class) .forEach(i -> result.getNamesOfClassesImplementing(i) .stream() .filter(inPackage) .forEach(k -> result.getNamesOfSubclassesOf(k) .stream() .filter(inPackage) result.getNamesOfClassesImplementing(Module.class) .stream() .filter(inPackage) result.getNamesOfClassesImplementing(Service.class) .stream() .filter(inPackage)
private static void ensureInit() { if (!init) { synchronized (BeanPopulators.class) { if (!init) { log.info("Init bean populators ..."); ScanResult result = AutumnClasspathScan.getScanResult(); result.getNamesOfSubclassesOf(AnnotatedFieldPopulator.class).forEach(cn -> { try { AnnotatedFieldPopulator<?> populator = (AnnotatedFieldPopulator<?>) result.classNameToClassRef(cn).newInstance(); annotatedFieldPopulatorMap.put(populator.getAnnotationClass(), populator); } catch (Exception e) { log.warn("Cannot init bean populator [{}]: {}", cn, String.valueOf(e)); } }); init = true; } } } }
/** * Get a class reference for this class. Causes the ClassLoader to load the class. * * @return The class reference. * @throws IllegalArgumentException * if there were problems loading or initializing the class. (Note that class initialization on load * is disabled by default, you can enable it with * {@code FastClasspathScanner#initializeLoadedClasses(true)} .) */ public Class<?> getClassRef() { return scanResult.classNameToClassRef(className); }
private void writeApis(ApiPrintWriter writer, ScanResult result) { Map<String, ClassInfo> allInfo = result.getClassNameToClassInfo(); result.getNamesOfAllClasses().forEach(className -> { if (className.contains(".internal.")) { Class<?> javaClass = result.classNameToClassRef(className); if (!isVisible(javaClass.getModifiers())) {
@SuppressWarnings("unchecked") public synchronized void scanAnnotations() { log.info("Scanning annotations ..."); ScanResult result = AutumnClasspathScan.getScanResult(); result.getNamesOfClassesWithAnnotation(WebServlet.class).forEach(cn -> { Class<?> cls = result.classNameToClassRef(cn); if (HttpServlet.class.isAssignableFrom(cls)) { WebServlet ws = cls.getAnnotation(WebServlet.class); TPServletRegistration registration = this.addServlet( ws.name().isEmpty() ? cn : ws.name(), (Class<? extends Servlet>) cls); registration.loadAnnotation(ws); } }); result.getNamesOfClassesWithAnnotation(WebFilter.class).forEach(cn -> { Class<?> cls = result.classNameToClassRef(cn); if (HttpFilter.class.isAssignableFrom(cls)) { WebFilter wf = cls.getAnnotation(WebFilter.class); TPFilterRegistration registration = this.addFilter( wf.filterName().isEmpty() ? cn : wf.filterName(), (Class<? extends Filter>) cls); registration.loadAnnotation(wf); } }); result.getNamesOfClassesWithAnnotation(WebListener.class).forEach(cn -> { Class<?> cls = result.classNameToClassRef(cn); if (EventListener.class.isAssignableFrom(cls)) { this.addListener((Class<? extends EventListener>) cls); } }); }
private static void ensureInit() { if (!init) { synchronized (BeanProcessors.class) { if (!init) { log.info("Init bean processors ..."); ScanResult result = AutumnClasspathScan.getScanResult(); result.getNamesOfClassesImplementing(BeanProcessor.class).forEach(cn -> { try { Class<? extends BeanProcessor> processorClass = (Class<? extends BeanProcessor>) result.classNameToClassRef(cn); BeanProcessor processor = processorClass.newInstance(); for (Class<?> intf : processorClass.getInterfaces()) { if (BeanProcessor.class.isAssignableFrom(intf)) { beanProcessors.computeIfAbsent((Class<? extends BeanProcessor>) intf, x -> new ArrayList<>()).add(processor); } } } catch (Exception e) { log.warn("Cannot init bean processor [{}]: {}", cn, String.valueOf(e)); } }); init = true; } } } }
@Override public Set<Field> getFieldsAnnotatedWith(Class clazz) { Map<String, ClassInfo> classInfos = scanResult.getClassNameToClassInfo(); Set<FieldIdentifier> fieldIdentifiers = new HashSet<>(); for (ClassInfo classInfo : classInfos.values()){ for (FieldInfo fieldInfo : classInfo.getFieldInfo()) { List<AnnotationInfo> fieldsAnnotationInfos = fieldInfo.getAnnotationInfo(); for (AnnotationInfo oneFieldAnnotation: fieldsAnnotationInfos) { if (oneFieldAnnotation.getAnnotationType() == clazz) { fieldIdentifiers.add(new FieldIdentifier(fieldInfo.getClassName(), fieldInfo.getFieldName(), fieldInfo.getType())); } } } } Set<Field> fields = new HashSet<>(fieldIdentifiers.size()); for (FieldIdentifier fieldIdentifier : fieldIdentifiers) { Class<?> classe = scanResult.classNameToClassRef(fieldIdentifier.getClassName()); for (Field field : classe.getDeclaredFields()) { if (fieldIdentifier.matchesField(classe, field)){ fields.add(field); } } } return fields; }
@Override public void lookForMatches(final ScanResult scanResult, final LogNode log) { final String superclassName = getStandardClassName(superclass); for (final String subclassName : scanResult.getNamesOfSubclassesOf(superclassName)) { LogNode subLog = null; if (log != null) { subLog = log.log("Matched subclass of " + superclassName + ": " + subclassName); } try { // Call classloader @SuppressWarnings("unchecked") final Class<? extends T> cls = (Class<? extends T>) loadClassForMatchProcessor(subclassName, scanResult, log); // Process match if (cls != null) { subclassMatchProcessor.processMatch(cls); } } catch (final Throwable e) { if (subLog != null) { subLog.log("Exception while processing match for class " + subclassName, e); } scanResult.addMatchProcessorException(e); } } } });
private List<String> getEntityClassNames(URL[] classPath) { this.logger.debug("basePackages = " + Arrays.toString(this.basePackages)); this.logger.debug("classPath = " + Arrays.toString(classPath)); final FastClasspathScanner classpathScanner = new FastClasspathScanner(this.basePackages).overrideClasspath((Object[]) classPath); final ScanResult scanResult = classpathScanner.scan(); this.logger.debug(scanResult.getNamesOfAllClasses().toString()); return scanResult.getNamesOfClassesWithAnnotationsAnyOf(Entity.class, MappedSuperclass.class, Embeddable.class, Converter.class); }
@Override public void lookForMatches(final ScanResult scanResult, final LogNode log) { for (final String className : scanResult.getNamesOfAllClasses()) { LogNode subLog = null; if (log != null) { subLog = log.log("Matched class: " + className); } try { // Call classloader final Class<?> cls = loadClassForMatchProcessor(className, scanResult, log); // Process match if (cls != null) { classMatchProcessor.processMatch(cls); } } catch (final Throwable e) { if (subLog != null) { subLog.log("Exception while processing match for class " + className, e); } scanResult.addMatchProcessorException(e); } } } });
@Override public void lookForMatches(final ScanResult scanResult, final LogNode log) { final String annotationName = getAnnotationName(annotation); for (final String classWithAnnotation : scanResult .getNamesOfClassesWithAnnotation(annotationName)) { LogNode subLog = null; if (log != null) { subLog = log.log( "Matched class with annotation " + annotationName + ": " + classWithAnnotation); } try { // Call classloader final Class<?> cls = loadClassForMatchProcessor(classWithAnnotation, scanResult, log); // Process match if (cls != null) { classAnnotationMatchProcessor.processMatch(cls); } } catch (final Throwable e) { if (subLog != null) { subLog.log("Exception while processing match for class " + classWithAnnotation, e); } scanResult.addMatchProcessorException(e); } } } });
/** * Get the names of all classes that implement (or have superclasses that implement) the given interface (or one * of its subinterfaces). * * @param implementedInterface * The interface. * @return The sorted list of the names of all classes that implement the given interface, or the empty list if * none. */ public List<String> getNamesOfClassesImplementing(final Class<?> implementedInterface) { return getNamesOfClassesImplementing(scanSpec.getInterfaceName(implementedInterface)); }
@Override public void lookForMatches(final ScanResult scanResult, final LogNode log) { final String implementedInterfaceName = getInterfaceName(implementedInterface); for (final String implementingClassName : scanResult .getNamesOfClassesImplementing(implementedInterfaceName)) { LogNode subLog = null; if (log != null) { subLog = log.log("Matched class implementing interface " + implementedInterfaceName + ": " + implementingClassName); } try { // Call classloader @SuppressWarnings("unchecked") final Class<? extends T> cls = (Class<? extends T>) loadClassForMatchProcessor( implementingClassName, scanResult, log); // Process match if (cls != null) { implementingClassMatchProcessor.processMatch(cls); } } catch (final Throwable e) { if (subLog != null) { subLog.log("Exception while processing match for class " + implementingClassName, e); } scanResult.addMatchProcessorException(e); } } } });
matches = scanResults.getClassNameToClassInfo().values().stream() .filter(ci -> ci.hasSuperclass(superClass.getName()) || ci.implementsInterface(superClass.getName())) .filter(ci -> ci.hasAnnotation(annotationClass.getName())).map(ClassInfo::getClassName) + "' and super class '" + superClass.getName() + "'"); } else { matches = scanResults.getClassNameToClassInfo().values().stream() .filter(ci -> ci.hasAnnotation(annotationClass.getName())).map(ClassInfo::getClassName) .collect(Collectors.toList());
/** * Produce a list of Class references given a list of class names. If any classes cannot be loaded (due to * classloading error, or due to an exception being thrown in the class initialization block), * IllegalArgumentException will be thrown. * * @param classNames * The list of names of classes to load. * @throws IllegalArgumentException * if there were problems loading or initializing the classes. (Note that class initialization on * load is disabled by default, you can enable it with * {@code FastClasspathScanner#initializeLoadedClasses(true)} .) * @return a list of references to the loaded classes. */ public List<Class<?>> classNamesToClassRefs(final List<String> classNames) throws IllegalArgumentException { return classNamesToClassRefs(classNames, /* ignoreExceptions = */ false); }
/** Return a set of sub types for the given super type. Scans the full classpath. */ @SuppressWarnings("unchecked") public static <T> Set<Class<? extends T>> getSubTypes(Class<T> superType) { if (scanResult == null) { getInstance(); } List<String> classNames; if (superType.isInterface()) { classNames = scanResult.getNamesOfClassesImplementing(superType); } else { classNames = scanResult.getNamesOfSubclassesOf(superType); } Set<Class<? extends T>> ret = new HashSet<>(); scanResult.classNamesToClassRefs(classNames).forEach(c -> ret.add((Class<? extends T>) c)); return ret; }