下面列出了怎么用org.springframework.core.io.support.PathMatchingResourcePatternResolver的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
/**
* 多数据源的 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();
}
@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;
}
@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());
}
@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());
}
@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());
}
/**
* 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();
}
}
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;
}
/**
* 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();
}
}
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);
}
}
}
@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;
}
@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;
}
@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);
}
@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;
}
@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();
}
@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);
}
}
@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());
}
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());
}
@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;
}
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;
}
/**
* 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();
}
}
@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());
}
@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;
}
@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());
}
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;
}
public void initialize() {
try {
if (Files.notExists(osiamHome)) {
Files.createDirectories(osiamHome);
} else {
checkState(Files.isDirectory(osiamHome), "'osiam.home' (%s) is not a directory", osiamHome);
checkState(Files.isReadable(osiamHome), "'osiam.home' (%s) is not readable", osiamHome);
checkState(Files.isExecutable(osiamHome), "'osiam.home' (%s) is not accessible", osiamHome);
}
if (!isEmpty(osiamHome)) {
return;
}
checkState(Files.isWritable(osiamHome), "'osiam.home' (%s) is not writable", osiamHome);
Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:/home/**/*");
for (Resource resource : resources) {
// don't process directories
if (resource.getURL().toString().endsWith("/")) {
continue;
}
copyToHome(resource, osiamHome);
}
if (Files.notExists(osiamHome.resolve("data"))) {
Files.createDirectories(osiamHome.resolve("data"));
}
hasInitializedHome = true;
} catch (IOException e) {
throw new IllegalStateException("Could not initialize osiam.home", e);
}
}
@Test
public void testCompatible_le() {
try {
Resource resource = new PathMatchingResourcePatternResolver().getResource("classpath:compatible/le-spring-context.xml");
String ruleStr = StringUtils.join(IOUtils.readLines(resource.getInputStream()), SystemUtils.LINE_SEPARATOR);
ApplicationContext context = new StringXmlApplicationContext(RuleCompatibleHelper.compatibleRule(ruleStr));
VirtualTableRoot vtr1 = (VirtualTableRoot) context.getBean("vtabroot");
Assert.assertNotNull(vtr1);
} catch (IOException e) {
Assert.fail(ExceptionUtils.getFullStackTrace(e));
}
}
@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);
}
}
@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) {
}
}
@Test
public void testExample1() throws Exception {
PersistenceUnitReader reader = new PersistenceUnitReader(
new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
String resource = "/org/springframework/orm/jpa/persistence-example1.xml";
PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);
assertNotNull(info);
assertEquals(1, info.length);
assertEquals("OrderManagement", info[0].getPersistenceUnitName());
assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}