Java Code Examples for org.reflections.scanners.ResourcesScanner

The following examples show how to use org.reflections.scanners.ResourcesScanner. These examples are extracted from open source projects. 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 Project: Civs   Source File: ItemManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void loadAllItemTypes() {
    final String ITEM_TYPES_FOLDER_NAME = Constants.ITEM_TYPES;
    String resourcePath = "resources." + ConfigManager.getInstance().getDefaultConfigSet() + "." + ITEM_TYPES_FOLDER_NAME;
    Reflections reflections = new Reflections(resourcePath, new ResourcesScanner());
    for (String fileName : reflections.getResources(Pattern.compile(".*\\.yml"))) {
        loopThroughResources("/" + fileName);
    }
    File itemTypesFolder = new File(Civs.dataLocation, ITEM_TYPES_FOLDER_NAME);
    if (itemTypesFolder.exists()) {
        for (File file : itemTypesFolder.listFiles()) {
            String itemName = file.getName().replace(".yml", "").toLowerCase();
            if (itemTypes.containsKey(itemName) &&
                    itemTypes.get(itemName).getItemType() != CivItem.ItemType.FOLDER) {
                continue;
            }
            loopThroughTypeFiles(file, null);
        }
    }
}
 
Example 2
Source Project: swagger-maven-plugin   Source File: JaxRSScanner.java    License: MIT License 6 votes vote down vote up
Application applicationInstance() {
    ConfigurationBuilder config = ConfigurationBuilder
            .build(resourcePackages)
            .setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
    Reflections reflections = new Reflections(config);
    Set<Class<? extends Application>> applicationClasses = reflections.getSubTypesOf(Application.class)
            .stream()
            .filter(this::filterClassByResourcePackages)
            .collect(Collectors.toSet());
    if (applicationClasses.isEmpty()) {
        return null;
    }
    if (applicationClasses.size() > 1) {
        log.warn("More than one javax.ws.rs.core.Application classes found on the classpath, skipping");
        return null;
    }
    return ClassUtils.createInstance(applicationClasses.iterator().next());
}
 
Example 3
Source Project: Java2PlantUML   Source File: Parser.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source Project: json-schema   Source File: TestCase.java    License: Apache License 2.0 6 votes vote down vote up
static List<Object[]> loadAsParamsFromPackage(String packageName) {
    List<Object[]> rval = new ArrayList<>();
    Reflections refs = new Reflections(packageName,
            new ResourcesScanner());
    Set<String> paths = refs.getResources(Pattern.compile(".*\\.json"));
    for (String path : paths) {
        if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) {
            continue;
        }
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        JSONArray arr = loadTests(TestSuiteTest.class.getResourceAsStream("/" + path));
        for (int i = 0; i < arr.length(); ++i) {
            JSONObject schemaTest = arr.getJSONObject(i);
            JSONArray testcaseInputs = schemaTest.getJSONArray("tests");
            for (int j = 0; j < testcaseInputs.length(); ++j) {
                JSONObject input = testcaseInputs.getJSONObject(j);
                TestCase testcase = new TestCase(input, schemaTest, fileName);
                rval.add(new Object[] { testcase, testcase.schemaDescription });
            }
        }
    }
    return rval;
}
 
Example 5
Source Project: oodt   Source File: Workbench.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 6
Source Project: mPaaS   Source File: ModuleLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 加载模块
 */
public void load() {
    Pattern pattern = Pattern.compile(RESOURCE_PATTERN);
    Reflections reflections = new Reflections(
            NamingConstant.BASE_PACKAGE,
            new ResourcesScanner()
    );
    // 获取资源路径
    Set<String> resources = reflections.getResources(pattern);
    resources.forEach(resource->{
        loadByProperties(resource);
    });
}
 
Example 7
Source Project: mPass   Source File: ModuleLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 加载模块
 */
public void load() {
    Pattern pattern = Pattern.compile(RESOURCE_PATTERN);
    Reflections reflections = new Reflections(
            NamingConstant.BASE_PACKAGE,
            new ResourcesScanner()
    );
    // 获取资源路径
    Set<String> resources = reflections.getResources(pattern);
    resources.forEach(resource->{
        loadByProperties(resource);
    });
}
 
Example 8
@Override
public MigrationSet getMigrationSet(final String basePackage) {
    checkNotNull(basePackage, "basePackage must not be null");

    final Set<String> resources = new Reflections(basePackage, new ResourcesScanner()).getResources(MIGRATION_FILE_PATTERN);
    final List<String> sortedResources = new ArrayList<>(resources);
    sortedResources.sort(String::compareTo);

    final List<MigrationSetEntry> migrationSetEntries = new LinkedList<>();
    for (String resource : sortedResources) {
        final String resourceName = resource.lastIndexOf("/") != -1 ? resource.substring(resource.lastIndexOf("/") + 1) : resource;
        final Matcher matcher = MIGRATION_FILE_PATTERN.matcher(resourceName);
        matcher.matches();

        final ChecksumedMigrationFile checksumedMigrationFile = yamlParser.parse(resource);
        migrationSetEntries.add(
                new MigrationSetEntry(
                        checksumedMigrationFile.getMigrationFile().getMigrations().stream().map(this::convertToMigration).collect(Collectors.toList()),
                        new MigrationMeta(
                                checksumedMigrationFile.getSha256Checksums(),
                                matcher.group(1).replaceAll("_", "."),
                                matcher.group(2)
                        )
                )
        );
    }

    migrationSetEntries.sort(Comparator.comparing(o -> o.getMigrationMeta().getVersion()));
    return new MigrationSet(migrationSetEntries);
}
 
Example 9
@Setup
public void init(){
    LoggerContext loggerContext= (LoggerContext) LoggerFactory.getILoggerFactory();
    //设置全局日志级别
    ch.qos.logback.classic.Logger logger = loggerContext.getLogger("root");
    logger.setLevel(Level.OFF);

    mapper = new T212Mapper()
            .enableDefaultParserFeatures()
            .enableDefaultVerifyFeatures();

    Reflections reflections = new Reflections("", new ResourcesScanner());
    Set<String> fileNames = reflections.getResources(Pattern.compile(".*\\.h212"));

    packets = fileNames.stream()
            .flatMap(fileName -> {
                try {
                    URI uri = this.getClass().getClassLoader().getResource(fileName).toURI();
                    return Files.readAllLines(Paths.get(uri))
                            .stream()
                            .map(line -> line + "\r\n");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return Stream.empty();
            })
            .collect(Collectors.toList());

    System.out.println("Packets :" + packets.size());
}
 
Example 10
Source Project: jkes   Source File: ClassUtils.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source Project: swagger-maven-plugin   Source File: JaxRSScanner.java    License: MIT License 5 votes vote down vote up
Set<Class<?>> classes() {
    ConfigurationBuilder config = ConfigurationBuilder
            .build(resourcePackages)
            .setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
    Reflections reflections = new Reflections(config);
    Stream<Class<?>> apiClasses = reflections.getTypesAnnotatedWith(Path.class)
            .stream()
            .filter(this::filterClassByResourcePackages);
    Stream<Class<?>> defClasses = reflections.getTypesAnnotatedWith(OpenAPIDefinition.class)
            .stream()
            .filter(this::filterClassByResourcePackages);
    return Stream.concat(apiClasses, defClasses).collect(Collectors.toSet());
}
 
Example 12
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.getName().replace(testsPackage+".",""));
				String descString = "";
				if (cl.getAnnotation(DemoDescription.class) != null) descString = cl.getAnnotation(DemoDescription.class).desc();
				classDescriptions.put(cl.getName().replace(testsPackage+".",""),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);
		
	}
 
Example 13
Source Project: connect-utils   Source File: PluginLoader.java    License: Apache License 2.0 5 votes vote down vote up
public PluginLoader(Package pkg) {
  this.pkg = pkg;
  this.reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forJavaClassPath())
      .forPackages(pkg.getName())
      .addScanners(new ResourcesScanner())
  );
}
 
Example 14
Source Project: connect-utils   Source File: TestDataUtils.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 15
Source Project: kafka-connect-spooldir   Source File: TestDataUtils.java    License: Apache License 2.0 5 votes vote down vote up
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;
  }
 
Example 16
Source Project: funktion-connectors   Source File: ConnectorGenerator.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 17
Source Project: irontest   Source File: UpgradeActions.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Result is sorted by fromVersion.
 * @param oldVersion
 * @param newVersion
 * @param subPackage
 * @param prefix
 * @param extension
 * @return
 */
private List<ResourceFile> getApplicableUpgradeResourceFiles(DefaultArtifactVersion oldVersion,
                                                             DefaultArtifactVersion newVersion, String subPackage,
                                                             String prefix, String extension) {
    List<ResourceFile> result = new ArrayList<>();

    Reflections reflections = new Reflections(
            getClass().getPackage().getName() + "." + subPackage, new ResourcesScanner());
    Set<String> upgradeFilePaths =
            reflections.getResources(Pattern.compile(prefix + ".*\\." + extension));
    for (String upgradeFilePath: upgradeFilePaths) {
        String[] upgradeFilePathFragments = upgradeFilePath.split("/");
        String upgradeFileName = upgradeFilePathFragments[upgradeFilePathFragments.length - 1];
        String[] versionsInUpgradeFileName = upgradeFileName.replace(prefix + "_", "").
                replace("." + extension, "").split("_To_");
        DefaultArtifactVersion fromVersionInUpgradeFileName = new DefaultArtifactVersion(
                versionsInUpgradeFileName[0].replace("_", "."));
        DefaultArtifactVersion toVersionInUpgradeFileName = new DefaultArtifactVersion(
                versionsInUpgradeFileName[1].replace("_", "."));
        if (fromVersionInUpgradeFileName.compareTo(oldVersion) >= 0 &&
                toVersionInUpgradeFileName.compareTo(newVersion) <=0) {
            ResourceFile upgradeResourceFile = new ResourceFile();
            upgradeResourceFile.setResourcePath(upgradeFilePath);
            upgradeResourceFile.setFromVersion(fromVersionInUpgradeFileName);
            upgradeResourceFile.setToVersion(toVersionInUpgradeFileName);
            result.add(upgradeResourceFile);
        }
    }

    Collections.sort(result);

    return result;
}
 
Example 18
Source Project: hbase-tools   Source File: Manager.java    License: Apache License 2.0 5 votes vote down vote up
private static Reflections createReflections() {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    return new Reflections(new ConfigurationBuilder()
        .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
        .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader(
            classLoadersList.toArray(new ClassLoader[classLoadersList.size()]))))
        .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command"))));
}
 
Example 19
Source Project: hbase-tools   Source File: Manager.java    License: Apache License 2.0 5 votes vote down vote up
private static Reflections createReflections() {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    return new Reflections(new ConfigurationBuilder()
        .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
        .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader(
            classLoadersList.toArray(new ClassLoader[classLoadersList.size()]))))
        .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command"))));
}
 
Example 20
Source Project: hbase-tools   Source File: Manager.java    License: Apache License 2.0 5 votes vote down vote up
private static Reflections createReflections() {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    return new Reflections(new ConfigurationBuilder()
        .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
        .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader(
            classLoadersList.toArray(new ClassLoader[classLoadersList.size()]))))
        .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command"))));
}
 
Example 21
Source Project: hbase-tools   Source File: Manager.java    License: Apache License 2.0 5 votes vote down vote up
private static Reflections createReflections() {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    return new Reflections(new ConfigurationBuilder()
        .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
        .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader(
            classLoadersList.toArray(new ClassLoader[classLoadersList.size()]))))
        .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command"))));
}
 
Example 22
Source Project: hbase-tools   Source File: Manager.java    License: Apache License 2.0 5 votes vote down vote up
private static Reflections createReflections() {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    return new Reflections(new ConfigurationBuilder()
        .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
        .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader(
            classLoadersList.toArray(new ClassLoader[classLoadersList.size()]))))
        .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command"))));
}
 
Example 23
Source Project: armeria   Source File: DocStringExtractor.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, String> getAllDocStrings0(ClassLoader classLoader) {
    final Configuration configuration = new ConfigurationBuilder()
            .filterInputsBy(new FilterBuilder().includePackage(path))
            .setUrls(ClasspathHelper.forPackage(path, classLoader))
            .addClassLoader(classLoader)
            .setScanners(new ResourcesScanner());
    if (configuration.getUrls() == null || configuration.getUrls().isEmpty()) {
        // No resource folders were found.
        return ImmutableMap.of();
    }

    final Reflections reflections = new Reflections(configuration);
    final Store store = reflections.getStore();
    if (!store.keySet().contains(ResourcesScanner.class.getSimpleName())) {
        // No resources were found.
        return ImmutableMap.of();
    }

    final Map<String, byte[]> files = reflections
            .getResources(this::acceptFile).stream()
            .map(f -> {
                try {
                    final URL url = classLoader.getResource(f);
                    if (url == null) {
                        throw new IllegalStateException("not found: " + f);
                    }
                    return Maps.immutableEntry(f, Resources.toByteArray(url));
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            })
            .collect(toImmutableMap(Entry::getKey, Entry::getValue));

    return getDocStringsFromFiles(files);
}
 
Example 24
Source Project: arangodb-java-driver   Source File: NativeImageHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static void generateReflectConfig() throws JsonProcessingException {
    System.out.println("---------------------------");
    System.out.println("--- reflect-config.json ---");
    System.out.println("---------------------------");

    List<String> packages = Arrays.asList("com.arangodb.entity", "com.arangodb.model");

    ObjectMapper mapper = new ObjectMapper();
    ArrayNode rootNode = mapper.createArrayNode();
    ObjectNode noArgConstructor = mapper.createObjectNode();
    noArgConstructor.put("name", "<init>");
    noArgConstructor.set("parameterTypes", mapper.createArrayNode());
    ArrayNode methods = mapper.createArrayNode();
    methods.add(noArgConstructor);

    packages.stream()
            .flatMap(p -> {
                final ConfigurationBuilder config = new ConfigurationBuilder()
                        .setScanners(new ResourcesScanner(), new SubTypesScanner(false))
                        .setUrls(ClasspathHelper.forPackage(p))
                        .filterInputsBy(new FilterBuilder().includePackage(p));

                return new Reflections(config).getSubTypesOf(Object.class).stream();
            })
            .map(Class::getName)
            .map(className -> {
                ObjectNode entry = mapper.createObjectNode();
                entry.put("name", className);
                entry.put("allDeclaredFields", true);
                entry.set("methods", methods);
                return entry;
            })
            .forEach(rootNode::add);

    String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
    System.out.println(jsonString);
}
 
Example 25
Source Project: incubator-gobblin   Source File: ClasspathConfigSource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Scan the classpath for {@link #classpathRootName} and return all resources under it.
 * {@inheritDoc}
 * @see org.apache.gobblin.config.store.deploy.DeployableConfigSource#getDeployableConfigPaths()
 */
private Set<String> getDeployableConfigPaths() {

  ConfigurationBuilder cb =
      new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader()).setScanners(new ResourcesScanner())
          .filterInputsBy(new FilterBuilder().include(String.format(".*%s.*", this.classpathRootName)));

  Reflections reflections = new Reflections(cb);
  Pattern pattern = Pattern.compile(".*");

  return reflections.getResources(pattern);
}
 
Example 26
Source Project: incubator-gobblin   Source File: AvroTestTools.java    License: Apache License 2.0 5 votes vote down vote up
static Set<String> getJsonFileSetByResourceRootName(String baseResource) {
  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .forPackages(baseResource)
      .filterInputsBy(name -> name.startsWith(baseResource))
      .setScanners(new ResourcesScanner()));

  return reflections.getResources(url -> url.endsWith(".json"));
}
 
Example 27
Source Project: mrgeo   Source File: DependencyLoader.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("squid:S1166") // Exception caught and handled
private static Set<Dependency> loadDependenciesByReflection(Class<?> clazz) throws IOException
{
  String jar = ClassUtil.findContainingJar(clazz);

  if (jar != null)
  {
    return loadDependenciesFromJar(jar);
  }
  else
  {
    // the properties may have been added on the classpath, lets see if we can find it...
    Set<Dependency> deps = null;

    // set up a resource scanner
    Reflections reflections = new Reflections(new ConfigurationBuilder()
        .setUrls(ClasspathHelper.forPackage(ClassUtils.getPackageName(DependencyLoader.class)))
        .setScanners(new ResourcesScanner()));

    Set<String> resources = reflections.getResources(Pattern.compile(".*dependencies\\.properties"));
    for (String resource : resources)
    {
      log.debug("Loading dependency properties from: /" + resource);

      InputStream is = DependencyLoader.class.getResourceAsStream("/" + resource);

      try
      {
        Set<Dependency> d = readDependencies(is);
        is.close();

        if (deps == null)
        {
          deps = d;
        }
        else
        {
          deps.addAll(d);
        }
      }
      finally
      {
        if (is != null)
        {
          try
          {
            is.close();
          }
          catch (IOException ignored)
          {
          }
        }
      }
    }

    return deps;
  }
}
 
Example 28
Source Project: tutorials   Source File: ReflectionsApp.java    License: MIT License 4 votes vote down vote up
public Set<String> getPomXmlPaths() {
    Reflections reflections = new Reflections(new ResourcesScanner());
    Set<String> resourcesSet = reflections.getResources(Pattern.compile(".*pom\\.xml"));
    return resourcesSet;
}