Java Code Examples for org.springframework.core.io.support.ResourcePatternResolver#getResources()

The following examples show how to use org.springframework.core.io.support.ResourcePatternResolver#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: ClassScanner.java    From kaif with Apache License 2.0 6 votes vote down vote up
public static List<Class> searchAnnotatedClasses(String basePackage, Class<?> annotation)
    throws IOException, ClassNotFoundException {
  ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
  MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(
      resourcePatternResolver);

  List<Class> candidates = new ArrayList<>();
  String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
      resolveBasePackage(basePackage) + "/" + "**/*.class";
  Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
  for (Resource resource : resources) {
    if (resource.isReadable()) {
      MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
      if (isCandidate(metadataReader, annotation)) {
        candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
      }
    }
  }
  return candidates;
}
 
Example 2
Source File: CustomTagAnnotations.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Finds all the classes which have a BeanTag or BeanTags annotation
 *
 * @param basePackage the package to start in
 * @return classes which have BeanTag or BeanTags annotation
 * @throws IOException
 * @throws ClassNotFoundException
 */
protected static List<Class<?>> findTagClasses(String basePackage) throws IOException, ClassNotFoundException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class<?>> classes = new ArrayList<Class<?>>();

    String resolvedBasePackage = ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(
            basePackage));
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            resolvedBasePackage + "/" + "**/*.class";

    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (metadataReader != null && isBeanTag(metadataReader)) {
                classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            }
        }
    }

    return classes;
}
 
Example 3
Source File: AbstractProcessEngineConfiguration.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
public List<Resource> discoverProcessDefinitionResources(ResourcePatternResolver applicationContext, String prefix, List<String> suffixes, boolean checkPDs) throws IOException {
  if (checkPDs) {

  	List<Resource> result = new ArrayList<Resource>();
  	for (String suffix : suffixes) {
  		String path = prefix + suffix;
  		Resource[] resources = applicationContext.getResources(path);
  		if (resources != null && resources.length > 0) {
  			for (Resource resource : resources) {
  				result.add(resource);
  			}
  		}
  	}
  	
  	if (result.isEmpty()) {
    	logger.info(String.format("No process definitions were found for autodeployment"));
  	}
  	
    return result;
  }
  return new ArrayList<Resource>();
}
 
Example 4
Source File: Application.java    From Alice-LiveMan with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Map<String, String> env = System.getenv();
    for (String envName : env.keySet()) {
        System.out.format("%s=%s%n", envName, env.get(envName));
    }
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources("resources/*");
    for (Resource resource : resources) {
        File resourceFile = new File(resource.getFilename());
        try (FileOutputStream fos = new FileOutputStream(resourceFile)) {
            IOUtils.copyLarge(resource.getInputStream(), fos);
        }
        resourceFile.setExecutable(true);
        resourceFile.setReadable(true);
        resourceFile.setWritable(true);
    }
    SpringApplication.run(Application.class, args);
}
 
Example 5
Source File: PathMatchingSimpleStorageResourcePatternResolverTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void testLoadingClasspathFile() throws Exception {
	AmazonS3 amazonS3 = mock(AmazonS3.class);
	ResourcePatternResolver resourceLoader = getResourceLoader(amazonS3);

	Resource[] resources = resourceLoader.getResources(
			"classpath*:org/springframework/cloud/aws/core/io/s3/PathMatchingSimpleStorageResourcePatternResolverTest.class");
	assertThat(resources.length).isEqualTo(1);
	assertThat(resources[0].exists()).as("load without wildcards").isTrue();

	Resource[] resourcesWithFileNameWildcard = resourceLoader.getResources(
			"classpath*:org/**/PathMatchingSimpleStorageResourcePatternResolverTes?.class");
	assertThat(resourcesWithFileNameWildcard.length).isEqualTo(1);
	assertThat(resourcesWithFileNameWildcard[0].exists()).as("load with wildcards")
			.isTrue();
}
 
Example 6
Source File: DataSourceConfiguration.java    From seata-samples with Apache License 2.0 6 votes vote down vote up
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSourceProxy dataSourceProxy,
                                                   MybatisProperties mybatisProperties) {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSourceProxy);

    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        Resource[] mapperLocaltions = resolver.getResources(mybatisProperties.getMapperLocations()[0]);
        bean.setMapperLocations(mapperLocaltions);

        if (StringUtils.isNotBlank(mybatisProperties.getConfigLocation())) {
            Resource[] resources = resolver.getResources(mybatisProperties.getConfigLocation());
            bean.setConfigLocation(resources[0]);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bean;
}
 
Example 7
Source File: DataManager.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private void loadData() {
    try {
        final ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
        final Resource[] resources = resolver.getResources("classpath:/META-INF/syndesis/connector/*.json");
        ReadApiClientData reader = new ReadApiClientData(encryptionComponent);

        for (Resource resource: resources) {
            try (InputStream is = resource.getInputStream()) {
                // Replace placeholders
                final String text = reader.findAndReplaceTokens(
                    StreamUtils.copyToString(is, StandardCharsets.UTF_8),
                    System.getenv()
                );

                Connector connector = JsonUtils.reader().forType(Connector.class).readValue(text);

                if (connector != null) {
                    LOGGER.info("Load connector: {} from resource: {}", connector.getId().orElse(""), resource.getURI());
                    final String id = connector.getId().get();
                    final Connector existing = fetch(Connector.class, id);
                    if (existing != null) {
                        // the only mutable part of the Connector
                        final Map<String, String> existingConfiguredProperties = existing.getConfiguredProperties();
                        final Map<String, String> mergedConfiguredProperties = merge(existingConfiguredProperties, connector.getConfiguredProperties());
                        connector = connector.builder().configuredProperties(mergedConfiguredProperties).build();
                    }
                    store(connector, Connector.class);
                }
            }
        }
    } catch (FileNotFoundException ignored) {
        // ignore
    } catch (IOException e) {
        throw new IllegalStateException("Cannot load connector from resources due to: " + e.getMessage(), e);
    }
}
 
Example 8
Source File: ResourceBasedPipelineRepository.java    From piper with Apache License 2.0 5 votes vote down vote up
@Override
public List<Pipeline> findAll () {
  try {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources(locationPattern);
    return Arrays.asList(resources)
                 .stream()
                 .map(r -> read(r))
                 .collect(Collectors.toList());
  }
  catch(IOException e) {
    throw Throwables.propagate(e);
  }
}
 
Example 9
Source File: SchemaLoader.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Resource getSchema(String schemaName) throws IOException {
  if (schemaName.contains("/")) {
    schemaName = schemaName.substring(schemaName.lastIndexOf('/'));
  }

  ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
  String searchPattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/**/" + schemaName;
  Resource[] resources = resourcePatternResolver.getResources(searchPattern);

  if (resources.length == 0) {
    throw new RuntimeException("Could not find schema [" + schemaName + "]");
  }

  return resources[0];
}
 
Example 10
Source File: ClasspathModuleDefinitionLocator.java    From cosmic with Apache License 2.0 5 votes vote down vote up
protected Map<String, ModuleDefinition> discoverModules(final String baseDir, final ResourcePatternResolver resolver) throws IOException {
    final Map<String, ModuleDefinition> result = new HashMap<>();

    for (final Resource r : resolver.getResources(ModuleLocationUtils.getModulesLocation(baseDir))) {
        final DefaultModuleDefinition def = new DefaultModuleDefinition(baseDir, r, resolver);
        def.init();

        if (def.isValid()) {
            result.put(def.getName(), def);
        }
    }

    return result;
}
 
Example 11
Source File: PatternResolverTest.java    From springdream with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    //////
    // 加载所有xml后缀的资源
    //////

    Resource resources[] = resolver.getResources("classpath*:*.xml");
    for (Resource resource:resources) {
        System.out.println("资源为:" + resource.getDescription());
    }
}
 
Example 12
Source File: TFGraphTestAllHelper.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
private static String[] modelDirNames(String base_dir, ExecuteWith executeWith, String modelFileName) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new ClassPathResource(base_dir).getClassLoader());
    Resource[] resources = resolver.getResources("classpath*:" + base_dir + "/**/" + modelFileName );
    String[] exampleNames = new String[resources.length];
    for (int i = 0; i < resources.length; i++) {
        String nestedName = resources[i].getURL().toString().split(base_dir + "/")[1];
        exampleNames[i] = nestedName.replaceAll(Pattern.quote(base_dir), "").replaceAll("/" + modelFileName, "");
    }
    return exampleNames;
}
 
Example 13
Source File: MybatisProperties.java    From mapper-boot-starter with MIT License 5 votes vote down vote up
public Resource[] resolveMapperLocations() {
  ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
  List<Resource> resources = new ArrayList<Resource>();
  if (this.mapperLocations != null) {
    for (String mapperLocation : this.mapperLocations) {
      try {
        Resource[] mappers = resourceResolver.getResources(mapperLocation);
        resources.addAll(Arrays.asList(mappers));
      } catch (IOException e) {
        // ignore
      }
    }
  }
  return resources.toArray(new Resource[resources.size()]);
}
 
Example 14
Source File: TFGraphTestAllHelper.java    From nd4j with Apache License 2.0 5 votes vote down vote up
protected static Map<String, INDArray> readVars(String modelName, String base_dir, String pattern) throws IOException {
    Map<String, INDArray> varMap = new HashMap<>();
    String modelDir = base_dir + "/" + modelName;
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new ClassPathResource(modelDir).getClassLoader());
    Resource[] resources = resolver.getResources("classpath*:" + modelDir + "/" + pattern + ".shape");
    val dtype = Nd4j.dataType();
    for (int i = 0; i < resources.length; i++) {
        String fileName = resources[i].getFilename();
        String varPath = modelDir + "/" + fileName;
        String[] varNameArr = fileName.split("\\.");
        String varName = String.join(".", Arrays.copyOfRange(varNameArr, 0, varNameArr.length - 2));
        int[] varShape = Nd4j.readNumpy(new ClassPathResource(varPath).getInputStream(), ",").data().asInt();
        try {
            float[] varContents = Nd4j.readNumpy(new ClassPathResource(varPath.replace(".shape", ".csv")).getInputStream(), ",").data().asFloat();
            INDArray varValue;
            if (varShape.length == 1) {
                if (varShape[0] == 0) {
                    varValue = Nd4j.trueScalar(varContents[0]);
                } else {
                    varValue = Nd4j.trueVector(varContents);
                }
            } else {
                varValue = Nd4j.create(varContents, varShape);
            }
            //varValue = Nd4j.readNumpy(new ClassPathResource(varPath.replace(".shape", ".csv")).getInputStream(), ",").reshape(varShape);
            if (varName.contains("____")) {
                //these are intermediate node outputs
                varMap.put(varName.replaceAll("____", "/"), varValue);
            } else {
                varMap.put(varName, varValue);
            }
        } catch (NumberFormatException e) {
            // FIXME: we can't parse boolean arrays right now :(
            continue;
        }
    }
    return varMap;
}
 
Example 15
Source File: BootJarLoadingTest.java    From karate with MIT License 5 votes vote down vote up
SpringBootResourceLoader(ClassLoader cl, String packagePath) {
    String locationPattern = CLASSPATH_ALL_URL_PREFIX + "**/" + packagePath + "/**/*.feature";
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
    try {
        resources = resolver.getResources(locationPattern);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 16
Source File: ConfigurationResolver.java    From vividus with Apache License 2.0 5 votes vote down vote up
private static List<Resource> collectResourcesRecursively(ResourcePatternResolver resourcePatternResolver,
        String resourcePath) throws IOException
{
    List<Resource> propertyResources = new LinkedList<>();
    StringBuilder path = new StringBuilder(ROOT_LOCATION);
    String[] locationParts = resourcePath.isEmpty() ? new String[] { resourcePath }
            : StringUtils.split(resourcePath, DELIMITER);
    for (int i = 0; i < locationParts.length; i++)
    {
        boolean deepestLevel = i + 1 == locationParts.length;
        String locationPart = locationParts[i];
        path.append(locationPart);
        if (!locationPart.isEmpty())
        {
            path.append(DELIMITER);
        }
        String resourceLocation = path.toString() + "*.properties";
        Resource[] resources = resourcePatternResolver.getResources(resourceLocation);
        if (deepestLevel && resources.length == 0)
        {
            throw new IllegalStateException(
                    "No files with properties were found at location with pattern: " + resourceLocation);
        }
        propertyResources.addAll(Stream.of(resources).filter(Resource::exists).collect(Collectors.toList()));
    }
    return propertyResources;
}
 
Example 17
Source File: BlogUtils.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
public static List<Theme> getThemes() {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    List<Theme> themes = null;
    try {
        Resource[] resources = resolver.getResources("templates/*/about.json");
        themes = loadDirectory(resources);
        String location = System.getProperty("site.location");
        if (null != location) {
            themes.addAll(loadDirectory(Paths.get(location, "storage", "templates")));
        }
    } catch (Exception e) {
        log.error("load themes error {}", e.getMessage(), e);
    }
    return themes;
}
 
Example 18
Source File: DroolsAutoConfiguration.java    From drools-examples with Apache License 2.0 4 votes vote down vote up
private Resource[] getRuleFiles() throws IOException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    return resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");
}
 
Example 19
Source File: StubManagerConfig.java    From WeCross with Apache License 2.0 4 votes vote down vote up
@Bean
public StubManager newStubManager() {
    System.out.println("Initializing StubManager...");

    StubManager stubManager = new StubManager();

    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    try {
        Resource[] resources =
                resourcePatternResolver.getResources(
                        ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                                + ClassUtils.convertClassNameToResourcePath("com.webank")
                                + "/**/*.class");
        logger.debug("Total {} resources", resources.length);

        MetadataReaderFactory metadataReaderFabtFactory = new SimpleMetadataReaderFactory();
        for (Resource resource : resources) {
            logger.debug("Scan stub plugin: {}", resource.getURI().toString());
            MetadataReader metadataReader =
                    metadataReaderFabtFactory.getMetadataReader(resource);
            if (metadataReader.getAnnotationMetadata().hasAnnotation(Stub.class.getName())) {
                Map<String, Object> attributes =
                        metadataReader
                                .getAnnotationMetadata()
                                .getAnnotationAttributes(Stub.class.getName());
                String name = (String) attributes.get("value");

                if (stubManager.hasDriver(name)) {
                    throw new Exception(
                            "Duplicate stub plugin["
                                    + name
                                    + "]: "
                                    + resource.getURI().toString());
                }

                Class<?> claz = Class.forName(metadataReader.getClassMetadata().getClassName());
                StubFactory stubFactory =
                        (StubFactory) claz.getDeclaredConstructor().newInstance();

                stubManager.addStubFactory(name, stubFactory);

                logger.info("Load stub plugin[" + name + "]: " + resource.getURI().toString());
            }
        }
    } catch (Exception e) {
        String errorMsg = "Loading stub error: " + e;
        logger.error(errorMsg);
        System.exit(-1);
    }

    return stubManager;
}
 
Example 20
Source File: DroolsAutoConfiguration.java    From drools-examples with Apache License 2.0 4 votes vote down vote up
private Resource[] getRuleFiles() throws IOException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    return resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");
}