Java Code Examples for org.reflections.Reflections#getResources()

The following examples show how to use org.reflections.Reflections#getResources() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ItemManager.java    From Civs with 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 File: TestCase.java    From json-schema with 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 3
Source File: ModuleLoader.java    From mPaaS with 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 4
Source File: ModuleLoader.java    From mPass with 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 5
Source File: BatchDefaultT212MapperBenchmark.java    From hj-t212-parser with Apache License 2.0 5 votes vote down vote up
@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 6
Source File: TestDataUtils.java    From connect-utils with 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 7
Source File: TestDataUtils.java    From kafka-connect-spooldir with 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 8
Source File: ConnectorGenerator.java    From funktion-connectors with 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 9
Source File: UpgradeActions.java    From irontest with 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 10
Source File: ClasspathConfigSource.java    From incubator-gobblin with 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 11
Source File: AvroTestTools.java    From incubator-gobblin with 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 12
Source File: DependencyLoader.java    From mrgeo with 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 13
Source File: ReflectionsApp.java    From tutorials with 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;
}