扫描包

@param basePackage 基础包
@param recursive   是否递归搜索子包
@return Set
962446
public Set<Class<?>> getPackageAllClasses(String basePackage,
                                              boolean recursive) {
        Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
        String packageName = basePackage;
        if (packageName.endsWith(".")) {
            packageName = packageName
                    .substring(0, packageName.lastIndexOf('.'));
        }
        String package2Path = packageName.replace('.', '/');

        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(
                    package2Path);
            while (dirs.hasMoreElements()) {
                URL url = dirs.nextElement();
                String protocol = url.getProtocol();
                if ("file".equals(protocol)) {
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    doScanPackageClassesByFile(classes, packageName, filePath, recursive);
                } else if ("jar".equals(protocol)) {
                    doScanPackageClassesByJar(packageName, url, recursive, classes);
                }
            }
        } catch (IOException e) {
            throw new LtsRuntimeException(e);
        }
        return classes;
    }
315257
public static boolean contains(Package pack, Package wantedPackage) {
    return new PackageTreeTraverser()
        .postOrderTraversal(pack)
        .anyMatch(childPackage -> Objects.equals(childPackage, wantedPackage));
  }
899614
public ImmutableSet<ClassInfo> getTopLevelClassesRecursive(String packageName) {
    checkNotNull(packageName);
    String packagePrefix = packageName + '.';
    ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
    ImmutableSet<ClassInfo> topLevelClasses = getTopLevelClasses();
    List<String> debugData = Lists.newLinkedList();
    for (ClassInfo classInfo : topLevelClasses) {
      if (classInfo.getName().startsWith(packagePrefix)) {
        builder.add(classInfo);
        debugData.add(classInfo.getResourceName() + "\n");
      }
    }
    return builder.build();
  }
774100
public static Set<Class<?>> scanPackage(ClassLoader classLoader, String pkg) throws IOException {
        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .addUrls(ClasspathHelper.forPackage(pkg, classLoader))
                .addClassLoader(classLoader)
                .setScanners(new SubTypesScanner(false)));
        Set<Class<?>> classes = new HashSet<Class<?>>();
        for (String typeNames : reflections.getStore().get(SubTypesScanner.class.getSimpleName()).values()) {
            Class<?> clazz = safeClassForName(classLoader, typeNames);
            if (clazz != null) {
                classes.add(clazz);
            }
        }
        return classes;
    }
1354269
private Collection<? extends String> recursiveCollect(String refId,
      Map<String, SortedSet<String>> relationKeyMap, int maxRecursion) {
    Set<String> list = new HashSet<>();
    if (maxRecursion > 0 && relationKeyMap.containsKey(refId)) {
      SortedSet<String> subList = relationKeyMap.get(refId);
      for (String subRefId : subList) {
        list.add(subRefId);
        list.addAll(
            recursiveCollect(subRefId, relationKeyMap, maxRecursion - 1));
      }
    }
    return list;
  }
1109520
private static Set<Type> getChildTypes(final Type _type)
        throws CacheReloadException
    {
        final Set<Type> ret = new HashSet<Type>();
        ret.add(_type);
        for (final Type child : _type.getChildTypes()) {
            ret.addAll(getChildTypes(child));
        }
        return ret;
    }
1008954
public static List<File> getResourcesInnPackage(String root) {
		try {
			logger.debug("getResourcesInnPackage for package: " + root);
			ClassLoader loader = Thread.currentThread().getContextClassLoader();
			URL url = loader.getResource(root);
			if (url != null) {
				logger.debug(" URL  :" + url.toURI());
				InputStream in = loader.getResourceAsStream(root);
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				String resource;
				List<File> fileNames = new ArrayList<>();
				while ((resource = br.readLine()) != null) {
					if (!root.endsWith("/")) {
						root += "/";
					}
					String resourcePath = root + resource;
					logger.debug("Processing resource path:" + resourcePath);
					File file = new File(loader.getResource(resourcePath).toURI());
					if (file.isDirectory()) {
						fileNames.addAll(getResourcesInnPackage(resourcePath + "/"));
					} else {
						logger.debug("Adding file :" + file.getName());
						fileNames.add(file);
					}
				}
				return fileNames;
			} else {
				logger.debug("Package not found, return empty list");
				return Collections.emptyList();
			}
		} catch (Exception e) {
			JK.throww(e);
			return null;
		}
	}
911734
public static Predicate<RequestHandler> basePackage(final String basePackage) {
    return input -> declaringClass(input).map(handlerPackage(basePackage)).orElse(true);
  }
121639
function getPackagesTasks(baseTask) {
	var packages = getPackages();
	var tasks = [];

	for (index = 0; index < packages.length; ++index) {
	    tasks.push(baseTask + '.' + packages[index]);
	}

	return tasks;
}
870278
@Override
    public Stream<FedoraResource> getChildren(final Boolean recursive) {
        try {
            if (recursive) {
                return nodeToGoodChildren(node).flatMap(FedoraResourceImpl::getAllChildren);
            }
            return nodeToGoodChildren(node);
        } catch (final RepositoryException e) {
            throw new RepositoryRuntimeException(e);
        }
    }
1016997
@NonNull
    public static Set<String> keySet(@Nullable Bundle bundle) {
        if (bundle == null) {
            return Collections.emptySet();
        }
        return bundle.keySet();
    }
693519
public List<Class<?>> getClasses(final String pkg, boolean recursive)
	{
		return getClasses(pkg, recursive, null);
	}
1337348
public static <K,V extends Item> Map<K,V> loadChildren(ItemGroup parent, File modulesDir, Function1<? extends K,? super V> key) {
        modulesDir.mkdirs(); // make sure it exists

        File[] subdirs = modulesDir.listFiles(new FileFilter() {
            public boolean accept(File child) {
                return child.isDirectory();
            }
        });
        CopyOnWriteMap.Tree<K,V> configurations = new CopyOnWriteMap.Tree<>();
        for (File subdir : subdirs) {
            try {
                // Try to retain the identity of an existing child object if we can.
                V item = (V) parent.getItem(subdir.getName());
                if (item == null) {
                    XmlFile xmlFile = Items.getConfigFile(subdir);
                    if (xmlFile.exists()) {
                        item = (V) Items.load(parent, subdir);
                    } else {
                        Logger.getLogger(ItemGroupMixIn.class.getName()).log(Level.WARNING, "could not find file " + xmlFile.getFile());
                        continue;
                    }
                } else {
                    item.onLoad(parent, subdir.getName());
                }
                configurations.put(key.call(item), item);
            } catch (Exception e) {
                Logger.getLogger(ItemGroupMixIn.class.getName()).log(Level.WARNING, "could not load " + subdir, e);
            }
        }

        return configurations;
    }
808826
public function collectPatches(RootPackageInterface $rootPackage, array $subPackages)
    {
        $collectedPatches = $this->collectPatchesFromPackage($rootPackage);
        $extra = $rootPackage->getExtra();
        if (isset($extra['allow-subpatches'])) {
            $allowedSubpatches = $extra['allow-subpatches'];
            if (!is_bool($allowedSubpatches) && !is_array($allowedSubpatches)) {
                $this->handleException(new Exception\InvalidPackageConfigurationValue($rootPackage, 'extra.allow-subpatches', $allowedSubpatches, 'The extra.allow-subpatches must be a boolean or an array of strings.'));
            }
            $collectedPatches->merge($this->collectSubpackagePatches($subPackages, $allowedSubpatches));
        }

        return $collectedPatches;
    }
1177968
@Override
    public void addPackages( Collection<? extends KiePackage> newPkgs ) {
        final List<InternalKnowledgePackage> clonedPkgs = new ArrayList<>();
        for (KiePackage newPkg : newPkgs) {
            clonedPkgs.add(((InternalKnowledgePackage)newPkg).deepCloneIfAlreadyInUse(rootClassLoader));
        }

        clonedPkgs.sort(Comparator.comparing( (InternalKnowledgePackage p) -> p.getRules().size() ).reversed().thenComparing( InternalKnowledgePackage::getName ));
        enqueueModification( () -> internalAddPackages( clonedPkgs ) );
    }
605863
private void scanClasses0(String basePackage)
            throws IOException, ClassNotFoundException, FileNotFoundException {
        File packageDirectory = null;
        ClassLoader cld = getLoader();
        String basePackagePath = basePackage.replace('.', '/');
        Enumeration<URL> basePackageUrls = cld.getResources(basePackagePath);
        if (basePackageUrls == null || !basePackageUrls.hasMoreElements()) {
            throw new ClassNotFoundException("Base package path not found: [" + basePackagePath
                    + "]");
        }
        while (basePackageUrls.hasMoreElements()) {
            String packagePath = basePackageUrls.nextElement().getFile();
            if (packagePath.contains(JAR_FILE_PATTERN)) {
                scanJarFile(basePackagePath, packagePath);
            } else {
                packageDirectory = new File(packagePath);
                scanDirectory(basePackage, packageDirectory);
            }
        }
    }
373178
@SuppressWarnings("all")
    synchronized public static <T> Set<Class<? extends T>> getNonAbstractSubClasses(Class<T> parentClass, String... packageNames) {
        return getNonAbstractSubClassInfoSet(parentClass, packageNames).stream().map(classInfo -> {
            try {
                //Here we must use parentClass's classloader to make sure we are always using the same classloader.
                return (Class<? extends T>) parentClass.getClassLoader().loadClass(classInfo.getName());
            } catch (ClassNotFoundException e) {
                SystemOutLogger.SINGLETON.error("Failed to load class " + classInfo.getName(), e, "");
                System.exit(Constant.SYSTEM_EXIT_CODE_FOR_SYS_INIT_ERROR);
                //dead code
                return null;
            }
        }).collect(Collectors.toSet());
    }