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

The following examples show how to use org.springframework.core.io.support.PathMatchingResourcePatternResolver. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
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 2
Source Project: springbootexamples   Source File: DataSourceConfig.java    License: 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 3
Source Project: ly-security   Source File: MybatisConfig.java    License: 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 4
Source Project: spring-analysis-note   Source File: PersistenceXmlParsingTests.java    License: 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 5
Source Project: spring-analysis-note   Source File: PersistenceXmlParsingTests.java    License: 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 6
Source Project: java-technology-stack   Source File: PersistenceXmlParsingTests.java    License: 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 7
/**
 * 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 8
Source Project: spring-cloud-release   Source File: TemplateGenerator.java    License: 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 9
/**
 * 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 10
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 11
Source Project: mybatis.flying   Source File: SqlSessionFactory2Config.java    License: 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 12
Source Project: MicroCommunity   Source File: ActivitiConfig.java    License: 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 13
Source Project: WeEvent   Source File: WeEventFileClientTest.java    License: 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 14
@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 15
Source Project: Resource   Source File: DataSource1Config.java    License: 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 16
Source Project: code   Source File: MybatisDataSourceConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean(name="sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
	SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
	bean.setDataSource(dataSource);
	// 添加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 17
Source Project: java-technology-stack   Source File: PersistenceXmlParsingTests.java    License: 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 18
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 19
Source Project: cc-s   Source File: MyBatisConfig.java    License: 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 Project: mercury   Source File: Utility.java    License: 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 21
/**
 * 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 22
Source Project: schema-evolution-samples   Source File: AvroCodecTests.java    License: 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 23
Source Project: WeBASE-Codegen-Monkey   Source File: BeanConfig.java    License: 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 24
@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 25
Source Project: deeplearning4j   Source File: TFGraphTestAllHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static String[] modelDirNames(String base_dir, ExecuteWith executeWith, String modelFileName) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new ClassPathResource(base_dir).getClassLoader());
    Resource[] resources = resolver.getResources("classpath*:" + base_dir + "/**/" + modelFileName );
    String[] exampleNames = new String[resources.length];
    for (int i = 0; i < resources.length; i++) {
        String nestedName = resources[i].getURL().toString().split(base_dir + "/")[1];
        exampleNames[i] = nestedName.replaceAll(Pattern.quote(base_dir), "").replaceAll("/" + modelFileName, "");
    }
    return exampleNames;
}
 
Example 26
Source Project: osiam   Source File: OsiamHome.java    License: MIT License 5 votes vote down vote up
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);
    }
}
 
Example 27
Source Project: tddl5   Source File: RuleCompatibleHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@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));
    }
}
 
Example 28
Source Project: jim-framework   Source File: MyBatisConfig.java    License: 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 Project: java-technology-stack   Source File: PersistenceXmlParsingTests.java    License: 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 30
Source Project: spring-analysis-note   Source File: PersistenceXmlParsingTests.java    License: MIT License 5 votes vote down vote up
@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());
}