public JSONObject createCompositeMapping(String compositeName) throws IOException { ResourcesScanner resourceScanner = new ResourcesScanner(); Reflections reflections = new Reflections(resourceScanner); Set<String> resources = reflections.getResources(Pattern.compile(".*\\.mapping\\.json")); JSONObject properties = new JSONObject(); for(String resource : resources) { InputStream is = getClass().getClassLoader().getResourceAsStream(resource); if(is == null) { throw new RuntimeException("Unable to read resource " + resource); } String json = IOUtils.toString(is, StandardCharsets.UTF_8); JSONObject part = new JSONObject(json); for(String key : part.keySet()) { properties.put(key, part.get(key)); } } return new JSONObject().put("mappings", new JSONObject().put(compositeName, new JSONObject().put("properties", properties))); }
private void doPackage(FilterBuilder fb, List<RuleFactory> resultL) throws Exception { List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(fb)); Set<Class<? extends RuleFactory>> subTypes = reflections.getSubTypesOf(RuleFactory.class); for(Class<? extends RuleFactory> clazz : subTypes) { RuleFactory factory = clazz.newInstance(); resultL.add(factory); } }
@Test public void testReflections() throws Exception { List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); String packageName = "org.dnal.core.world"; Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName)))); Set<String> types = reflections.getAllTypes(); for(String s : types) { System.out.println(s); } Set<Class<? extends RuleFactory>> subTypes = reflections.getSubTypesOf(RuleFactory.class); for(Class<? extends RuleFactory> clazz : subTypes) { System.out.println("sub: " + clazz.getName()); RuleFactory factory = clazz.newInstance(); RuleDeclaration decl = factory.getDeclaration(); System.out.println("d: " + decl.ruleName); } }
private ArrayList<String> getResourceDirectoryContent(String resourcePattern) { ArrayList<String> tempFilesContentList = new ArrayList<>(); Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("io.logz")) .setScanners(new ResourcesScanner()) .filterInputsBy(new FilterBuilder().include(resourcePattern))); Set<String> properties = reflections.getResources(Pattern.compile(".*\\.json")); properties.forEach((resourceName) -> { URL resourceUrl = Resources.getResource(resourceName); try { tempFilesContentList.add(Resources.toString(resourceUrl, Charset.forName("utf-8")).replace("\n", "")); } catch (IOException e) { logger.info("Could not read file {}", resourceUrl.toString()); } }); if (tempFilesContentList.isEmpty()) throw new RuntimeException("Did not find any files under "+ resourcePattern +"!"); return tempFilesContentList; }
/** * Finds all package names starting with prefix * @param prefix The package in which to start searching * @param statik True to statically return components names * @return a set of component name */ public List<String> findAllPackagesStartingWith(final String prefix, final boolean statik) { final List<ClassLoader> classLoadersList = new ArrayList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[classLoadersList.size()]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(prefix)))); Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); final Set<String> packages = new HashSet<>(); for (final Class classInstance : classes) { String packageName = classInstance.getPackage().getName(); packageName = packageName.split("\\.")[packageName.split("\\.").length-1].toLowerCase(); packages.add(packageName); } return new ArrayList<>(packages); }
private static Collection<? extends Class<?>> getPackageTypes(String packageToPase, Collection<URL> urls) { Set<Class<?>> classes = new HashSet<>(); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* exclude Object.class */), new ResourcesScanner(), new TypeElementsScanner()) .setUrls(urls) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageToPase)).exclude("java.*"))); Set<String> types; types = reflections.getStore().get("TypeElementsScanner").keySet(); for (String type: types) { Class<?> aClass = TypesHelper.loadClass(type, CLASS_LOADER); boolean wantedElement = StringUtils.startsWith(type, packageToPase); if (null != aClass && wantedElement) { logger.log(Level.INFO, "looking up for type: " + type); classes.add(aClass); } } return classes; }
public static void scanForCommands() { //Populate all the cmds System.out.println("[EvenWurse] Reloading cmd list..."); ArrayList<ClassLoader> classLoadersList = new ArrayList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections( new ConfigurationBuilder().setScanners(new SubTypesScanner(), new ResourcesScanner()).setUrls( ClasspathHelper .forClassLoader(classLoadersList.toArray(new ClassLoader[classLoadersList.size()])))); Set<Class<? extends Cmd>> classes = reflections.getSubTypesOf(Cmd.class); KNOWN_CMDS = new Class[classes.size()]; for (int i = 0; i < classes.size(); i++) { KNOWN_CMDS[i] = (Class<? extends Cmd>) classes.toArray()[i]; System.out.println("[EvenWurse] Found cmd: " + KNOWN_CMDS[i].getSimpleName() + "!"); } System.out.println("[EvenWurse] Found " + KNOWN_CMDS.length + " cmds!"); }
public static void scanForMods() { //Populate all the mods System.out.println("[EvenWurse] Reloading mod list..."); ArrayList<ClassLoader> classLoadersList = new ArrayList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections( new ConfigurationBuilder().setScanners(new SubTypesScanner(), new ResourcesScanner()).setUrls( ClasspathHelper .forClassLoader(classLoadersList.toArray(new ClassLoader[classLoadersList.size()])))); Set<Class<? extends Mod>> classes = reflections.getSubTypesOf(Mod.class); KNOWN_MODS = new Class[classes.size()]; for (int i = 0; i < classes.size(); i++) { KNOWN_MODS[i] = (Class<? extends Mod>) classes.toArray()[i]; System.out.println("[EvenWurse] Found mod: " + KNOWN_MODS[i].getSimpleName() + "!"); } System.out.println("[EvenWurse] Found " + KNOWN_MODS.length + " mods!"); }
public static Iterable<URL> scan(String pattern) { // lookup from classpath ConfigurationBuilder rcp = new ConfigurationBuilder()// .setUrls(ClasspathHelper.forClassLoader())// .setScanners(new ResourcesScanner()); { String path = pathChar.replaceFrom(pattern, '.'); rcp.setInputsFilter(in -> (false == in.startsWith("java.")) && Wildcard.match(in, path)); } Set<String> scans = new Reflections(rcp).getResources(Predicates.alwaysTrue()); // transforms strings to urls return Iterables.transform(scans, res -> getURL(res)); }
@SuppressWarnings("unchecked") private void registerScriptEngineFactories() { List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner(), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.jsen")))); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(ScriptEngineFactory.class); for (Class<?> clazz : annotated) { if (AbstractScriptEngineFactory.class.isAssignableFrom(clazz)) { registerMimeContentFactory((Class<AbstractScriptEngineFactory>)clazz); } } }
private Map<String, String> getAllDocStrings0(ClassLoader classLoader) { final Configuration configuration = new ConfigurationBuilder() .filterInputsBy(new FilterBuilder().includePackage(path)) .setUrls(ClasspathHelper.forPackage(path)) .addClassLoader(classLoader) .setScanners(new ResourcesScanner()); if (configuration.getUrls() == null || configuration.getUrls().isEmpty()) { return Collections.emptyMap(); } Map<String, byte[]> files = new Reflections(configuration) .getResources(this::acceptFile).stream() .map(f -> { try { URL url = classLoader.getResource(f); if (url == null) { throw new IllegalStateException("not found: " + f); } return new SimpleImmutableEntry<>(f, Resources.toByteArray(url)); } catch (IOException e) { throw new UncheckedIOException(e); } }) .collect(toImmutableMap(Entry::getKey, Entry::getValue)); return getDocStringsFromFiles(files); }
public static List<URL> urls( String atPackage, String ext ) { final ExecutorService executorService = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors(), new ThreadFactoryBuilder().setNameFormat( "reflections-%d" ).build() ); try { final ConfigurationBuilder configuration = new ConfigurationBuilder() .setUrls( ClasspathHelper.forPackage( atPackage ) ) .setScanners( new ResourcesScanner() ) .filterInputsBy( new FilterBuilder().includePackage( atPackage ) ) .setExecutorService( executorService ); final Reflections reflections = new Reflections( configuration ); final Set<String> resources = reflections.getResources( in -> in.endsWith( "." + ext ) ); return new ArrayList<>( Sets.map( resources, r -> Thread.currentThread().getContextClassLoader().getResource( r ) ) ); } finally { executorService.shutdown(); } }
/** * Creates reflection for package and base class. * @param pack * @param clazz */ public Reflection(String pack, Class clazz) { if (clazz.equals(Object.class)) { // @see http://stackoverflow.com/a/9571146 List<ClassLoader> classLoadersList = new LinkedList(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); this.reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false), new ResourcesScanner()) .addUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .addUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[1]))) .addUrls(ClasspathHelper.forJavaClassPath()) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(pack)))); } else { this.reflections = new Reflections(clazz); } }
public static void initialize() { // Scan for json configuration files on the classpath ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setScanners(new ResourcesScanner()); builder.setUrls(ClasspathHelper.forClassLoader( ClasspathHelper.contextClassLoader(), ClasspathHelper.staticClassLoader())); reflections = new Reflections(builder); json = new Json(); for (String path : reflections.getResources(Pattern.compile(".*\\.json"))) { if (!path.startsWith("items") && !path.startsWith("tiles") && !path.startsWith("walls")) continue; FileHandle file = Gdx.files.internal(path); Type type = json.fromJson(null, file); registerType(type); } airItem = getItem("airItem"); airTile = getTile("airTile"); airWall = getWall("airWall"); }
@Test public void testAll() throws IOException { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("net.bramp.dissector.zip")) .setScanners(new ResourcesScanner()) ); for (String path : reflections.getResources(Pattern.compile(".*\\.zip"))) { System.out.print(path); ExtendedRandomAccessFile in = open( path ); try { new ZipDissector().read(in); // Read but don't do anything with it System.out.println(" [OK]"); } catch (Exception e) { System.out.println(" [BAD]"); } } }
public static void installDefaultOverlays() throws IOException { // Create the overlay directory File overlayDir = AppConstants.OVERLAY_DIR; overlayDir.mkdirs(); // Copy default overlays from resources // https://dzone.com/articles/get-all-classes-within-package Reflections reflections = new Reflections(DEFAULT_OVERLAYS, new ResourcesScanner()); Set<String> resourcePathSet = reflections.getResources(Pattern.compile(".*")); for (String resourcePath : resourcePathSet) { URL inputUrl = AppSetup.class.getClassLoader().getResource(resourcePath); String resourceName = resourcePath.substring(DEFAULT_OVERLAYS.length()); try { log.info("Installing overlay: " + resourceName); FileUtils.copyURLToFile(inputUrl, new File(overlayDir, resourceName)); } catch (IOException e) { log.error("ERROR writing " + inputUrl); log.error(e); } } }
private Set<String> findAllPackages() { final List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); final Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[classLoadersList.size()]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(basePackage)))); final Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); final Set<String> packageNameSet = new TreeSet<String>(); for (final Class classInstance : classes) { packageNameSet.add(classInstance.getPackage().getName()); } return packageNameSet; }
public static Set<String> getImageFiles(String packageName) { Pattern pattern = Pattern.compile(".*\\.(png|gif|jpg|jpeg|jp2)"); Set<String> resources = new Reflections(packageName, new ResourcesScanner()) .getResources(pattern); Set<String> filteredResources = new HashSet<String>(); Map<String, Boolean> resMap = new ConcurrentHashMap<String, Boolean>(); for (String res : resources) { String resName = new File(res).getName(); if (!resMap.containsKey(resName)) { resMap.put(resName, true); filteredResources.add(resName); } } return filteredResources; }
private synchronized void loadLanguageResources(String languageCode) { if (loadedLanguages.contains(languageCode)) return; //Scan classpath for resources in the /dl4j_i18n/ directory... URL url = this.getClass().getResource("/" + DEFAULT_I8N_RESOURCES_DIR + "/"); Reflections reflections = new Reflections(new ConfigurationBuilder().setScanners(new ResourcesScanner()).setUrls(url)); String pattern = ".*" + languageCode; Set<String> resources = reflections.getResources(Pattern.compile(pattern)); Map<String, String> messages = new HashMap<>(); for (String s : resources) { if (!s.endsWith(languageCode)) continue; log.trace("Attempting to parse file: {}", s); parseFile(s, messages); } messagesByLanguage.put(languageCode, messages); loadedLanguages.add(languageCode); }
public static ArrayList<Class> getSubtypes(String rootPackage) { log.debug("------------ Getting all children of MOI from package: " + rootPackage); Reflections reflections = new Reflections(new ConfigurationBuilder() .filterInputsBy(new FilterBuilder.Include(FilterBuilder.prefix(rootPackage))) .setUrls(ClasspathHelper.forPackage(rootPackage)) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner(), new ResourcesScanner())); ArrayList<Class> annoList = new ArrayList<Class>(); annoList.addAll(reflections.getTypesAnnotatedWith(IgnoreFromTableCreation.class, true)); log.debug("annoList.size()::" + annoList.size()); ArrayList<Class> subTypesList = new ArrayList<Class>(); subTypesList.addAll(reflections.getSubTypesOf(ModelObjectInterface.class)); log.debug("getSubtypes: removing because it's annotated with @IgnoreFromTableCreation clazz = " + annoList); subTypesList.removeAll(annoList); log.debug("getSubtypes: found types: " + subTypesList); return subTypesList; }
public static ArrayList<Class> getSubtypes(Class rootClass) { log.debug("------------ Getting all children of MOI for class: " + rootClass.getCanonicalName()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forClass(rootClass)) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner(), new ResourcesScanner())); ArrayList<Class> annoList = new ArrayList<Class>(); annoList.addAll(reflections.getTypesAnnotatedWith(IgnoreFromTableCreation.class, true)); log.debug("annoList.size()::" + annoList.size()); ArrayList<Class> subTypesList = new ArrayList<Class>(); subTypesList.addAll(reflections.getSubTypesOf(ModelObjectInterface.class)); log.debug("getSubtypes: removing because it's annotated with @IgnoreFromTableCreation clazz = " + annoList); subTypesList.removeAll(annoList); log.debug("getSubtypes: found types: " + subTypesList); return subTypesList; }
/** * load every properties contained in the classpath * @return properties Object containing all loaded properties from every properties files contained in the classpath * @throws IOException */ public static Properties getProperties() throws IOException{ Predicate<String> filter = new FilterBuilder().include(".*.properties"); Reflections reflections = new Reflections(new ConfigurationBuilder() .filterInputsBy(filter) .setScanners(new ResourcesScanner()) .setUrls(Arrays.asList(ClasspathHelper.forClass(PropertyLoader.class)))); Set<String> propertiesfiles = reflections.getStore().get(ResourcesScanner.class).keySet(); Properties prop = new Properties(); for(Iterator<String> propertiesFilesIterator = propertiesfiles.iterator(); propertiesFilesIterator.hasNext();){ String currentPropertyFile = propertiesFilesIterator.next(); InputStream is = PropertyLoader.class.getClassLoader().getResourceAsStream(currentPropertyFile); if(is != null){ prop.load(is); } } return prop; }
private Reflections initializeReflections(final String packageNameOfVictims, final List<ClassLoader> classLoadersList) { SubTypesScanner scanner = new SubTypesScanner(false); ClassLoader[] loaders = classLoadersList.toArray(new ClassLoader[0]); FilterBuilder filter = new FilterBuilder() {{ include(FilterBuilder.prefix(packageNameOfVictims)); }}; ConfigurationBuilder builder = new ConfigurationBuilder() .setScanners(scanner, new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(loaders)) .filterInputsBy(filter); return new Reflections(builder); }
public static Collection<String> scan(final String path) { Reflections reflections = new Reflections( // new ConfigurationBuilder().setScanners( // new ResourcesScanner()).setUrls( // ClasspathHelper.forPackage(path))); Map<String, Multimap<String, String>> store = reflections.getStore().getStoreMap(); Preconditions.checkArgument(store.size() == 1, "Stores should just have one key"); Multimap<String, String> foundResouces = store.values().iterator().next(); return Collections2.filter(foundResouces.values(), new Predicate<String>() { @Override public boolean apply(String input) { return input.startsWith(path); } }); }
public static <T extends NamedTest> List<T> loadJsonResourceFiles(String packageName, Class<T> cls) throws IOException { // Preconditions.checkNotNull(packageName, "packageName cannot be null"); Reflections reflections = new Reflections(packageName, new ResourcesScanner()); Set<String> resources = reflections.getResources(new FilterBuilder.Include(".*")); List<T> datas = new ArrayList<>(resources.size()); Path packagePath = Paths.get("/" + packageName.replace(".", "/")); for (String resource : resources) { log.trace("Loading resource {}", resource); Path resourcePath = Paths.get("/" + resource); Path relativePath = packagePath.relativize(resourcePath); File resourceFile = new File("/" + resource); T data; try (InputStream inputStream = cls.getResourceAsStream(resourceFile.getAbsolutePath())) { data = ObjectMapperFactory.INSTANCE.readValue(inputStream, cls); } catch (IOException ex) { if (log.isErrorEnabled()) { log.error("Exception thrown while loading {}", resourcePath, ex); } throw ex; } String nameWithoutExtension = Files.getNameWithoutExtension(resource); if (null != relativePath.getParent()) { String parentName = relativePath.getParent().getFileName().toString(); data.testName(parentName + "/" + nameWithoutExtension); } else { data.testName(nameWithoutExtension); } datas.add(data); } return datas; }
private static Set<String> getClasspathResources(Set<String> filesExtensions) { Collection<URL> classpathJars = classpathJars(); System.out.println(classpathJars.size()); classpathJars.forEach(System.out::println); ConfigurationBuilder configuration = new ConfigurationBuilder() .setUrls(classpathJars) .setScanners(new ResourcesScanner()); configuration.setInputsFilter(Assets::isValidResourcePath); Reflections reflections = new Reflections(configuration); Set<String> resources = reflections.getResources(getResourcePattern(filesExtensions)); return resources; }
public static Set<String> getClasspathResources(Set<String> filesExtensions, Predicate<String> inputsFilter) { Collection<URL> classpathJars = getUsedJars(); System.out.println(classpathJars.size()); classpathJars.forEach(System.out::println); ConfigurationBuilder configuration = new ConfigurationBuilder().setUrls(classpathJars) .setScanners(new ResourcesScanner()); configuration.setInputsFilter(inputsFilter); Reflections reflections = new Reflections(configuration); Set<String> resources = reflections.getResources(getResourcePattern(filesExtensions)); return resources; }
static Set<Class<?>> getClasses(String packageName) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName)))); Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); return classes; }
private static void printUsage() { System.out.println("Usage: ./gradlew run -Pdemo=<demo>\n\nAvailable options for <demo>"); List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(testsPackage)))); Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); TreeSet<String> sortedClasses = new TreeSet<String>(); HashMap<String,String> classDescriptions = new HashMap<String, String>(); for (Class<? extends Object> cl : classes) { if (!cl.getSimpleName().equals("")) { sortedClasses.add(cl.getSimpleName()); String descString = ""; if (cl.getAnnotation(DemoDescription.class) != null) descString = cl.getAnnotation(DemoDescription.class).desc(); classDescriptions.put(cl.getSimpleName(),descString); } } for (String className : sortedClasses) { System.out.println(); List<String> descStrings = StringUtils.description(" \u001B[1m\u001b[32m"+className+"\u001b[0m: ", classDescriptions.get(className), 72, 6); for (String ds : descStrings) System.out.println(ds); } System.out.println(); String note = "Most examples require the ReedsSheppCarPlanner motion planner, which is provided via a" + "linked library that has to be built and depends on ompl (http://ompl.kavrakilab.org/)" + "and mrpt (http://www.mrpt.org/). See REAME.md for building instructions."; List<String> formattedNote = StringUtils.description("NOTE: ", note, 72); for (String line : formattedNote) System.out.println(line); }
public static <T extends NamedTest> List<T> loadJsonResourceFiles(String packageName, Class<T> cls) throws IOException { Preconditions.checkNotNull(packageName, "packageName cannot be null"); Reflections reflections = new Reflections(packageName, new ResourcesScanner()); Set<String> resources = reflections.getResources(new FilterBuilder.Include(".*")); List<T> datas = new ArrayList<>(resources.size()); Path packagePath = Paths.get("/" + packageName.replace(".", "/")); for (String resource : resources) { log.trace("Loading resource {}", resource); Path resourcePath = Paths.get("/" + resource); Path relativePath = packagePath.relativize(resourcePath); File resourceFile = new File("/" + resource); T data; try (InputStream inputStream = cls.getResourceAsStream(resourceFile.getAbsolutePath())) { data = ObjectMapperFactory.INSTANCE.readValue(inputStream, cls); } catch (IOException ex) { if (log.isErrorEnabled()) { log.error("Exception thrown while loading {}", resourcePath, ex); } throw ex; } String nameWithoutExtension = Files.getNameWithoutExtension(resource); if (null != relativePath.getParent()) { String parentName = relativePath.getParent().getFileName().toString(); data.testName(parentName + "/" + nameWithoutExtension); } else { data.testName(nameWithoutExtension); } datas.add(data); } return datas; }
public static <T extends NamedTest> List<T> loadJsonResourceFiles(String packageName, Class<T> cls) throws IOException { Preconditions.checkNotNull(packageName, "packageName cannot be null"); log.info("packageName = {}", packageName); // Preconditions.checkState(packageName.startsWith("/"), "packageName must start with a /."); Reflections reflections = new Reflections(packageName, new ResourcesScanner()); Set<String> resources = reflections.getResources(new FilterBuilder.Include("^.*\\.json$")); List<T> datas = new ArrayList<T>(resources.size()); Path packagePath = Paths.get("/" + packageName.replace(".", "/")); for (String resource : resources) { log.trace("Loading resource {}", resource); Path resourcePath = Paths.get("/" + resource); Path relativePath = packagePath.relativize(resourcePath); File resourceFile = new File("/" + resource); T data; try (InputStream inputStream = cls.getResourceAsStream(resourceFile.getAbsolutePath())) { data = ObjectMapperFactory.INSTANCE.readValue(inputStream, cls); } catch (IOException ex) { if (log.isErrorEnabled()) { log.error("Exception thrown while loading {}", resourcePath, ex); } throw ex; } if (null != relativePath.getParent()) { data.path(relativePath); } else { data.path(relativePath); } datas.add(data); } return datas; }
@Override public ReflectionsWrapper configure() { reflections = (Reflections) cache.get(Reflections.class.getName()); if (reflections == null) { ConfigurationBuilder cb = new ConfigurationBuilder(); Set<URL> classLocations = new LinkedHashSet<>(); try { List<URL> urls = Collections.list(Thread.currentThread().getContextClassLoader().getResources("")); for (URL url : urls) { if (url.getPath().contains("/geemvc/target/")) { classLocations.add(url); } } } catch (IOException e) { throw new IllegalStateException(e); } cb = cb.addUrls(classLocations).addClassLoader(Thread.currentThread().getContextClassLoader()); cb = cb.setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new MethodAnnotationsScanner(), new SubTypesScanner()); reflections = cb.build(); // Reflections cachedReflections = (Reflections) cache.putIfAbsent(Reflections.class.getName(), reflections); // if (cachedReflections != null) // reflections = cachedReflections; } return this; }
private CamelCatalog createCamelCatalog() throws IOException{ CamelCatalog result = new DefaultCamelCatalog(true); //add funktion camel components Predicate<String> filter = new FilterBuilder().includePackage("io.fabric8.funktion.camel"); Reflections resources = new Reflections(new ConfigurationBuilder() .filterInputsBy(filter) .setScanners(new ResourcesScanner()) .setUrls(ClasspathHelper.forJavaClassPath())); Set<String> jsonFiles = resources.getResources(Pattern.compile(".*\\.json")); LOG.info("Processing Funktion Camel components ..."); for (String jsonFile: jsonFiles){ InputStream inputStream = getClass().getClassLoader().getResourceAsStream(jsonFile); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(inputStream); JsonNode component = root.path("component"); if (!component.isMissingNode()) { String scheme = component.path("scheme").asText(); String componentName = component.path("javaType").asText(); result.addComponent(scheme,componentName); LOG.info("Processed component " + scheme); }else{ LOG.error("Failed to find Component for " + jsonFile); } } return result; }
public CommandManager() { ConfigurationBuilder builder = new ConfigurationBuilder() .setScanners(new SubTypesScanner(false), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(Arrays.asList(ClasspathHelper.contextClassLoader(), ClasspathHelper.staticClassLoader()).toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("github.scarsz.discordsrv.commands"))); builder = builder.setUrls(builder.getUrls().stream().filter(url -> !Pattern.compile(".*[.](so|dll)", Pattern.CASE_INSENSITIVE).matcher(url.getFile()).matches()).collect(Collectors.toList())); Reflections reflections = new Reflections(builder); for (String className : reflections.getAllTypes()) { Class clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException ignored) { continue; } if (clazz.isAnnotation()) continue; for (Method method : clazz.getMethods()) { if (!method.isAnnotationPresent(Command.class)) continue; // make sure method is marked as an annotation if (method.getParameters().length != 2) { DiscordSRV.debug("Method " + method.toGenericString().replace("public static void ", "") + " annotated as command but parameters count != 2"); continue; } if (method.getParameters()[0].getType() != CommandSender.class && method.getParameters()[0].getType() != Player.class) { DiscordSRV.debug("Method " + method.toGenericString().replace("public static void ", "") + " annotated as command but parameter 1's type != CommandSender || Player"); continue; } if (method.getParameters()[1].getType() != String[].class) { DiscordSRV.debug("Method " + method.toGenericString().replace("public static void ", "") + " annotated as command but parameter 2's type != String[]"); continue; } Command annotation = method.getAnnotation(Command.class); for (String commandName : annotation.commandNames()) commands.put(commandName.toLowerCase(), method); } } }
@Override public List<String> getDataMapperNames() { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()); cb.setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))); FilterBuilder fb = new FilterBuilder(); for (Package aPackage : getSearchPackages()) { fb.include(FilterBuilder.prefix(aPackage.getName())); } cb.filterInputsBy(fb); Reflections reflections = new Reflections(cb); Set<Class<?>> subTypesOf = reflections.getSubTypesOf(Object.class); ArrayList<String> collected = subTypesOf.stream() .map(Class::getSimpleName) .collect(Collectors.toCollection(ArrayList::new)); return collected; }
public static Collection<WSSimulation> classPathScanner(SimulationFilter simulationFilter) { List<SearchFilter> searchFilters = searchFilters(simulationFilter); Reflections reflections = new Reflections(packagePrefixFilter(searchFilters), new ResourcesScanner()); Set<String> candidateClasspathLocations = reflections.getResources(Pattern.compile(regexFilter(searchFilters))); List<WSSimulation> candidateSimulations = classpathToSimulations(candidateClasspathLocations); Collection<WSSimulation> wsSimulations = filterSimulationsByContent(candidateSimulations, simulationFilter); LOG.info("matched {} simulations", wsSimulations.size()); return wsSimulations; }
public DependencyInfo(URI uri) throws MalformedURLException { _url = uri.toURL(); FilterBuilder filter = new FilterBuilder().include(".*pom[.]properties"); Reflections ref = new Reflections(new ResourcesScanner(), _url, filter); Set<String> resources = ref.getResources(filter); Properties properties = new Properties(); if (resources.size() == 1) { String relativePath = resources.iterator().next(); try (URLClassLoader cl = new URLClassLoader(new URL[] {_url}, null)) { URL resource = cl.getResource(relativePath); if (resource != null) { try (InputStream in = resource.openStream()) { properties.load(in); } catch (IOException ex) { s_logger.debug(ex.getMessage(), ex); } } } catch (IOException ex2) { s_logger.debug(ex2.getMessage(), ex2); } } else if (_url.toString().endsWith(".jar")) { String name = StringUtils.substringAfterLast(_url.toString(), "/"); name = StringUtils.substringBeforeLast(name, ".jar"); properties.setProperty("version", StringUtils.substringAfterLast(name, "-")); properties.setProperty("groupId", "?"); properties.setProperty("artifactId", StringUtils.substringBeforeLast(name, "-")); } _version = properties.getProperty("version", "?"); _groupId = properties.getProperty("groupId", "?"); _artifactId = properties.getProperty("artifactId", "?"); }
public Collection<Class<? extends BrainGdxGame>> discover() { List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(APP_PACKAGE)))); return reflections.getSubTypesOf(BrainGdxGame.class); }
/** * Provides all classes in package 'com.jcabi.github'. * @return Classes */ public Iterable<Class<?>> allTypes() { return Iterables.filter( new Reflections( new ConfigurationBuilder() .setScanners( new SubTypesScanner(false), new ResourcesScanner() ) .setUrls( ClasspathHelper.forClassLoader( ClasspathHelper.contextClassLoader(), ClasspathHelper.staticClassLoader() ) ).filterInputsBy( new FilterBuilder().include( FilterBuilder.prefix("com.jcabi.github") ) ) ).getSubTypesOf(Object.class), new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { final String name = input.getName(); // @checkstyle BooleanExpressionComplexityCheck (6 lines) return !name.endsWith("Test") && !name.endsWith("ITCase") && !name.endsWith("ClasspathRule") && !name.endsWith("RepoRule") && (input.getEnclosingClass() == null || name.endsWith("Smart")); } } ); }
/** * Open all of the files found in the specified subdirectory of the provided * class. * * @param clazz the class location * @param folderPath the subdirectory in the class location * @return an array of {@link InputStream}s representing the files found */ public static InputStream[] openStreams(final Class clazz, final String folderPath) { if (null == folderPath) { return new InputStream[0]; } String folderPathChecked = getFormattedPath(folderPath); final HashSet<InputStream> inputStreams = Sets.newHashSet(); new Reflections(new ConfigurationBuilder() .setScanners(new ResourcesScanner()) .setUrls(ClasspathHelper.forClass(clazz))) .getResources(Pattern.compile(".*")) .stream() .filter(file -> file.startsWith(folderPathChecked)) .forEach(file -> { try { inputStreams.add(openStream(clazz, file)); } catch (final Exception e) { int closedStreamsCount = closeStreams(inputStreams.toArray(new InputStream[inputStreams.size()])); LOGGER.info(String.format("Closed %s input streams", closedStreamsCount)); } } ); if (inputStreams.isEmpty()) { throw new IllegalArgumentException("No file could be found in path: " + folderPath); } return inputStreams.toArray(new InputStream[inputStreams.size()]); }