io.github.classgraph.ClassGraph Java Examples

The following examples show how to use io.github.classgraph.ClassGraph. 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: 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 #3
Source File: DescribeBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<Class<?>> scanJaxrsClass() throws Exception {
	try (ScanResult scanResult = new ClassGraph().disableJarScanning().enableAnnotationInfo().scan()) {
		SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
		for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
			Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
			for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
					"getClasses")) {
				Path path = o.getAnnotation(Path.class);
				JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
				if (null != path && null != jaxrsDescribe) {
					classes.add(o);
				}
			}
		}
		return classes;
	}
}
 
Example #4
Source File: CreateWebXml.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String metadataCompleteFalse(String project, String thisApplicationClassName) throws Exception {
	Class<?> thisApplication = Class.forName(thisApplicationClassName);
	try (ScanResult scanResult = new ClassGraph().enableAnnotationInfo()
			.whitelistPackages(thisApplication.getPackage().getName(), Compilable.class.getPackage().getName())
			.scan()) {
		StringBuffer sb = new StringBuffer();
		String moduleClassName = moduleClassName(scanResult, project);
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		sb.append("<web-app id=\"" + project + "\" metadata-complete=\"false\" version=\"3.0\">");
		sb.append("<display-name>" + project + "</display-name>");
		sb.append("<context-param>");
		sb.append("<param-name>project</param-name>");
		sb.append("<param-value>" + moduleClassName + "</param-value>");
		sb.append("</context-param>");
		sb.append("</web-app>");
		return sb.toString();
	}
}
 
Example #5
Source File: Describe.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<Class<?>> scanJaxrsClass(String name) throws Exception {
	// String pack = "com." + name.replaceAll("_", ".");
	String pack = "";
	if (StringUtils.startsWith(name, "o2_")) {
		pack = name.replaceAll("_", ".");
	} else {
		pack = "com." + name.replaceAll("_", ".");
	}
	try (ScanResult scanResult = new ClassGraph().whitelistPackages(pack).enableAllInfo().scan()) {
		SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
		for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
			Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
			for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
					"getClasses")) {
				Path path = o.getAnnotation(Path.class);
				JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
				if (null != path && null != jaxrsDescribe) {
					classes.add(o);
				}
			}
		}
		return classes;
	}
}
 
Example #6
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 #7
Source File: ApiBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<Class<?>> scanJaxrsClass() throws Exception {
	try (ScanResult scanResult = new ClassGraph().disableJarScanning().enableAnnotationInfo().scan()) {
		SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
		for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
			Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
			for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
					"getClasses")) {
				Path path = o.getAnnotation(Path.class);
				JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
				if (null != path && null != jaxrsDescribe) {
					classes.add(o);
				}
			}
		}
		return classes;
	}
}
 
Example #8
Source File: ClassGraphTest.java    From vertx-vaadin with MIT License 6 votes vote down vote up
@Test
public void testME() {
    Path resourcePath = Paths.get(META_INF_RESOURCES_PATH);
    try (ScanResult scanResult = new ClassGraph()
        .verbose()
        .whitelistPaths(META_INF_RESOURCES_PATH)
        .removeTemporaryFilesAfterScan()
        .scan()) {

        scanResult.getAllResources()
            .nonClassFilesOnly()
            .stream()
            .map(Resource::getPathRelativeToClasspathElement)
            .map(Paths::get)
            .map(resourcePath::relativize)
            .forEach(System.out::println);
    }
    Assert.assertTrue(true);
}
 
Example #9
Source File: ClassGraphUtil.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * Reflection is not thread-safe scanning the jars files in the classpath,
 * must be synchronized otherwise a "java.lang.IllegalStateException: zip file closed" is thrown.
 */
synchronized public static <T> Set<ClassInfo> getNonAbstractSubClassInfoSet(Class<T> parentClass, String... packageNames) {
    if (packageNames == null || packageNames.length == 0) {
        packageNames = defaultPackages();
    }
    try (ScanResult scanResult =
                 new ClassGraph()
                         .enableAllInfo()
                         .whitelistPackages(packageNames)
                         .scan()) {
        ClassInfoList classInfos = parentClass.isInterface() ?
                scanResult.getClassesImplementing(parentClass.getName()) :
                scanResult.getSubclasses(parentClass.getName());
        return classInfos
                .stream()
                .filter(classInfo -> !classInfo.isAbstract())
                .collect(Collectors.toSet());
    }
}
 
Example #10
Source File: CheckCore.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void main(String... args) throws Exception {
	try (ScanResult sr = new ClassGraph().disableJarScanning().enableAnnotationInfo().scan()) {
		List<ClassInfo> classInfos = sr.getClassesWithAnnotation(ContainerEntity.class.getName());
		List<Class<?>> classes = new ArrayList<>();
		for (ClassInfo info : classInfos) {
			classes.add(Class.forName(info.getName()));
		}
		checkColumnName(classes);
		checkColumnLength(classes);
		checkLobIndex(classes);
		checkListFieldContainerTableName(classes);
		checkFieldDescribeOnStatic(classes);
		checkTableNameUniqueConstraintName(classes);
		checkIdCreateTimeUpdateTimeSequenceIndex(classes);
		checkEnum(classes);
	}
}
 
Example #11
Source File: PersistenceXmlWriter.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private static List<Class<?>> scanContainerEntity(String project) throws Exception {
	List<Class<?>> list = new ArrayList<>();
	try (ScanResult scanResult = new ClassGraph().enableAnnotationInfo().scan()) {
		List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Module.class.getName());
		for (ClassInfo info : classInfos) {
			if (StringUtils.equals(info.getSimpleName(), project)) {
				Class<?> cls = Class.forName(info.getName());
				Module moudle = cls.getAnnotation(Module.class);
				for (String str : moudle.containerEntities()) {
					if (StringUtils.isNotEmpty(str)) {
						list.add(Class.forName(str));
					}
				}
			}
		}
		return list;
	}
}
 
Example #12
Source File: BaseAction.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private List<Class<?>> listAssemble() throws Exception {
	if (null == assembles) {
		synchronized (BaseAction.class) {
			if (null == assembles) {
				try (ScanResult scanResult = new ClassGraph().enableAnnotationInfo().scan()) {
					assembles = new CopyOnWriteArrayList<Class<?>>();
					List<ClassInfo> list = new ArrayList<>();
					list.addAll(scanResult.getClassesWithAnnotation(Module.class.getName()));
					list = list.stream().sorted(Comparator.comparing(ClassInfo::getName))
							.collect(Collectors.toList());
					for (ClassInfo info : list) {
						Class<?> cls = Class.forName(info.getName());
						Module module = cls.getAnnotation(Module.class);
						if (Objects.equal(module.type(), ModuleType.ASSEMBLE)) {
							assembles.add(cls);
						}
					}
				}
			}
		}
	}
	return assembles;
}
 
Example #13
Source File: ResourceFactory.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void bind() throws Exception {
	try (ScanResult sr = new ClassGraph().enableAnnotationInfo().scan()) {
		node(sr);
		containerEntities(sr);
		containerEntityNames(sr);
		stroageContainerEntityNames(sr);
	}
	if (Config.logLevel().audit().enable()) {
		auditLog();
	}
	if (Config.externalDataSources().enable()) {
		external();
	} else {
		internal();
	}
	processPlatformExecutors();
}
 
Example #14
Source File: NodeAgent.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<ClassInfo> listModuleDependencyWith(String name) throws Exception {
	List<ClassInfo> list = new ArrayList<>();
	try (ScanResult scanResult = new ClassGraph().enableAnnotationInfo().scan()) {
		List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Module.class.getName());
		for (ClassInfo info : classInfos) {
			Class<?> cls = Class.forName(info.getName());
			Module module = cls.getAnnotation(Module.class);
			if (Objects.equals(module.type(), ModuleType.ASSEMBLE)
					|| Objects.equals(module.type(), ModuleType.SERVICE)
					|| Objects.equals(module.type(), ModuleType.CENTER)) {
				if (ArrayUtils.contains(module.storeJars(), name) || ArrayUtils.contains(module.customJars(), name)
						|| ArrayUtils.contains(module.dynamicJars(), name)) {
					list.add(info);
				}
			}
		}
	}
	return list;
}
 
Example #15
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 #16
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 #17
Source File: ScribeMojo.java    From Chimera with MIT License 6 votes vote down vote up
@Override
public void execute() throws MojoFailureException {
    var graph = new ClassGraph().enableClassInfo().enableAnnotationInfo().addClassLoader(Processor.loader(classpaths));
    var environment = new MavenEnvironment(project());
    
    try (var processor = new MavenProcessor(environment, graph)) {   
        processor.run();
        
        if (valid(environment)) {
            var yaml = YAML.fromFile("Scribe Maven Plugin", new File(folder, "plugin.yml"));
            yaml.write(environment.mappings);

        } else {
            throw new MojoFailureException("Could not resolve annotations");
        }
    }
}
 
Example #18
Source File: ClassFinder.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
/**
 * Searches for the implementations/subtypes of the given class. Only the matching classes are loaded.
 *
 * @param superType The type the implementations/subtypes of which are to be searched for
 * @param packages The packages to limit the search to
 *
 * @return A collection of classes discovered that implementation/extend {@code superType}
 */
public List<Class<?>> findImplementations(Class superType, Predicate<ClassInfo> filter, String... packages) {
    String[] scanPackages = Utils.emptyIfNull(packages);
    String cacheKey = Arrays.stream(scanPackages).sorted().collect(Collectors.joining());
    ScanResult scanResults = cache.computeIfAbsent(cacheKey, k -> new ClassGraph()
            .whitelistPackages(packages)
            .enableAllInfo()
            .initializeLoadedClasses()
            .scan());
    try {
        return scanResults.getAllClasses().stream()
                .filter(impl -> superType.isInterface() ? impl.implementsInterface(superType.getName()) : impl.extendsSuperclass(superType.getName()))
                .filter(filter == null ? info -> true : filter)
                .flatMap(info -> loadClass(info, superType))
                .collect(Collectors.toList());
    } catch (Exception e) {
        log.error("Failed to auto discover the subtypes of " + superType.getName()
                + ". Error encountered while scanning the classpath/modulepath.", e);
        return Collections.emptyList();
    }
}
 
Example #19
Source File: APIParser.java    From swagger with Apache License 2.0 6 votes vote down vote up
private List<Class<?>> scanClass() throws ClassNotFoundException {
    List<Class<?>> classes = new ArrayList<>();
    for (String pkg : packageToScan) {
        try (ScanResult scanResult =
                     new ClassGraph()
                             .enableClassInfo()
                             .enableAnnotationInfo()
                             .whitelistPackages(pkg)
                             .scan()) {
            for (ClassInfo classInfo : scanResult.getClassesWithAnnotation(APIs.class.getName())) {
                classes.add(Class.forName(classInfo.getName()));
            }
        }
    }
    return classes;
}
 
Example #20
Source File: ClasspathScanningResourcesDetectorTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDetectResourcesInOrderTheyAppearInURLClassLoader() throws Exception {
  File file1 = createTestTmpJarFile("test1");
  File file2 = createTestTmpJarFile("test2");
  ClassLoader classLoader =
      new URLClassLoader(new URL[] {file1.toURI().toURL(), file2.toURI().toURL()});

  ClasspathScanningResourcesDetector detector =
      new ClasspathScanningResourcesDetector(new ClassGraph());

  List<String> result = detector.detect(classLoader);

  assertThat(
      result,
      containsInRelativeOrder(
          containsString(file1.getAbsolutePath()), containsString(file2.getAbsolutePath())));
}
 
Example #21
Source File: ActionMembershipTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllActionsEitherHtmlOrJson() {
  // All UI actions should serve valid HTML or JSON. There are three valid options:
  // 1. Extending HtmlAction to signal that we are serving an HTML page
  // 2. Extending JsonAction to show that we are serving JSON POST requests
  // 3. Extending JsonGetAction to serve JSON GET requests
  ImmutableSet.Builder<String> failingClasses = new ImmutableSet.Builder<>();
  try (ScanResult scanResult =
      new ClassGraph().enableAnnotationInfo().whitelistPackages("google.registry.ui").scan()) {
    scanResult
        .getClassesWithAnnotation(Action.class.getName())
        .forEach(
            classInfo -> {
              if (!classInfo.extendsSuperclass(HtmlAction.class.getName())
                  && !classInfo.implementsInterface(JsonActionRunner.JsonAction.class.getName())
                  && !classInfo.implementsInterface(JsonGetAction.class.getName())) {
                failingClasses.add(classInfo.getName());
              }
            });
  }
  assertWithMessage(
          "All UI actions must implement / extend HtmlAction, JsonGetAction, "
              + "or JsonActionRunner.JsonAction. Failing classes:")
      .that(failingClasses.build())
      .isEmpty();
}
 
Example #22
Source File: EntityTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("This won't be done until b/152410794 is done, since it requires many entity changes")
public void testSqlEntityPersistence() {
  try (ScanResult scanResult =
      new ClassGraph().enableAnnotationInfo().whitelistPackages("google.registry").scan()) {
    // All javax.persistence entities must implement SqlEntity and vice versa
    ImmutableSet<String> javaxPersistenceClasses =
        getClassNames(
            scanResult.getClassesWithAnnotation(javax.persistence.Entity.class.getName()));
    ImmutableSet<String> sqlEntityClasses =
        getClassNames(scanResult.getClassesImplementing(SqlEntity.class.getName()));
    assertThat(javaxPersistenceClasses).isEqualTo(sqlEntityClasses);

    // All com.googlecode.objectify.annotation.Entity classes must implement DatastoreEntity and
    // vice versa
    ImmutableSet<String> objectifyClasses =
        getClassNames(
            scanResult.getClassesWithAnnotation(
                com.googlecode.objectify.annotation.Entity.class.getName()));
    ImmutableSet<String> datastoreEntityClasses =
        getClassNames(scanResult.getClassesImplementing(DatastoreEntity.class.getName()));
    assertThat(objectifyClasses).isEqualTo(datastoreEntityClasses);
  }
}
 
Example #23
Source File: ClasspathScanningPrimitiveTypeRegistry.java    From atomix with Apache License 2.0 6 votes vote down vote up
public ClasspathScanningPrimitiveTypeRegistry(ClassLoader classLoader) {
  Map<String, PrimitiveType> types = CACHE.computeIfAbsent(classLoader, cl -> {
    final Map<String, PrimitiveType> result = new ConcurrentHashMap<>();
    final String[] whitelistPackages = StringUtils.split(System.getProperty("io.atomix.whitelistPackages"), ",");
    final ClassGraph classGraph = whitelistPackages != null
        ? new ClassGraph().enableClassInfo().whitelistPackages(whitelistPackages).addClassLoader(classLoader)
        : new ClassGraph().enableClassInfo().addClassLoader(classLoader);
    try (final ScanResult scanResult = classGraph.scan()) {
      scanResult.getClassesImplementing(PrimitiveType.class.getName()).forEach(classInfo -> {
        if (classInfo.isInterface() || classInfo.isAbstract() || Modifier.isPrivate(classInfo.getModifiers())) {
          return;
        }
        final PrimitiveType primitiveType = newInstance(classInfo.loadClass());
        final PrimitiveType oldPrimitiveType = result.put(primitiveType.name(), primitiveType);
        if (oldPrimitiveType != null) {
          LOGGER.warn("Found multiple primitives types name={}, classes=[{}, {}]", primitiveType.name(),
                  oldPrimitiveType.getClass().getName(), primitiveType.getClass().getName());
        }
      });
    }
    return Collections.unmodifiableMap(result);
  });
  primitiveTypes.putAll(types);
}
 
Example #24
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 #25
Source File: Configuration.java    From javalite with Apache License 2.0 6 votes vote down vote up
/**
 * A sub-package is what you find between "app.controller" and a controller simple class name.
 * <p>
 * For instance, if the name of the controller class is <code>app.controllers.pack1.pack2.HomeController</code>,
 * then <code>pack1.pack2</code> will be returned.
 *
 * @return a list of  of sub-package names
 * @throws IOException
 */
static List<String> locateControllerSubPackages() {

    List<String> subpackages = new ArrayList<>();
    String controllerRootPackage = Configuration.getRootPackage() + ".controllers";
    try (ScanResult scanResult = new ClassGraph().whitelistPackages(controllerRootPackage).scan()) {
        for (ClassInfo classInfo : scanResult.getSubclasses(AppController.class.getName())) {
            if(!classInfo.isAbstract()){
                String className = classInfo.getName();
                if (className.chars().filter(ch -> ch == '.').count() > 2) {
                    subpackages.add(className.substring(className.indexOf("controllers." ) + 12, className.lastIndexOf('.')));
                }
            }
        }
    }
    return subpackages;
}
 
Example #26
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 #27
Source File: CompletionProvider.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
private ScanResult scanClasses() {
	try {
		return new ClassGraph().overrideClassLoaders(classLoader).enableClassInfo().enableSystemJarsAndModules()
				.scan();
	} catch (ClassGraphException e) {
	}
	return null;
}
 
Example #28
Source File: CheckCore.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String packageName(String name) throws Exception {
	try (ScanResult scanResult = new ClassGraph().enableAnnotationInfo().scan()) {
		List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Module.class.getName());
		for (ClassInfo info : classInfos) {
			if (StringUtils.equals(info.getSimpleName(), name)) {
				Class<?> cls = Class.forName(info.getName());
				Module module = cls.getAnnotation(Module.class);
				return module.packageName();
			}
		}
	}
	return null;
}
 
Example #29
Source File: SqlIntegrationMembershipTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void sqlIntegrationMembershipComplete() {
  ImmutableSet<String> sqlDependentTests;
  try (ScanResult scanResult =
      new ClassGraph().enableAnnotationInfo().whitelistPackages("google.registry").scan()) {
    sqlDependentTests =
        scanResult.getClassesWithAnnotation(RunWith.class.getName()).stream()
            .filter(clazz -> clazz.getSimpleName().endsWith("Test"))
            .map(clazz -> clazz.loadClass())
            .filter(SqlIntegrationMembershipTest::isSqlDependent)
            .map(Class::getName)
            .collect(ImmutableSet.toImmutableSet());
  }
  ImmutableSet<String> declaredTests =
      Stream.of(SqlIntegrationTestSuite.class.getAnnotation(SuiteClasses.class).value())
          .map(Class::getName)
          .collect(ImmutableSet.toImmutableSet());
  SetView<String> undeclaredTests = Sets.difference(sqlDependentTests, declaredTests);
  expect
      .withMessage(
          "Undeclared sql-dependent tests found. "
              + "Please add them to SqlIntegrationTestSuite.java.")
      .that(undeclaredTests)
      .isEmpty();
  SetView<String> unnecessaryDeclarations = Sets.difference(declaredTests, sqlDependentTests);
  expect
      .withMessage("Found tests that should not be included in SqlIntegrationTestSuite.java.")
      .that(unnecessaryDeclarations)
      .isEmpty();
}
 
Example #30
Source File: GenerateCodeTask.java    From gradle-plugins with MIT License 5 votes vote down vote up
@TaskAction
public void generate() {

    ScanResult scan = new ClassGraph()
            .overrideClasspath(codeGeneratorClasspath)
            .enableClassInfo()
            .enableAnnotationInfo()
            .scan();
    ClassInfoList classesWithAnnotation = scan.getClassesWithAnnotation(CodeGenerator.class.getCanonicalName());
    ClassInfoList classesImplementing = scan.getClassesImplementing(Generator.class.getCanonicalName());

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Found {} with code generator annotation ({}): ", classesWithAnnotation.size(), CodeGenerator.class.getCanonicalName());
        getLogger().debug(classesWithAnnotation.stream().map(ClassInfo::getName).collect(Collectors.joining(",")));
        getLogger().debug("Found {} implementing {}: ", classesImplementing.size(), Generator.class.getCanonicalName());
        getLogger().debug(classesImplementing.stream().map(ClassInfo::getName).collect(Collectors.joining(",")));
    }

    ProjectContext context = new ProjectContext(getProject().getProjectDir(), inputDir.getAsFile().getOrElse(this.getTemporaryDir()), outputDir.getAsFile().get(), configurationValues.getOrElse(Collections.emptyMap()), sourceSet.getOrElse("none"));

    WorkQueue workQueue = workerExecutor.classLoaderIsolation(spec -> spec.getClasspath().from(codeGeneratorClasspath));

    for (ClassInfo classInfo : classesWithAnnotation) {
        workQueue.submit(UnitOfWork.class, parameters -> {
            parameters.getClassName().set(classInfo.getName());
            parameters.getProjectContext().set(context);
        });
    }
}