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

The following examples show how to use org.springframework.core.io.support.ResourcePatternResolver. 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: ResourceEditorRegistrar.java    From lams with 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 #3
Source File: SeataDataSourceProxyConfig.java    From lion with 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 #4
Source File: SingletonBeanFactoryLocator.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: LTSXmlApplicationContext.java    From light-task-scheduler with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: LoadVividusClassesTests.java    From vividus with 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 #7
Source File: KnownIssueProvider.java    From vividus with 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 #8
Source File: MyBatisConfig.java    From MicroCommunity with 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 #9
Source File: SingletonBeanFactoryLocator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #10
Source File: SeataDataSourceProxyConfig.java    From lion with 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 #11
Source File: CapitalizeNamesJobConfig.java    From spring-batch with 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 #12
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 #13
Source File: CsvReportEntitiesMapping.java    From aw-reporting with 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 #14
Source File: ContextSingletonBeanFactoryLocator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #15
Source File: FileUtils.java    From cola-cloud with 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 #16
Source File: MybatisConfigurer.java    From spring-boot-api-project-seed with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: DataSourceConfig.java    From momo-cloud-permission with 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 #18
Source File: MyBatisConfig.java    From seata-samples with 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 #19
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 #20
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 #21
Source File: ResourceEditorRegistrar.java    From spring4-understanding with Apache License 2.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));
	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 #22
Source File: AutomaticJobRegistrarConfiguration.java    From spring-boot-starter-batch-web with Apache License 2.0 6 votes vote down vote up
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 #23
Source File: ContextSingletonBeanFactoryLocator.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #24
Source File: ClassPathTestScanner.java    From COLA with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #25
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 #26
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 #27
Source File: PackagesSqlSessionFactoryBean.java    From spring-boot-api-project-seed with Apache License 2.0 5 votes vote down vote up
@Override
public void setTypeAliasesPackage(String typeAliasesPackage) {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
    typeAliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            ClassUtils.convertClassNameToResourcePath(typeAliasesPackage) + "/" + DEFAULT_RESOURCE_PATTERN;

    //将加载多个绝对匹配的所有Resource
    //将首先通过ClassLoader.getResource("META-INF")加载非模式路径部分
    //然后进行遍历模式匹配
    try {
        List<String> result = new ArrayList<>();
        Resource[] resources = resolver.getResources(typeAliasesPackage);
        if (resources.length > 0) {
            MetadataReader metadataReader = null;
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
                }
            }
        }
        if (!result.isEmpty()) {
            super.setTypeAliasesPackage(StringUtils.join(result.toArray(), ","));
        } else {
            String msg = String.format("参数typeAliasesPackage:%s,未找到任何包", typeAliasesPackage);
            logger.warn(msg);
        }
    } catch (IOException | ClassNotFoundException e) {
        logger.info(e.getMessage());
    }
}
 
Example #28
Source File: WriteOrReadDatabaseConfig.java    From demo-project with MIT License 5 votes vote down vote up
/**
 * 多数据源需要自己设置sqlSessionFactory
 */
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(routingDataSource());
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    // 实体类对应的位置
    bean.setTypeAliasesPackage(typeAliasesPackage);
    // mybatis的XML的配置
    bean.setMapperLocations(resolver.getResources(mapperLocation));
    bean.setConfigLocation(resolver.getResource(configLocation));
    return bean.getObject();
}
 
Example #29
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 #30
Source File: PEMManager.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public void load()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
                NoSuchProviderException, InvalidKeySpecException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource pemResources = resolver.getResource(pemFile);

    load(pemResources.getInputStream());
}