Java Code Examples for org.springframework.core.io.support.ResourcePatternResolver

The following examples show how to use org.springframework.core.io.support.ResourcePatternResolver. 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: vividus   Source File: KnownIssueProvider.java    License: Apache License 2.0 6 votes vote down vote up
private void loadKnownIssueIdentifiers() throws IOException
{
    String locationPattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + fileName;
    Resource[] resources = applicationContext.getResources(locationPattern);
    if (resources.length > 0)
    {
        ObjectMapper objectMapper = ObjectMapperFactory.createWithCaseInsensitiveEnumDeserializer();
        MapType mapType = objectMapper.getTypeFactory().constructMapType(Map.class, String.class,
                BddKnownIssueIdentifier.class);
        for (Resource resource : resources)
        {
            LOGGER.debug("Loading known issue identifiers from {}", resource.getDescription());
            knownIssueIdentifiers.putAll(filter(objectMapper.readValue(resource.getInputStream(), mapType)));
        }
    }
    else
    {
        LOGGER.warn("Known issue functionality is not available. No resource is found by location pattern: {}",
                locationPattern);
    }
}
 
Example 2
Source Project: vividus   Source File: LoadVividusClassesTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
 void testClassLoading() throws Exception
{
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    ClassLoader classLoader = resourcePatternResolver.getClassLoader();
    for (Resource resource : resourcePatternResolver.getResources(LOCATION_PATTERN))
    {
        String url = resource.getURL().toExternalForm();
        Matcher matcher = CLASS_PATTERN.matcher(url);
        if (matcher.find())
        {
            String className = matcher.group(1);
            className = className.replace('/', '.');
            try
            {
                Class.forName(className, false, classLoader);
            }
            catch (NoClassDefFoundError e)
            {
                fail(className + SPLITTER + e.getClass().getCanonicalName() + SPLITTER + e.getMessage());
            }
        }
    }
}
 
Example 3
public LTSXmlApplicationContext(String[] paths) {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    List<Resource> resourceList = new ArrayList<Resource>();
    if (paths != null && paths.length > 0) {
        for (String path : paths) {
            try {
                Resource[] resources = resolver.getResources(path);
                if (resources != null && resources.length > 0) {
                    Collections.addAll(resourceList, resources);
                }
            } catch (IOException e) {
                LOGGER.error("resolve resource error: [path={}]", path, e);
            }
        }
    }

    configResources = new Resource[resourceList.size()];
    resourceList.toArray(configResources);

    refresh();
}
 
Example 4
Source Project: lams   Source File: ResourceEditorRegistrar.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Populate the given {@code registry} with the following resource editors:
 * ResourceEditor, InputStreamEditor, InputSourceEditor, FileEditor, URLEditor,
 * URIEditor, ClassEditor, ClassArrayEditor.
 * <p>If this registrar has been configured with a {@link ResourcePatternResolver},
 * a ResourceArrayPropertyEditor will be registered as well.
 * @see org.springframework.core.io.ResourceEditor
 * @see org.springframework.beans.propertyeditors.InputStreamEditor
 * @see org.springframework.beans.propertyeditors.InputSourceEditor
 * @see org.springframework.beans.propertyeditors.FileEditor
 * @see org.springframework.beans.propertyeditors.URLEditor
 * @see org.springframework.beans.propertyeditors.URIEditor
 * @see org.springframework.beans.propertyeditors.ClassEditor
 * @see org.springframework.beans.propertyeditors.ClassArrayEditor
 * @see org.springframework.core.io.support.ResourceArrayPropertyEditor
 */
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
	ResourceEditor baseEditor = new ResourceEditor(this.resourceLoader, this.propertyResolver);
	doRegisterEditor(registry, Resource.class, baseEditor);
	doRegisterEditor(registry, ContextResource.class, baseEditor);
	doRegisterEditor(registry, InputStream.class, new InputStreamEditor(baseEditor));
	doRegisterEditor(registry, InputSource.class, new InputSourceEditor(baseEditor));
	doRegisterEditor(registry, File.class, new FileEditor(baseEditor));
	if (pathClass != null) {
		doRegisterEditor(registry, pathClass, new PathEditor(baseEditor));
	}
	doRegisterEditor(registry, Reader.class, new ReaderEditor(baseEditor));
	doRegisterEditor(registry, URL.class, new URLEditor(baseEditor));

	ClassLoader classLoader = this.resourceLoader.getClassLoader();
	doRegisterEditor(registry, URI.class, new URIEditor(classLoader));
	doRegisterEditor(registry, Class.class, new ClassEditor(classLoader));
	doRegisterEditor(registry, Class[].class, new ClassArrayEditor(classLoader));

	if (this.resourceLoader instanceof ResourcePatternResolver) {
		doRegisterEditor(registry, Resource[].class,
				new ResourceArrayPropertyEditor((ResourcePatternResolver) this.resourceLoader, this.propertyResolver));
	}
}
 
Example 5
Source Project: aw-reporting   Source File: CsvReportEntitiesMapping.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Finds the beans classes that are annotated with {@code CsvReport} and extends the
 * {@code Report} base class.
 *
 * @param basePackage the package to be scanned.
 * @return the list of classes that match the requirements to be a report bean.
 */
private List<Class<? extends Report>> findReportBeans(String basePackage) throws IOException,
    ClassNotFoundException {
  ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
  MetadataReaderFactory metadataReaderFactory =
      new CachingMetadataReaderFactory(resourcePatternResolver);
  String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
      + resolveBasePackage(basePackage) + "/" + "**/*.class";
  Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);

  List<Class<? extends Report>> candidates = new ArrayList<Class<? extends Report>>();
  for (Resource resource : resources) {
    addCandidateIfApplicable(resource, metadataReaderFactory, candidates);
  }

  return candidates;
}
 
Example 6
/**
 * Returns an instance which uses the the specified selector, as the name of the
 * definition file(s). In the case of a name with a Spring "classpath*:" prefix,
 * or with no prefix, which is treated the same, the current thread's context class
 * loader's {@code getResources} method will be called with this value to get
 * all resources having that name. These resources will then be combined to form a
 * definition. In the case where the name uses a Spring "classpath:" prefix, or
 * a standard URL prefix, then only one resource file will be loaded as the
 * definition.
 * @param selector the location of the resource(s) which will be read and
 * combined to form the definition for the BeanFactoryLocator instance.
 * Any such files must form a valid ApplicationContext definition.
 * @return the corresponding BeanFactoryLocator instance
 * @throws BeansException in case of factory loading failure
 */
public static BeanFactoryLocator getInstance(String selector) throws BeansException {
	String resourceLocation = selector;
	if (resourceLocation == null) {
		resourceLocation = DEFAULT_RESOURCE_LOCATION;
	}

	// For backwards compatibility, we prepend "classpath*:" to the selector name if there
	// is no other prefix (i.e. "classpath*:", "classpath:", or some URL prefix).
	if (!ResourcePatternUtils.isUrl(resourceLocation)) {
		resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation;
	}

	synchronized (instances) {
		if (logger.isTraceEnabled()) {
			logger.trace("ContextSingletonBeanFactoryLocator.getInstance(): instances.hashCode=" +
					instances.hashCode() + ", instances=" + instances);
		}
		BeanFactoryLocator bfl = instances.get(resourceLocation);
		if (bfl == null) {
			bfl = new ContextSingletonBeanFactoryLocator(resourceLocation);
			instances.put(resourceLocation, bfl);
		}
		return bfl;
	}
}
 
Example 7
/**
 * Returns an instance which uses the specified selector, as the name of the
 * definition file(s). In the case of a name with a Spring "classpath*:" prefix,
 * or with no prefix, which is treated the same, the current thread's context class
 * loader's {@code getResources} method will be called with this value to get
 * all resources having that name. These resources will then be combined to form a
 * definition. In the case where the name uses a Spring "classpath:" prefix, or
 * a standard URL prefix, then only one resource file will be loaded as the
 * definition.
 * @param selector the location of the resource(s) which will be read and
 * combined to form the definition for the BeanFactoryLocator instance.
 * Any such files must form a valid ApplicationContext definition.
 * @return the corresponding BeanFactoryLocator instance
 * @throws BeansException in case of factory loading failure
 */
public static BeanFactoryLocator getInstance(String selector) throws BeansException {
	String resourceLocation = selector;
	if (resourceLocation == null) {
		resourceLocation = DEFAULT_RESOURCE_LOCATION;
	}

	// For backwards compatibility, we prepend "classpath*:" to the selector name if there
	// is no other prefix (i.e. "classpath*:", "classpath:", or some URL prefix).
	if (!ResourcePatternUtils.isUrl(resourceLocation)) {
		resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation;
	}

	synchronized (instances) {
		if (logger.isTraceEnabled()) {
			logger.trace("ContextSingletonBeanFactoryLocator.getInstance(): instances.hashCode=" +
					instances.hashCode() + ", instances=" + instances);
		}
		BeanFactoryLocator bfl = instances.get(resourceLocation);
		if (bfl == null) {
			bfl = new ContextSingletonBeanFactoryLocator(resourceLocation);
			instances.put(resourceLocation, bfl);
		}
		return bfl;
	}
}
 
Example 8
/**
 * Populate the given {@code registry} with the following resource editors:
 * ResourceEditor, InputStreamEditor, InputSourceEditor, FileEditor, URLEditor,
 * URIEditor, ClassEditor, ClassArrayEditor.
 * <p>If this registrar has been configured with a {@link ResourcePatternResolver},
 * a ResourceArrayPropertyEditor will be registered as well.
 * @see org.springframework.core.io.ResourceEditor
 * @see org.springframework.beans.propertyeditors.InputStreamEditor
 * @see org.springframework.beans.propertyeditors.InputSourceEditor
 * @see org.springframework.beans.propertyeditors.FileEditor
 * @see org.springframework.beans.propertyeditors.URLEditor
 * @see org.springframework.beans.propertyeditors.URIEditor
 * @see org.springframework.beans.propertyeditors.ClassEditor
 * @see org.springframework.beans.propertyeditors.ClassArrayEditor
 * @see org.springframework.core.io.support.ResourceArrayPropertyEditor
 */
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
	ResourceEditor baseEditor = new ResourceEditor(this.resourceLoader, this.propertyResolver);
	doRegisterEditor(registry, Resource.class, baseEditor);
	doRegisterEditor(registry, ContextResource.class, baseEditor);
	doRegisterEditor(registry, InputStream.class, new InputStreamEditor(baseEditor));
	doRegisterEditor(registry, InputSource.class, new InputSourceEditor(baseEditor));
	doRegisterEditor(registry, File.class, new FileEditor(baseEditor));
	doRegisterEditor(registry, Reader.class, new ReaderEditor(baseEditor));
	doRegisterEditor(registry, URL.class, new URLEditor(baseEditor));

	ClassLoader classLoader = this.resourceLoader.getClassLoader();
	doRegisterEditor(registry, URI.class, new URIEditor(classLoader));
	doRegisterEditor(registry, Class.class, new ClassEditor(classLoader));
	doRegisterEditor(registry, Class[].class, new ClassArrayEditor(classLoader));

	if (this.resourceLoader instanceof ResourcePatternResolver) {
		doRegisterEditor(registry, Resource[].class,
				new ResourceArrayPropertyEditor((ResourcePatternResolver) this.resourceLoader, this.propertyResolver));
	}
}
 
Example 9
@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 10
Source Project: seata-samples   Source File: DataSourceConfiguration.java    License: 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 11
Source Project: seata-samples   Source File: MyBatisConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
    MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
    bean.setDataSource(dataSourceProxy);
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    // bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
    bean.setMapperLocations(resolver.getResources("classpath*:mybatis/**/*-mapper.xml"));

    SqlSessionFactory factory = null;
    try {
        factory = bean.getObject();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return factory;
}
 
Example 12
Source Project: momo-cloud-permission   Source File: DataSourceConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean(name = "primarySqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
    final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setTypeAliasesPackage(TYPE_ALIASES_Package);
    PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();

    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + MAPPER_PATH;

    //添加插件
    sessionFactory.setPlugins(pageInterceptor());
    sessionFactory.setDataSource(dataSource);
    sessionFactory.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
    sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
    return sessionFactory.getObject();
}
 
Example 13
Source Project: kaif   Source File: ClassScanner.java    License: 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 14
Source Project: cola-cloud   Source File: FileUtils.java    License: MIT License 6 votes vote down vote up
public static String readByResourceLoader(String path) {
    String content = null;
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        Resource[] resources = resolver.getResources(path);
        for (Resource resource : resources) {
            InputStream stream = resource.getInputStream();// 获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流
            if (log.isInfoEnabled()) {
                log.info("读取的文件流  [" + stream + "]");
            }
            content = IOUtils.toString(stream, "UTF-8");
        }
    } catch (Exception e) {
        log.error("获取模板错误", e);
    }
    return content;
}
 
Example 15
@Bean
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
    PackagesSqlSessionFactoryBean sqlSessionFactory = new PackagesSqlSessionFactoryBean();
    sqlSessionFactory.setDataSource(dataSource);
    sqlSessionFactory.setTypeAliasesPackage(TYPE_ALIASES_PACKAGE);

    //配置分页插件,详情请查阅官方文档
    PageInterceptor interceptor = new PageInterceptor();
    Properties properties = new Properties();
    //分页尺寸为0时查询所有纪录不再执行分页
    properties.setProperty("pageSizeZero", "true");
    //页码<=0 查询第一页,页码>=总页数查询最后一页
    properties.setProperty("reasonable", "true");
    //支持通过 Mapper 接口参数来传递分页参数
    properties.setProperty("supportMethodsArguments", "true");
    interceptor.setProperties(properties);

    //添加插件
    //为了防止插件被重复注册,可以在启动类中使用"@SpringBootApplication(exclude = PageHelperAutoConfiguration.class)"排除默认的配置
    sqlSessionFactory.setPlugins(new Interceptor[]{interceptor});

    //添加XML目录
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    sqlSessionFactory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
    return sqlSessionFactory.getObject();
}
 
Example 16
private List<Class<?>> findMyTypes(String basePackage) 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)) {
				candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
			}
		}
	}
	return candidates;
}
 
Example 17
private Set<Class<?>> findTestComponents(String... basePackages) throws Exception {
    Set<Class<?>> testClzzList = new HashSet<>();
    for(String basePackage : basePackages){
        if(StringUtils.isBlank(basePackage)){
            continue;
        }
        String resourcePath = ClassUtils.convertClassNameToResourcePath(this.environment.resolveRequiredPlaceholders(basePackage));

        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            resourcePath + '/' + DEFAULT_RESOURCE_PATTERN;
        Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
        for(Resource res : resources){
            Class testClass = Thread.currentThread().getContextClassLoader().loadClass(getClassName(res));
            if(!isColaTestClass(testClass)){
                continue;
            }
            testClzzList.add(testClass);
        }
    }

    return testClzzList;
}
 
Example 18
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 19
Source Project: spring-batch   Source File: CapitalizeNamesJobConfig.java    License: MIT License 6 votes vote down vote up
@Bean
public MultiResourceItemReader<Person> multiItemReader() {
  ResourcePatternResolver patternResolver =
      new PathMatchingResourcePatternResolver();
  Resource[] resources = null;
  try {
    resources = patternResolver
        .getResources("file:target/test-inputs/*.csv");
  } catch (IOException e) {
    LOGGER.error("error reading files", e);
  }

  return new MultiResourceItemReaderBuilder<Person>()
      .name("multiPersonItemReader").delegate(itemReader())
      .resources(resources).setStrict(true).build();
}
 
Example 20
Source Project: lion   Source File: SeataDataSourceProxyConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
    MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    //bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
    bean.setMapperLocations(resolver.getResources(mapperLocations));

    SqlSessionFactory factory;
    try {
        factory = bean.getObject();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return factory;
}
 
Example 21
Source Project: lion   Source File: SeataDataSourceProxyConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
    MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    //bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
    bean.setMapperLocations(resolver.getResources(mapperLocations));

    SqlSessionFactory factory;
    try {
        factory = bean.getObject();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return factory;
}
 
Example 22
/**
 * Returns an instance which uses the the specified selector, as the name of the
 * definition file(s). In the case of a name with a Spring 'classpath*:' prefix,
 * or with no prefix, which is treated the same, the current thread context
 * ClassLoader's {@code getResources} method will be called with this value
 * to get all resources having that name. These resources will then be combined to
 * form a definition. In the case where the name uses a Spring 'classpath:' prefix,
 * or a standard URL prefix, then only one resource file will be loaded as the
 * definition.
 * @param selector the name of the resource(s) which will be read and
 * combined to form the definition for the BeanFactoryLocator instance.
 * Any such files must form a valid BeanFactory definition.
 * @return the corresponding BeanFactoryLocator instance
 * @throws BeansException in case of factory loading failure
 */
public static BeanFactoryLocator getInstance(String selector) throws BeansException {
	String resourceLocation = selector;
	if (resourceLocation == null) {
		resourceLocation = DEFAULT_RESOURCE_LOCATION;
	}

	// For backwards compatibility, we prepend 'classpath*:' to the selector name if there
	// is no other prefix (i.e. classpath*:, classpath:, or some URL prefix.
	if (!ResourcePatternUtils.isUrl(resourceLocation)) {
		resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation;
	}

	synchronized (instances) {
		if (logger.isTraceEnabled()) {
			logger.trace("SingletonBeanFactoryLocator.getInstance(): instances.hashCode=" +
					instances.hashCode() + ", instances=" + instances);
		}
		BeanFactoryLocator bfl = instances.get(resourceLocation);
		if (bfl == null) {
			bfl = new SingletonBeanFactoryLocator(resourceLocation);
			instances.put(resourceLocation, bfl);
		}
		return bfl;
	}
}
 
Example 23
Source Project: MicroCommunity   Source File: MyBatisConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setTypeAliasesPackage("tk.mybatis.springboot.model");

    //添加XML目录
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
       // bean.setMapperLocations(resolver.getResources("classpath:mapper/*/*.xml"));
        Resource[] resources = null;
        List<Resource> resourceList = new ArrayList<Resource>();
        for(String path : java110Properties.getMappingPath().split(",")) {
            resources = resolver.getResources(path);
            resourceList.addAll(Arrays.asList(resources));
        }
        bean.setMapperLocations(resourceList.toArray(new Resource[resourceList.size()]));
        return bean.getObject();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
 
Example 24
/**
 * Returns an instance which uses the specified selector, as the name of the
 * definition file(s). In the case of a name with a Spring 'classpath*:' prefix,
 * or with no prefix, which is treated the same, the current thread context
 * ClassLoader's {@code getResources} method will be called with this value
 * to get all resources having that name. These resources will then be combined to
 * form a definition. In the case where the name uses a Spring 'classpath:' prefix,
 * or a standard URL prefix, then only one resource file will be loaded as the
 * definition.
 * @param selector the name of the resource(s) which will be read and
 * combined to form the definition for the BeanFactoryLocator instance.
 * Any such files must form a valid BeanFactory definition.
 * @return the corresponding BeanFactoryLocator instance
 * @throws BeansException in case of factory loading failure
 */
public static BeanFactoryLocator getInstance(String selector) throws BeansException {
	String resourceLocation = selector;
	if (resourceLocation == null) {
		resourceLocation = DEFAULT_RESOURCE_LOCATION;
	}

	// For backwards compatibility, we prepend 'classpath*:' to the selector name if there
	// is no other prefix (i.e. classpath*:, classpath:, or some URL prefix.
	if (!ResourcePatternUtils.isUrl(resourceLocation)) {
		resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation;
	}

	synchronized (instances) {
		if (logger.isTraceEnabled()) {
			logger.trace("SingletonBeanFactoryLocator.getInstance(): instances.hashCode=" +
					instances.hashCode() + ", instances=" + instances);
		}
		BeanFactoryLocator bfl = instances.get(resourceLocation);
		if (bfl == null) {
			bfl = new SingletonBeanFactoryLocator(resourceLocation);
			instances.put(resourceLocation, bfl);
		}
		return bfl;
	}
}
 
Example 25
Source Project: cloudbreak   Source File: DefaultClusterTemplateCache.java    License: Apache License 2.0 5 votes vote down vote up
private List<String> getFiles() throws IOException {
    ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
    return Arrays.stream(patternResolver.getResources("classpath:" + defaultTemplateDir + "/**/*.json"))
            .map(resource -> {
                try {
                    String[] path = resource.getURL().getPath().split(defaultTemplateDir);
                    return String.format("%s%s", defaultTemplateDir, path[1]);
                } catch (IOException e) {
                    // wrap to runtime exception because of lambda and log the error in the caller method.
                    throw new RuntimeException(e);
                }
            }).collect(Collectors.toList());
}
 
Example 26
Source Project: mybatis.flying   Source File: SpringBootVFS.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<String> list(URL url, String path) throws IOException {
	ClassLoader cl = this.getClass().getClassLoader();
	ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
	Resource[] resources = resolver.getResources(path + "/**/*.class");
	List<Resource> resources1 = Arrays.asList(resources);
	List<String> resourcePaths = new ArrayList<String>();
	for (Resource resource : resources1) {
		resourcePaths.add(preserveSubpackageName(resource.getURI(), path));
	}
	return resourcePaths;
}
 
Example 27
Source Project: herd   Source File: ModelClassFinder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds all the model classes and the model error class.
 *
 * @throws MojoExecutionException if a class couldn't be instantiated or an I/O error occurred.
 */
private void findModelClasses() throws MojoExecutionException
{
    try
    {
        log.debug("Finding model classes.");

        // Get the model classes as resources.
        modelClasses = new HashSet<>();

        // Loop through each model resource and add each one to the set of model classes.
        for (Resource resource : ResourceUtils.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(modelJavaPackage)) +
            "/**/*.class"))
        {
            if (resource.isReadable())
            {
                MetadataReader metadataReader = new CachingMetadataReaderFactory(new PathMatchingResourcePatternResolver()).getMetadataReader(resource);
                Class<?> clazz = Class.forName(metadataReader.getClassMetadata().getClassName());
                modelClasses.add(clazz);
                log.debug("Found model class \"" + clazz.getName() + "\".");

                // If the model error class name is configured and matches this class, then hold onto it.
                if (clazz.getSimpleName().equals(modelErrorClassName))
                {
                    log.debug("Found model error class \"" + clazz.getName() + "\".");
                    modelErrorClass = clazz;
                }
            }
        }
    }
    catch (IOException | ClassNotFoundException e)
    {
        throw new MojoExecutionException("Error finding model classes. Reason: " + e.getMessage(), e);
    }
}
 
Example 28
Source Project: springdream   Source File: PatternResolverTest.java    License: 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 29
Source Project: web3sdk   Source File: P12Manager.java    License: Apache License 2.0 5 votes vote down vote up
public void load()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
                NoSuchProviderException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    keyStore = KeyStore.getInstance("PKCS12", "BC");
    Resource keyStoreResource = resolver.getResource(p12File);

    keyStore.load(keyStoreResource.getInputStream(), password.toCharArray());

    // logger.debug(" p12 load, keyStore: {}", keyStore);
}
 
Example 30
protected Map<String, ModuleDefinition> discoverModules(String baseDir, ResourcePatternResolver resolver) throws IOException {
    Map<String, ModuleDefinition> result = new HashMap<String, ModuleDefinition>();

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

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

    return result;
}