io.github.classgraph.ClassInfo Java Examples

The following examples show how to use io.github.classgraph.ClassInfo. 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: 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 #3
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 #4
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 #5
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 #6
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 #7
Source File: DefaultImplementationDiscoveryStrategy.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
public List<AnnotatedType> findImplementations(AnnotatedType type, boolean autoDiscover, String[] scanPackages, BuildContext buildContext) {
    if (Utils.isArrayEmpty(scanPackages) && Utils.isArrayNotEmpty(buildContext.basePackages)) {
        scanPackages = buildContext.basePackages;
    }
    Predicate<ClassInfo> filter = NON_IGNORED.and(filters.stream().reduce(Predicate::and).orElse(ALL));

    List<AnnotatedType> additionalImpls = additionalImplementationsOf(type);
    if (!autoDiscover) {
        return additionalImpls;
    }
    List<AnnotatedType> discoveredImpls = buildContext.classFinder.findImplementations(type, filter, false, scanPackages);
    Set<Class<?>> seen = new HashSet<>(discoveredImpls.size() + additionalImpls.size());
    return Stream.concat(additionalImpls.stream(), discoveredImpls.stream())
            .filter(impl -> seen.add(GenericTypeReflector.erase(impl.getType())))
            .collect(Collectors.toList());
}
 
Example #8
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 #9
Source File: ServletContainerInitializerHandler.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
/**
 * Resolves the {@link Class}[] of the {@code HandlesTypes}-annotations present on the given
 * {@code ServletContainerInitializer} implementation.
 *
 * @param servletContainerInitializerClassInfo The {@link ClassInfo} object representing the {@code ServletContainerInitializer} implementation
 * @return The classes listed in the {@code HandlesTypes} annotation of the given class.
 */
private List<ClassInfo> resolveHandledTypes(ClassInfo servletContainerInitializerClassInfo) {
	AnnotationInfo handlesTypes = servletContainerInitializerClassInfo.getAnnotationInfo(HANDLES_TYPES);

	Object[] value = (Object[]) handlesTypes.getParameterValues().get("value").getValue();

	return Arrays.stream(value)
			.map(AnnotationClassRef.class::cast)
			.map(annotationClassRef -> {
				ClassInfo classInfo = annotationClassRef.getClassInfo();
				if (classInfo == null) {
					log.warn("{} not found in the scan result, but declared in the @HandlesTypes annotation of {}", annotationClassRef.getName(), servletContainerInitializerClassInfo.getName());
				}
				return classInfo;
			})
			.filter(Objects::nonNull)
			.collect(Collectors.toList());
}
 
Example #10
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 #11
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 #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: 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 #14
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 #15
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 #16
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 #17
Source File: CompletionProvider.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
private CompletionItemKind classInfoToCompletionItemKind(ClassInfo classInfo) {
	if (classInfo.isInterface()) {
		return CompletionItemKind.Interface;
	}
	if (classInfo.isEnum()) {
		return CompletionItemKind.Enum;
	}
	return CompletionItemKind.Class;
}
 
Example #18
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 #19
Source File: ResponseTest.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Scan all the classes in package {@link com.linkedin.kafka.cruisecontrol} for classes which could be used
 * to build JSON response, which are annotated with {@link JsonResponseClass}.
 *
 * @throws ClassNotFoundException If the definition of the class is not found.
 */
@Before
public void scanForResponseClass() throws ClassNotFoundException {
  _schemaToClass = new HashMap<>();
  ScanResult scanResult = new ClassGraph().ignoreClassVisibility()
                                          .enableAnnotationInfo()
                                          .whitelistPackages(CRUISE_CONTROL_PACKAGE)
                                          .scan();
  for (ClassInfo classInfo : scanResult.getClassesWithAnnotation(JsonResponseClass.class.getName())) {
    String className = classInfo.getName();
    _schemaToClass.put(extractSimpleClassName(className), Class.forName(className));
  }
}
 
Example #20
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);
        });
    }
}
 
Example #21
Source File: EntityTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private ImmutableSet<String> getClassNames(ClassInfoList classInfoList) {
  return classInfoList.stream()
      .filter(ClassInfo::isStandardClass)
      .map(ClassInfo::loadClass)
      .filter(clazz -> !clazz.isAnnotationPresent(EntityForTesting.class))
      .map(Class::getName)
      .collect(toImmutableSet());
}
 
Example #22
Source File: MantaroCore.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
private Set<Class<?>> lookForAnnotatedOn(String packageName, Class<? extends Annotation> annotation) {
    return new ClassGraph()
            .whitelistPackages(packageName)
            .enableAnnotationInfo()
            .scan(2)
            .getAllClasses().stream().filter(classInfo -> classInfo.hasAnnotation(annotation.getName())).map(ClassInfo::loadClass)
            .collect(Collectors.toSet());
}
 
Example #23
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 #24
Source File: AutoScanAbstractInputHandler.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public List<Class<?>> findConcreteSubTypes(Class<?> abstractType, BuildContext buildContext) {
    if (!scanCondition.test(abstractType)) {
        return Collections.emptyList();
    }
    Predicate<ClassInfo> filter = CONCRETE.and(NON_IGNORED).and(candidateFilters.stream().reduce(Predicate::and).orElse(ALL));
    List<Class<?>> subTypes = buildContext.classFinder.findImplementations(abstractType, filter, buildContext.basePackages);
    if (subTypes.isEmpty()) {
        log.warn("No concrete subtypes of " + abstractType.getName() + " found");
    }
    return subTypes;
}
 
Example #25
Source File: ServletContainerInitializerHandler.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(ScanResult scanResult, File classpathRoot) throws IOException {
	ClassInfoList scis = scanResult.getClassesImplementing(SERVLET_CONTAINER_INITIALIZER)
			.filter(classInfo -> classInfo.hasAnnotation(HANDLES_TYPES));

	for (ClassInfo sciClassInfo : scis) {
		List<ClassInfo> handledTypes = resolveHandledTypes(sciClassInfo);

		SortedSet<String> classes = findHandledClasses(scanResult, handledTypes);

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

		writeClassList(resultFile, classes);
	}
}
 
Example #26
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);
        });
    }
}
 
Example #27
Source File: ApplicationServerTools.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void cleanWorkDirectory(List<ClassInfo> officialClassInfos, List<String> customNames)
		throws Exception {
	List<String> names = new ArrayList<>();
	for (ClassInfo o : officialClassInfos) {
		names.add(o.getSimpleName());
	}
	names.addAll(customNames);
	for (String str : Config.dir_servers_applicationServer_work(true).list()) {
		if (!names.contains(str)) {
			FileUtils.forceDelete(new File(Config.dir_servers_applicationServer_work(), str));
		}
	}
}
 
Example #28
Source File: NodeAgent.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private ClassInfo scanModuleClassInfo(String name) throws Exception {
	try (ScanResult scanResult = new ClassGraph().enableAnnotationInfo().scan()) {
		List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Module.class.getName());
		for (ClassInfo info : classInfos) {
			Class<?> clz = Class.forName(info.getName());
			if (StringUtils.equals(clz.getSimpleName(), name)) {
				return info;
			}
		}
		return null;
	}
}
 
Example #29
Source File: CreateWebXml.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String moduleClassName(ScanResult scanResult, String project) throws Exception {
	List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Module.class.getName());
	for (ClassInfo info : classInfos) {
		if (StringUtils.equals(info.getSimpleName(), project)) {
			return info.getName();
		}
	}
	return null;
}
 
Example #30
Source File: ResourceFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void containerEntities(ScanResult sr) throws Exception {
	Map<String, List<String>> map = new TreeMap<>();
	for (ClassInfo info : sr.getClassesWithAnnotation(Module.class.getName())) {
		Class<?> cls = Class.forName(info.getName());
		List<String> os = ListTools.toList(cls.getAnnotation(Module.class).containerEntities());
		map.put(info.getName(), ListUtils.unmodifiableList(os));
	}
	new Resource(Config.RESOURCE_CONTAINERENTITIES, MapUtils.unmodifiableMap(map));
}