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

The following examples show how to use org.springframework.core.io.support.PathMatchingResourcePatternResolver. 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: PersistenceXmlParsingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetaInfCase() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/META-INF/persistence.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example #2
Source File: PersistenceXmlParsingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testExample3() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example3.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement3", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertEquals(0, info[0].getProperties().keySet().size());
	assertNull(info[0].getJtaDataSource());
	assertNull(info[0].getNonJtaDataSource());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example #3
Source File: PersistenceXmlParsingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testExample3() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example3.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement3", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertEquals(0, info[0].getProperties().keySet().size());
	assertNull(info[0].getJtaDataSource());
	assertNull(info[0].getNonJtaDataSource());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example #4
Source File: MybatisConfig.java    From ly-security with Apache License 2.0 6 votes vote down vote up
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws IOException {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

    //mybatis配置
    Properties prop = new Properties();
    prop.setProperty("mapUnderscoreToCamelCase", "true");

    sqlSessionFactoryBean.setConfigurationProperties(prop);
    sqlSessionFactoryBean.setTypeAliasesPackage("com.tc.ly.bean");

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources("classpath:mapper/*.xml");

    sqlSessionFactoryBean.setMapperLocations(resources);
    sqlSessionFactoryBean.setDataSource(dataSource);

    return sqlSessionFactoryBean;
}
 
Example #5
Source File: AbstractDataBaseBean.java    From spring-boot-starter-dao with Apache License 2.0 6 votes vote down vote up
protected final AbstractBeanDefinition createSqlSessionFactoryBean(String dataSourceName, String mapperPackage,
		String typeAliasesPackage, Dialect dialect, Configuration configuration) {
	configuration.setDatabaseId(dataSourceName);
	BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(SqlSessionFactoryBean.class);
	bdb.addPropertyValue("configuration", configuration);
	bdb.addPropertyValue("failFast", true);
	bdb.addPropertyValue("typeAliases", this.saenTypeAliases(typeAliasesPackage));
	bdb.addPropertyReference("dataSource", dataSourceName);
	bdb.addPropertyValue("plugins", new Interceptor[] { new CustomPageInterceptor(dialect) });
	if (!StringUtils.isEmpty(mapperPackage)) {
		try {
			mapperPackage = new StandardEnvironment().resolveRequiredPlaceholders(mapperPackage);
			String mapperPackages = ClassUtils.convertClassNameToResourcePath(mapperPackage);
			String mapperPackagePath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPackages + "/*.xml";
			Resource[] resources = new PathMatchingResourcePatternResolver().getResources(mapperPackagePath);
			bdb.addPropertyValue("mapperLocations", resources);
		} catch (Exception e) {
			log.error("初始化失败", e);
			throw new RuntimeException( String.format("SqlSessionFactory 初始化失败  mapperPackage=%s", mapperPackage + ""));
		}
	}
	return bdb.getBeanDefinition();
}
 
Example #6
Source File: PersistenceXmlParsingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testMetaInfCase() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/META-INF/persistence.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example #7
Source File: DataSourceConfig.java    From springbootexamples with Apache License 2.0 6 votes vote down vote up
/**
 * 多数据源的 SqlSessionFactory
 * @param dynamicDataSource
 * @return
 * @throws Exception
 */
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource)
        throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dynamicDataSource);
    //设置数据数据源的Mapper.xml路径
    bean.setMapperLocations(
            new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
    //设置Mybaties查询数据自动以驼峰式命名进行设值
    org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session
            .Configuration();
    configuration.setMapUnderscoreToCamelCase(true);
    bean.setConfiguration(configuration);

    return bean.getObject();
}
 
Example #8
Source File: AbstractBeanDefinitionReader.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create a new AbstractBeanDefinitionReader for the given bean factory.
 * <p>If the passed-in bean factory does not only implement the BeanDefinitionRegistry
 * interface but also the ResourceLoader interface, it will be used as default
 * ResourceLoader as well. This will usually be the case for
 * {@link org.springframework.context.ApplicationContext} implementations.
 * <p>If given a plain BeanDefinitionRegistry, the default ResourceLoader will be a
 * {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.
 * <p>If the passed-in bean factory also implements {@link EnvironmentCapable} its
 * environment will be used by this reader.  Otherwise, the reader will initialize and
 * use a {@link StandardEnvironment}. All ApplicationContext implementations are
 * EnvironmentCapable, while normal BeanFactory implementations are not.
 * @param registry the BeanFactory to load bean definitions into,
 * in the form of a BeanDefinitionRegistry
 * @see #setResourceLoader
 * @see #setEnvironment
 */
protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	this.registry = registry;

	// Determine ResourceLoader to use.
	if (this.registry instanceof ResourceLoader) {
		this.resourceLoader = (ResourceLoader) this.registry;
	}
	else {
		this.resourceLoader = new PathMatchingResourcePatternResolver();
	}

	// Inherit Environment if possible
	if (this.registry instanceof EnvironmentCapable) {
		this.environment = ((EnvironmentCapable) this.registry).getEnvironment();
	}
	else {
		this.environment = new StandardEnvironment();
	}
}
 
Example #9
Source File: TemplateGenerator.java    From spring-cloud-release with Apache License 2.0 6 votes vote down vote up
File generate(List<Project> projects,
		List<ConfigurationProperty> configurationProperties) {
	PathMatchingResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
	try {
		Resource[] resources = resourceLoader
				.getResources("templates/spring-cloud/*.hbs");
		List<TemplateProject> templateProjects = templateProjects(projects);
		for (Resource resource : resources) {
			File templateFile = resource.getFile();
			File outputFile = new File(outputFolder, renameTemplate(templateFile));
			Template template = template(templateFile.getName().replace(".hbs", ""));
			Map<String, Object> map = new HashMap<>();
			map.put("projects", projects);
			map.put("springCloudProjects", templateProjects);
			map.put("properties", configurationProperties);
			String applied = template.apply(map);
			Files.write(outputFile.toPath(), applied.getBytes());
			info("Successfully rendered [" + outputFile.getAbsolutePath() + "]");
		}
	}
	catch (IOException e) {
		throw new IllegalStateException(e);
	}
	return outputFolder;
}
 
Example #10
Source File: AbstractBeanDefinitionReader.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new AbstractBeanDefinitionReader for the given bean factory.
 * <p>If the passed-in bean factory does not only implement the BeanDefinitionRegistry
 * interface but also the ResourceLoader interface, it will be used as default
 * ResourceLoader as well. This will usually be the case for
 * {@link org.springframework.context.ApplicationContext} implementations.
 * <p>If given a plain BeanDefinitionRegistry, the default ResourceLoader will be a
 * {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.
 * <p>If the the passed-in bean factory also implements {@link EnvironmentCapable} its
 * environment will be used by this reader.  Otherwise, the reader will initialize and
 * use a {@link StandardEnvironment}. All ApplicationContext implementations are
 * EnvironmentCapable, while normal BeanFactory implementations are not.
 * @param registry the BeanFactory to load bean definitions into,
 * in the form of a BeanDefinitionRegistry
 * @see #setResourceLoader
 * @see #setEnvironment
 */
protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	this.registry = registry;

	// Determine ResourceLoader to use.
	if (this.registry instanceof ResourceLoader) {
		this.resourceLoader = (ResourceLoader) this.registry;
	}
	else {
		this.resourceLoader = new PathMatchingResourcePatternResolver();
	}

	// Inherit Environment if possible
	if (this.registry instanceof EnvironmentCapable) {
		this.environment = ((EnvironmentCapable) this.registry).getEnvironment();
	}
	else {
		this.environment = new StandardEnvironment();
	}
}
 
Example #11
Source File: FreemarkerSqlTemplates.java    From spring-data-jpa-extra with Apache License 2.0 6 votes vote down vote up
private void loadPatternResource(Set<String> names, String pattern) throws IOException {
    PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(
            resourceLoader);
    Resource[] resources = resourcePatternResolver.getResources(pattern);
    for (Resource resource : resources) {
        String resourceName = resource.getFilename().replace(suffix, "");
        if (names.contains(resourceName)) {
            //allow multi resource.
            List<Resource> resourceList;
            if (sqlResources.containsKey(resourceName)) {
                resourceList = sqlResources.get(resourceName);
            } else {
                resourceList = new LinkedList<>();
                sqlResources.put(resourceName, resourceList);
            }
            resourceList.add(resource);
        }
    }
}
 
Example #12
Source File: SqlSessionFactory2Config.java    From mybatis.flying with Apache License 2.0 6 votes vote down vote up
@Bean(name = "sqlSessionFactory2")
@Primary
public SqlSessionFactoryBean createSqlSessionFactory2Bean() throws IOException {
	SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
	/** 设置datasource */
	sqlSessionFactoryBean.setDataSource(dataSource2);
	VFS.addImplClass(SpringBootVFS.class);
	/** 设置mybatis configuration 扫描路径 */
	sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("Configuration.xml"));
	/** 设置typeAlias 包扫描路径 */
	sqlSessionFactoryBean.setTypeAliasesPackage("indi.mybatis.flying");
	/** 添加mapper 扫描路径 */
	PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
	Resource[] ra1 = resolver.getResources("classpath*:indi/mybatis/flying/mapper*/*.xml");
	sqlSessionFactoryBean.setMapperLocations(ra1); // 扫描映射文件
	return sqlSessionFactoryBean;
}
 
Example #13
Source File: DataSourceAutoConfiguration.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@Bean
public SqlSessionFactoryBean SqlSessionFactoryBean(DataSource dataSource) throws Exception {
	// Define path matcher resolver.
	PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

	// SqlSessionFactory
	SqlSessionFactoryBean factory = new MultipleSqlSessionFactoryBean();
	factory.setDataSource(dataSource);
	factory.setTypeAliases(getTypeAliases(resolver));
	factory.setConfigLocation(new ClassPathResource(configLocation));

	// Page.
	PageHelper pageHelper = new PageHelper();
	Properties props = new Properties();
	props.setProperty("dialect", "mysql");
	props.setProperty("reasonable", "true");
	props.setProperty("supportMethodsArguments", "true");
	props.setProperty("returnPageInfo", "check");
	props.setProperty("params", "count=countSql");
	pageHelper.setProperties(props); // 添加插件
	factory.setPlugins(new Interceptor[] { pageHelper });

	factory.setMapperLocations(resolver.getResources(mapperLocations));
	return factory;
}
 
Example #14
Source File: WeEventFileClientTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testPublishFileWithVerify() throws Exception {
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource resource = resolver.getResource("classpath:" + "0x2809a9902e47d6fcaabe6d0183855d9201c93af1.public.pem");

    WeEventFileClient weEventFileClient = new WeEventFileClient(this.groupId, this.localReceivePath, this.fileChunkSize, this.fiscoConfig);

    weEventFileClient.openTransport4Sender(this.topicName, resource.getInputStream());

    // handshake time delay for web3sdk
    Thread.sleep(1000*10);

    FileChunksMeta fileChunksMeta = weEventFileClient.publishFile(this.topicName,
            new File("src/main/resources/ca.crt").getAbsolutePath(), true);

    Assert.assertNotNull(fileChunksMeta);
}
 
Example #15
Source File: BeanConfig.java    From WeBASE-Codegen-Monkey with Apache License 2.0 6 votes vote down vote up
@Bean
public Map<String, Web3jTypeVO> getCustomDefineWeb3jMap() throws IOException {
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource def = resolver.getResource("file:config/web3j.def");
    File defFile = def.getFile();
    Map<String, Web3jTypeVO> map = new HashMap<String, Web3jTypeVO>();
    if (defFile.exists()) {
        log.info("defFile detect.");
        List<String> lines = FileUtils.readLines(defFile, "utf8");
        if (!CollectionUtils.isEmpty(lines)) {
            for (String line : lines) {
                line = line.replaceAll("\"", "");
                String[] tokens = StringUtils.split(line, ",");
                if (tokens.length < 4) {
                    continue;
                }
                Web3jTypeVO vo = new Web3jTypeVO();
                vo.setSolidityType(tokens[0]).setSqlType(tokens[1]).setJavaType(tokens[2]).setTypeMethod(tokens[3]);
                map.put(tokens[0], vo);
                log.info("Find Web3j type definetion : {}", JacksonUtils.toJson(vo));
            }
        }
    }
    return map;
}
 
Example #16
Source File: AvroCodecTests.java    From schema-evolution-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void reflectEncoderReflectDecoder() throws Exception{
	SchemaRegistryClient client = mock(SchemaRegistryClient.class);
	Schema schema = load("status.avsc");
	when(client.register(any())).thenReturn(10);
	when(client.fetch(eq(10))).thenReturn(schema);
	AvroCodec codec = new AvroCodec();
	codec.setSchemaRegistryClient(client);
	codec.setResolver(new PathMatchingResourcePatternResolver(new AnnotationConfigApplicationContext()));
	codec.setProperties(new AvroCodecProperties());
	codec.init();
	Status status = new Status("1","sample",System.currentTimeMillis());
	byte[] results = codec.encode(status);
	Status decoded = codec.decode(results,Status.class);
	Assert.assertEquals(status.getId(),decoded.getId());
}
 
Example #17
Source File: AbstractBeanDefinitionReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a new AbstractBeanDefinitionReader for the given bean factory.
 * <p>If the passed-in bean factory does not only implement the BeanDefinitionRegistry
 * interface but also the ResourceLoader interface, it will be used as default
 * ResourceLoader as well. This will usually be the case for
 * {@link org.springframework.context.ApplicationContext} implementations.
 * <p>If given a plain BeanDefinitionRegistry, the default ResourceLoader will be a
 * {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.
 * <p>If the passed-in bean factory also implements {@link EnvironmentCapable} its
 * environment will be used by this reader.  Otherwise, the reader will initialize and
 * use a {@link StandardEnvironment}. All ApplicationContext implementations are
 * EnvironmentCapable, while normal BeanFactory implementations are not.
 * @param registry the BeanFactory to load bean definitions into,
 * in the form of a BeanDefinitionRegistry
 * @see #setResourceLoader
 * @see #setEnvironment
 */
protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	this.registry = registry;

	// Determine ResourceLoader to use.
	if (this.registry instanceof ResourceLoader) {
		this.resourceLoader = (ResourceLoader) this.registry;
	}
	else {
		this.resourceLoader = new PathMatchingResourcePatternResolver();
	}

	// Inherit Environment if possible
	if (this.registry instanceof EnvironmentCapable) {
		this.environment = ((EnvironmentCapable) this.registry).getEnvironment();
	}
	else {
		this.environment = new StandardEnvironment();
	}
}
 
Example #18
Source File: Utility.java    From mercury with Apache License 2.0 6 votes vote down vote up
private List<String> getJarList(String path) {
    List<String> list = new ArrayList<>();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        Resource[] res = resolver.getResources(path);
        for (Resource r : res) {
            String name = r.getFilename();
            if (name != null) {
                list.add(name.endsWith(JAR) ? name.substring(0, name.length() - JAR.length()) : name);
            }
        }
    } catch (IOException e) {
        // ok to ignore
    }
    return list;
}
 
Example #19
Source File: MyBatisConfig.java    From cc-s with MIT License 6 votes vote down vote up
@Bean
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(env.getProperty("mybatis.config-location")));
    PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + env.getProperty("mybatis.mapper-locations");
    sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
    sqlSessionFactoryBean.setDataSource(dataSource());

    PageHelper pageHelper = new PageHelper();
    Properties properties = new Properties();
    properties.setProperty("reasonable", env.getProperty("pageHelper.reasonable"));
    properties.setProperty("supportMethodsArguments", env.getProperty("pageHelper.supportMethodsArguments"));
    properties.setProperty("returnPageInfo", env.getProperty("pageHelper.returnPageInfo"));
    properties.setProperty("params", env.getProperty("pageHelper.params"));
    pageHelper.setProperties(properties);
    sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});

    return sqlSessionFactoryBean;
}
 
Example #20
Source File: TestLabelsProperties.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected void testLabelsTranslations(String propertiesFolder, String properties1, String properties2) throws Throwable {
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources1 = resolver.getResources(propertiesFolder + properties1);
    Resource[] resources2 = resolver.getResources(propertiesFolder + properties2);
    Properties props1 = new Properties();
    Properties props2 = new Properties();
    props1.load(resources1[0].getInputStream());
    props2.load(resources2[0].getInputStream());
    Set<String> stringPropertyNames1 = props1.stringPropertyNames();
    Set<String> stringPropertyNames2 = props2.stringPropertyNames();
    stringPropertyNames1.removeAll(stringPropertyNames2);
    stringPropertyNames1.forEach((v) -> {
        logger.error("{}{} -> found error for the key {} check this or {} file to fix this error", propertiesFolder, properties1, v, properties2);
    });
    assertEquals(0, stringPropertyNames1.size());

    stringPropertyNames1 = props1.stringPropertyNames();
    stringPropertyNames2 = props2.stringPropertyNames();
    stringPropertyNames2.removeAll(stringPropertyNames1);
    stringPropertyNames2.forEach((v) -> {
        logger.error("{}{} found error for the key {} check this or {} file to fix this error", propertiesFolder, properties2, v, properties1);
    });
    assertEquals(0, stringPropertyNames2.size());
}
 
Example #21
Source File: PersistenceXmlParsingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testMetaInfCase() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/META-INF/persistence.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example #22
Source File: MybatisDataSourceConfig.java    From code with Apache License 2.0 6 votes vote down vote up
@Bean(name="sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
	SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
	bean.setDataSource(dataSource);
	// 添加XML目录
	ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
	try {
		bean.setMapperLocations(resolver.getResources("classpath:com/bfxy/springboot/mapping/*.xml"));
		SqlSessionFactory sqlSessionFactory = bean.getObject();
		sqlSessionFactory.getConfiguration().setCacheEnabled(Boolean.TRUE);
		
		return sqlSessionFactory;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #23
Source File: DataSource1Config.java    From Resource with GNU General Public License v3.0 6 votes vote down vote up
@Bean(name = "db1SqlSessionFactory")
public SqlSessionFactory setSqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource,
                                              @Qualifier("db1Configuration") org.apache.ibatis.session.Configuration configuration)
    throws Exception
{
    String url = "classpath:com/zsm/mapper/db1/*.xml";
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setConfiguration(configuration);
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(url));
    org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
    config.setMapUnderscoreToCamelCase(true); // 开启驼峰命名支持
    bean.setConfiguration(config);
    //格式化sql语句打印
    PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
    Properties properties = new Properties();
    properties.setProperty("format", "true");
    performanceInterceptor.setProperties(properties);
    bean.setPlugins(new Interceptor[] {performanceInterceptor});
    return bean.getObject();
}
 
Example #24
Source File: ActivitiConfig.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
@Bean
public SpringProcessEngineConfiguration springProcessEngineConfiguration() {
    SpringProcessEngineConfiguration spec = new SpringProcessEngineConfiguration();
    spec.setDataSource(dataSource);
    spec.setTransactionManager(platformTransactionManager);
    spec.setDatabaseSchemaUpdate("true");
    spec.setActivityFontName("宋体");
    spec.setAnnotationFontName("宋体");
    spec.setLabelFontName("宋体");
    Resource[] resources = null;
    // 启动自动部署流程
    try {
        resources = new PathMatchingResourcePatternResolver().getResources("classpath*:processes/*.bpmn");
    } catch (IOException e) {
        e.printStackTrace();
    }
    spec.setDeploymentResources(resources);
    return spec;
}
 
Example #25
Source File: XsdHelper.java    From celerio with Apache License 2.0 5 votes vote down vote up
public static String getResourceContentAsString(String resourcePath) {
    PathMatchingResourcePatternResolver o = new PathMatchingResourcePatternResolver();

    try {
        Resource packInfosAsResource[] = o.getResources(resourcePath);
        for (Resource r : packInfosAsResource) {
            return IOUtils.toString(r.getInputStream());
        }
        return null;
    } catch (IOException ioe) {
        throw new RuntimeException("Error while searching for : " + resourcePath, ioe);
    }
}
 
Example #26
Source File: PersistenceXmlParsingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Ignore  // not doing schema parsing anymore for JPA 2.0 compatibility
@Test
public void testInvalidPersistence() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-invalid.xml";
	try {
		reader.readPersistenceUnitInfos(resource);
		fail("expected invalid document exception");
	}
	catch (RuntimeException expected) {
	}
}
 
Example #27
Source File: PdfReportBuilderImpl.java    From cat-boot with Apache License 2.0 5 votes vote down vote up
private void loadResourceFonts() {
    try {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

        for (Resource font : resourcePatternResolver.getResources("classpath*:fonts/*.ttf")) {
            registerFont(font);
        }
    } catch (IOException e) {
        LOG.error("Failed to get files!", e);
    }
}
 
Example #28
Source File: MyBatisConfig.java    From jim-framework with Apache License 2.0 5 votes vote down vote up
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setTypeAliasesPackage("com.jim.dao.generated.entity");

    //分页插件
    PageHelper pageHelper = new PageHelper();
    Properties properties = new Properties();
    properties.setProperty("dialect", "postgresql");
    properties.setProperty("reasonable", "true");
    properties.setProperty("supportMethodsArguments", "true");
    properties.setProperty("returnPageInfo", "check");
    properties.setProperty("params", "count=countSql");
    pageHelper.setProperties(properties);

    //添加插件
    bean.setPlugins(new Interceptor[]{pageHelper});

    //添加XML目录
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        return bean.getObject();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
 
Example #29
Source File: AlfrescoEnviroment.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean exists(String classpath)
{
    ClassLoader cl = this.getClass().getClassLoader();
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
    Resource resource = resolver.getResource("classpath:" + classpath);
    return resource.exists();
}
 
Example #30
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;
}