下面列出了javax.persistence.Embeddable#io.github.classgraph.ClassGraph 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
};
}
@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);
}
/**
* 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());
}
}
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);
}
}
}
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;
}
}
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;
}
}
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;
}
}
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();
}
}
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);
}
}
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;
}
}
@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;
}
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();
}
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;
}
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;
}
}
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;
}
@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());
}
}
}
@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");
}
}
}
/**
* 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();
}
}
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;
}
@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())));
}
@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();
}
@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);
}
}
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);
}
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;
}
/**
* 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;
}
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;
}
private static void configureLog4j2()
{
Predicate<String> log4j2XmlPredicate = Pattern.compile("log4j2.*\\.xml").asMatchPredicate();
try (ScanResult scanResult = new ClassGraph().whitelistPackagesNonRecursive("").scan();
ResourceList log4j2Resources = scanResult.getAllResources()
.filter(resource -> log4j2XmlPredicate.test(resource.getPath())))
{
log4j2Resources.stream()
.map(Resource::getPath)
.collect(Collectors.collectingAndThen(Collectors.joining(","),
cfg -> System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, cfg)));
}
}
private ScanResult scanClasses() {
try {
return new ClassGraph().overrideClassLoaders(classLoader).enableClassInfo().enableSystemJarsAndModules()
.scan();
} catch (ClassGraphException e) {
}
return null;
}
static List<Class<?>> getSubTypesOf(String superclassName) {
try (ScanResult scanResult = new ClassGraph()
.enableClassInfo().enableAnnotationInfo()
.ignoreClassVisibility()
.blacklistModules("*")
.scan()) {
ClassInfoList classInfoList = scanResult.getSubclasses(superclassName);
return classInfoList.loadClasses();
}
}
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());
}
}