io.github.classgraph.ScanResult Java Examples

The following examples show how to use io.github.classgraph.ScanResult. 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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: VaadinVerticle.java    From vertx-vaadin with MIT License 6 votes vote down vote up
private void registerHandledTypes(ScanResult scanResult, Class<?> initializerClass, Map<Class<?>, Set<Class<?>>> map) {

        HandlesTypes handledTypes = initializerClass.getAnnotation(HandlesTypes.class);
        if (handledTypes != null) {
            Function<Class<?>, ClassInfoList> classFinder = type -> {
                if (type.isAnnotation()) {
                    return scanResult.getClassesWithAnnotation(type.getCanonicalName());
                } else if (type.isInterface()) {
                    return scanResult.getClassesImplementing(type.getCanonicalName());
                } else {
                    return scanResult.getSubclasses(type.getCanonicalName());
                }
            };

            Set<Class<?>> classes = Stream.of(handledTypes.value())
                .map(classFinder)
                .flatMap(c -> c.loadClasses().stream())
                .collect(Collectors.toSet());

            if (!classes.isEmpty()) {
                map.put(initializerClass, classes);
            }
        }
    }
 
Example #11
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 #12
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 #13
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 #14
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 #15
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 #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: MyFacesInitializerRegistrationBean.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleScanResult(ScanResult scanResult) {
	super.handleScanResult(scanResult);

	Map<Class<? extends Annotation>, Set<Class<?>>> annotatedClasses = new HashMap<>();

	Arrays.asList(
			ManagedBean.class,
			FacesComponent.class,
			FacesBehavior.class,
			FacesConverter.class,
			NamedEvent.class,
			FacesRenderer.class,
			FacesBehaviorRenderer.class,
			FacesValidator.class
	).forEach(annotationClass -> {
		List<Class<?>> classes = scanResult.getClassesWithAnnotation(annotationClass.getName()).loadClasses();
		annotatedClasses.put(annotationClass, new HashSet<>(classes));
	});

	JoinFacesAnnotationProvider.setAnnotatedClasses(annotatedClasses);
}
 
Example #18
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 #19
Source File: ServletContainerInitializerHandler.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
/**
 * Find the classes which match the given {@code HandlesTypes} spec.
 *
 * @param scanResult   The {@link ScanResult} in which the classes are searched.
 * @param handledTypes The filter spec as found in the {@code HandlesTypes} annotation.
 * @return The {@link SortedSet set} of classes which implement, extend or are annotated with the given classes.
 */
private SortedSet<String> findHandledClasses(ScanResult scanResult, List<ClassInfo> handledTypes) {

	SortedSet<String> classes = new TreeSet<>(String::compareTo);

	handledTypes.forEach(handledType -> {
		String name = handledType.getName();

		if (handledType.isAnnotation()) {
			classes.addAll(scanResult.getClassesWithAnnotation(name).getNames());
			classes.addAll(scanResult.getClassesWithMethodAnnotation(name).getNames());
			classes.addAll(scanResult.getClassesWithFieldAnnotation(name).getNames());
		}
		else if (handledType.isInterface()) {
			classes.addAll(scanResult.getClassesImplementing(name).getNames());
		}
		else {
			classes.addAll(scanResult.getSubclasses(name).getNames());
		}

	});

	return classes;
}
 
Example #20
Source File: MyFacesAnnotationProviderHandler.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(ScanResult scanResult, File classpathRoot) throws IOException {
	if (scanResult.getClassInfo(MYFACES_ANNOTATION_PROVIDER) == null) {
		return;
	}

	Map<String, List<String>> result = new LinkedHashMap<>();

	for (String myfacesAnnotation : MYFACES_ANNOTATIONS) {
		result.put(myfacesAnnotation, scanResult.getClassesWithAnnotation(myfacesAnnotation).getNames());
	}

	File resultFile = new File(classpathRoot, "META-INF/joinfaces/" + MYFACES_ANNOTATION_PROVIDER + ".classes");

	writeClassMap(resultFile, result);

}
 
Example #21
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 #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
Source File: ClassGraphUtil.java    From xian with Apache License 2.0 5 votes vote down vote up
public synchronized static ClassInfoList getWithAnnotatedClassInfoList(Class<? extends Annotation> annotationClass, String... packageNames) {
    if (packageNames == null || packageNames.length == 0) {
        packageNames = defaultPackages();
    }
    try (ScanResult scanResult =
                 new ClassGraph()
                         .enableAllInfo()
                         .whitelistPackages(packageNames)
                         .scan()) {
        return scanResult.getClassesWithAnnotation(annotationClass.getName());
    }
}
 
Example #30
Source File: Table.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
private static void autoRegisterReadersAndWriters() {
  try (ScanResult scanResult =
      new ClassGraph().enableAllInfo().whitelistPackages("tech.tablesaw.io").scan()) {
    List<String> classes = new ArrayList<>();
    classes.addAll(scanResult.getClassesImplementing(DataWriter.class.getName()).getNames());
    classes.addAll(scanResult.getClassesImplementing(DataReader.class.getName()).getNames());
    for (String clazz : classes) {
      try {
        Class.forName(clazz);
      } catch (ClassNotFoundException e) {
        throw new IllegalStateException(e);
      }
    }
  }
}