Java Code Examples for io.github.classgraph.ClassGraph#scan()

The following examples show how to use io.github.classgraph.ClassGraph#scan() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestDataMap.java    From justtestlah with Apache License 2.0 7 votes vote down vote up
private void initializeTestDataObjectRegistry() {
  LOG.info("Initialising test data object registry");
  LOG.info("Scanning classpath for test data classes");
  ClassGraph classGraph = new ClassGraph().enableAnnotationInfo();
  if (modelPackage != null && !modelPackage.isEmpty()) {
    classGraph = classGraph.whitelistPackages(modelPackage);
  }
  try (ScanResult scanResult = classGraph.scan()) {
    for (ClassInfo routeClassInfo :
        scanResult.getClassesWithAnnotation(TestData.class.getName())) {
      Class<?> type = routeClassInfo.loadClass();

      String name = type.getAnnotation(TestData.class).value();
      if (name.isEmpty()) {
        name = type.getSimpleName();
        name = name.substring(0, 1).toLowerCase() + name.substring(1);
      }
      LOG.info("Register class {} as {}", type, name);
      registry.register(type, name);
    }
  }
}
 
Example 2
Source File: StartupContext.java    From vertx-vaadin with MIT License 6 votes vote down vote up
private static Handler<Promise<Set<String>>> scanResources(VaadinOptions vaadinOptions) {
    ClassGraph classGraph = new ClassGraph()
        .whitelistPaths()
        .removeTemporaryFilesAfterScan();
    if (vaadinOptions.debug()) {
        classGraph.verbose();
    }
    return future -> {
        try (ScanResult scanResult = classGraph.scan()) {
            future.complete(
                scanResult.getAllResources()
                    .nonClassFilesOnly()
                    .stream()
                    .map(Resource::getPathRelativeToClasspathElement)
                    .collect(Collectors.toSet())
            );
        } catch (Exception ex) {
            future.fail(ex);
        }
    };
}
 
Example 3
Source File: ClasspathScanner.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public String[] getSystemClasspath() {
	if (systemClasspath != null) {
		return systemClasspath;
	}
	ClassGraph classGraph = classGraphProvider.get()
		.enableSystemJarsAndModules()
		.addClassLoader(ClassLoader.getSystemClassLoader());
	try (ScanResult scanResult = classGraph.scan()) {
		List<URI> classpathURIs = scanResult.getClasspathURIs();
		systemClasspath = classpathURIs.stream()
			.map(URI::getPath)
			.filter(Objects::nonNull)
			.toArray(String[]::new);
		return systemClasspath;
	}
}
 
Example 4
Source File: SpringBootAnnotationConfigProvider.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
private Set<Class<?>> scanClasses(final Set<Class<? extends Annotation>> supportedAnnotations) {
	Set<Class<?>> result = new LinkedHashSet<>();

	ClassGraph classGraph = new ClassGraph()
			.enableAllInfo()
			.enableExternalClasses();
	List<String> basePackages = this.properties.getBasePackages();
	if (basePackages != null && !basePackages.isEmpty()) {
		classGraph = classGraph.whitelistPackages(basePackages.toArray(new String[0]));
	}

	try (ScanResult scanResult = classGraph.scan()) {
		for (final Class<? extends Annotation> supportedAnnotation : supportedAnnotations) {
			result.addAll(scanResult.getClassesWithAnnotation(supportedAnnotation.getName()).loadClasses(true));
			result.addAll(scanResult.getClassesWithMethodAnnotation(supportedAnnotation.getName()).loadClasses(true));
			result.addAll(scanResult.getClassesWithFieldAnnotation(supportedAnnotation.getName()).loadClasses(true));
		}
	}

	return result;
}
 
Example 5
Source File: ClasspathScanner.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "https://github.com/spotbugs/spotbugs/issues/756")
public void scanClasses() throws IOException {

	ClassGraph classGraph = new ClassGraph()
			.enableAllInfo()
			.enableExternalClasses()
			.enableSystemJarsAndModules();

	classGraph = getClassGraphConfigurer().apply(classGraph);

	try (ScanResult scanResult = classGraph.scan()) {
		for (ScanResultHandler scanResultHandler : ServiceLoader.load(ScanResultHandler.class)) {
			scanResultHandler.handle(scanResult, getClasspathRoot());
		}
	}
}
 
Example 6
Source File: Input.java    From typescript-generator with MIT License 6 votes vote down vote up
public ScanResult getScanResult() {
    if (scanResult == null) {
        TypeScriptGenerator.getLogger().info("Scanning classpath");
        final Date scanStart = new Date();
        ClassGraph classGraph = new ClassGraph()
                .enableClassInfo()
                .enableAnnotationInfo()
                .ignoreClassVisibility();
        if (classLoader != null) {
            classGraph = classGraph.overrideClasspath((Object[])classLoader.getURLs());
        }
        if (verbose) {
            classGraph = classGraph.verbose();
        }
        final ScanResult result = classGraph.scan();
        final int count = result.getAllClasses().size();
        final Date scanEnd = new Date();
        final double timeInSeconds = (scanEnd.getTime() - scanStart.getTime()) / 1000.0;
        TypeScriptGenerator.getLogger().info(String.format("Scanning finished in %.2f seconds. Total number of classes: %d.", timeInSeconds, count));
        scanResult = result;
    }
    return scanResult;
}
 
Example 7
Source File: Mapper.java    From morphia with Apache License 2.0 6 votes vote down vote up
private Set<Class<?>> getClasses(final ClassLoader loader, final String packageName, final boolean mapSubPackages)
    throws ClassNotFoundException {
    final Set<Class<?>> classes = new HashSet<>();

    ClassGraph classGraph = new ClassGraph()
                                .addClassLoader(loader)
                                .enableAllInfo();
    if (mapSubPackages) {
        classGraph.whitelistPackages(packageName);
        classGraph.whitelistPackages(packageName + ".*");
    } else {
        classGraph.whitelistPackagesNonRecursive(packageName);
    }

    try (ScanResult scanResult = classGraph.scan()) {
        for (final ClassInfo classInfo : scanResult.getAllClasses()) {
            classes.add(Class.forName(classInfo.getName(), true, loader));
        }
    }
    return classes;
}
 
Example 8
Source File: SerializerRegistryImpl.java    From fabric-chaincode-java with Apache License 2.0 5 votes vote down vote up
/**
 * Find all the serializers that have been defined.
 *
 * @see org.hyperledger.fabric.contract.routing.RoutingRegistry#findAndSetContracts()
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public void findAndSetContents() throws InstantiationException, IllegalAccessException {

    final ClassGraph classGraph = new ClassGraph().enableClassInfo().enableAnnotationInfo();

    // set to ensure that we don't scan the same class twice
    final Set<String> seenClass = new HashSet<>();

    try (ScanResult scanResult = classGraph.scan()) {
        for (final ClassInfo classInfo : scanResult.getClassesWithAnnotation(this.annotationClass.getCanonicalName())) {
            logger.debug("Found class with contract annotation: " + classInfo.getName());
            try {
                final Class<SerializerInterface> cls = (Class<SerializerInterface>) classInfo.loadClass();
                logger.debug("Loaded class");

                final String className = cls.getCanonicalName();
                if (!seenClass.contains(className)) {
                    seenClass.add(className);
                    this.add(className, Serializer.TARGET.TRANSACTION, cls);
                }

            } catch (final IllegalArgumentException e) {
                logger.debug("Failed to load class: " + e);
            }
        }

    }

}
 
Example 9
Source File: ClasspathScanner.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Iterable<ITypeDescriptor> loadDescriptors(ClassLoader classLoader, boolean bootstrap,
		Collection<String> packagePrefixes) {
	ClassGraph classGraph = classGraphProvider.get()
		.ignoreClassVisibility()
		.enableClassInfo()
		.whitelistPackages(packagePrefixes.toArray(new String[packagePrefixes.size()]))
		.addClassLoader(classLoader);
	if (bootstrap) {
		classGraph.enableSystemJarsAndModules();
	}
	try (ScanResult scanResult = classGraph.scan()) {
		return loadDescriptors(scanResult);
	}
}
 
Example 10
Source File: ServletContainerInitializerRegistrationBean.java    From joinfaces with Apache License 2.0 4 votes vote down vote up
@Nullable
protected Set<Class<?>> performClasspathScan() {
	HandlesTypes handlesTypes = AnnotationUtils.findAnnotation(getServletContainerInitializerClass(), HandlesTypes.class);

	if (handlesTypes == null) {
		return null;
	}

	Class<?>[] handledTypes = handlesTypes.value();
	if (handledTypes.length == 0) {
		return null;
	}

	StopWatch stopWatch = new StopWatch(getServletContainerInitializerClass().getName());
	stopWatch.start("prepare");

	ClassGraph classGraph = new ClassGraph()
			.enableClassInfo();

	// Only scan for Annotations if we have to
	if (Arrays.stream(handledTypes).anyMatch(Class::isAnnotation)) {
		classGraph = classGraph.enableAnnotationInfo();
	}

	classGraph = classGraph.enableExternalClasses()
			.enableSystemJarsAndModules() // Find classes in javax.faces
			.blacklistPackages("java", "jdk", "sun", "javafx", "oracle")
			.blacklistPackages("javax.xml", "javax.el", "javax.persistence")
			.blacklistModules("java.*", "jdk.*")
			.filterClasspathElements(path -> {
				log.debug("Path {}", path);
				return true;
			});

	Set<Class<?>> classes = new HashSet<>();

	stopWatch.stop();
	stopWatch.start("classpath scan");

	try (ScanResult scanResult = classGraph.scan()) {

		stopWatch.stop();
		stopWatch.start("collect results");

		for (Class<?> handledType : handledTypes) {
			ClassInfoList classInfos;
			if (handledType.isAnnotation()) {
				classInfos = scanResult.getClassesWithAnnotation(handledType.getName());
			}
			else if (handledType.isInterface()) {
				classInfos = scanResult.getClassesImplementing(handledType.getName());
			}
			else {
				classInfos = scanResult.getSubclasses(handledType.getName());
			}
			classes.addAll(classInfos.loadClasses());
		}

		handleScanResult(scanResult);
	}
	finally {
		stopWatch.stop();
		log.info("Resolving classes for {} took {}s", getServletContainerInitializerClass().getName(), stopWatch.getTotalTimeSeconds());
		if (log.isDebugEnabled()) {
			log.debug(stopWatch.prettyPrint());
		}
	}

	return classes.isEmpty() ? null : classes;
}
 
Example 11
Source File: VertxRestService.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<RestService> start() {
  server = vertx.createHttpServer();
  deployment = new VertxResteasyDeployment();
  deployment.start();

  deployment.getDispatcher().getDefaultContextObjects()
      .put(ClusterMembershipService.class, atomix.getMembershipService());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(ClusterCommunicationService.class, atomix.getCommunicationService());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(ClusterEventService.class, atomix.getEventService());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(PrimitiveFactory.class, atomix.getPrimitivesService());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(PrimitivesService.class, atomix.getPrimitivesService());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(EventManager.class, new EventManager());
  deployment.getDispatcher().getDefaultContextObjects()
      .put(AtomixRegistry.class, atomix.getRegistry());

  final ClassLoader classLoader = atomix.getClass().getClassLoader();
  final String[] whitelistPackages = StringUtils.split(System.getProperty("io.atomix.whitelistPackages"), ",");
  final ClassGraph classGraph = whitelistPackages != null
      ? new ClassGraph().enableAnnotationInfo().whitelistPackages(whitelistPackages).addClassLoader(classLoader)
      : new ClassGraph().enableAnnotationInfo().addClassLoader(classLoader);

  try (final ScanResult scanResult = classGraph.scan()) {
    scanResult.getClassesWithAnnotation(AtomixResource.class.getName()).forEach(classInfo -> {
      deployment.getRegistry().addPerInstanceResource(classInfo.loadClass(), "/v1");
    });
  }

  deployment.getDispatcher().getProviderFactory().register(new JacksonProvider(createObjectMapper()));

  server.requestHandler(new VertxRequestHandler(vertx, deployment));

  CompletableFuture<RestService> future = new CompletableFuture<>();
  server.listen(address.port(), address.address(true).getHostAddress(), result -> {
    if (result.succeeded()) {
      open.set(true);
      LOGGER.info("Started");
      future.complete(this);
    } else {
      future.completeExceptionally(result.cause());
    }
  });
  return future;
}