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

The following examples show how to use org.springframework.core.io.support.ResourcePatternUtils. 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: SingletonBeanFactoryLocator.java    From blog_demos 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 #2
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 #3
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 #4
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 #5
Source File: DatabaseConfiguration.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);

    try {
        Properties properties = new Properties();
        properties.put("prefix", env.getDataSourcePrefix());
        sqlSessionFactoryBean.setConfigurationProperties(properties);
        sqlSessionFactoryBean
                .setMapperLocations(ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:/META-INF/admin-mybatis-mappings/*.xml"));
        sqlSessionFactoryBean.afterPropertiesSet();
        return sqlSessionFactoryBean.getObject();
    } catch (Exception e) {
        throw new RuntimeException("Could not create sqlSessionFactory", e);
    }

}
 
Example #6
Source File: AbstractSingleSpringContextTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Subclasses can override this method to return the locations of their
 * config files.
 * <p>A plain path will be treated as class path location, e.g.:
 * "org/springframework/whatever/foo.xml". Note however that you may prefix
 * path locations with standard Spring resource prefixes. Therefore, a
 * config location path prefixed with "classpath:" with behave the same as a
 * plain path, but a config location such as
 * "file:/some/path/path/location/appContext.xml" will be treated as a
 * filesystem location.
 * <p>The default implementation builds config locations for the config paths
 * specified through {@link #getConfigPaths()}.
 * @return an array of config locations
 * @see #getConfigPaths()
 * @see org.springframework.core.io.ResourceLoader#getResource(String)
 */
protected final String[] getConfigLocations() {
	String[] paths = getConfigPaths();
	String[] convertedPaths = new String[paths.length];
	for (int i = 0; i < paths.length; i++) {
		String path = paths[i];
		if (path.startsWith(SLASH)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path;
		}
		else if (!ResourcePatternUtils.isUrl(path)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + SLASH
					+ StringUtils.cleanPath(ClassUtils.classPackageAsResourcePath(getClass()) + SLASH + path);
		}
		else {
			convertedPaths[i] = StringUtils.cleanPath(path);
		}
	}
	return convertedPaths;
}
 
Example #7
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 #8
Source File: WebSecurityBeanConfig.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Bean
public MetadataStatementsProvider metadataStatementsProvider(MetadataItemsProvider metadataItemsProvider, ResourceLoader resourceLoader, ObjectConverter objectConverter) throws IOException {

    List<MetadataStatementsProvider> list = new ArrayList<>();
    list.add(new MetadataItemsMetadataStatementsProvider(metadataItemsProvider));

    JsonFileResourceMetadataStatementsProvider provider = new JsonFileResourceMetadataStatementsProvider(objectConverter);
    Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:metadata/test-tools/*.json");
    provider.setResources(Arrays.asList(resources));
    list.add(provider);

    return new AggregatingMetadataStatementsProvider(list);
}
 
Example #9
Source File: LocalSessionFactoryBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new LocalSessionFactoryBuilder for the given DataSource.
 * @param dataSource the JDBC DataSource that the resulting Hibernate SessionFactory should be using
 * (may be {@code null})
 * @param resourceLoader the ResourceLoader to load application classes from
 * @param metadataSources the Hibernate MetadataSources service to use (e.g. reusing an existing one)
 * @since 4.3
 */
public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader, MetadataSources metadataSources) {
	super(metadataSources);

	getProperties().put(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
	if (dataSource != null) {
		getProperties().put(AvailableSettings.DATASOURCE, dataSource);
	}

	// Hibernate 5.1/5.2: manually enforce connection release mode ON_CLOSE (the former default)
	try {
		// Try Hibernate 5.2
		AvailableSettings.class.getField("CONNECTION_HANDLING");
		getProperties().put("hibernate.connection.handling_mode", "DELAYED_ACQUISITION_AND_HOLD");
	}
	catch (NoSuchFieldException ex) {
		// Try Hibernate 5.1
		try {
			AvailableSettings.class.getField("ACQUIRE_CONNECTIONS");
			getProperties().put("hibernate.connection.release_mode", "ON_CLOSE");
		}
		catch (NoSuchFieldException ex2) {
			// on Hibernate 5.0.x or lower - no need to change the default there
		}
	}

	getProperties().put(AvailableSettings.CLASSLOADERS, Collections.singleton(resourceLoader.getClassLoader()));
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #10
Source File: GroovyBeanDefinitionReader.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Import Spring bean definitions from either XML or Groovy sources into the
 * current bean builder instance.
 * @param resourcePattern the resource pattern
 */
public void importBeans(String resourcePattern) throws IOException {
	Resource[] resources =
			ResourcePatternUtils.getResourcePatternResolver(getResourceLoader()).getResources(resourcePattern);
	for (Resource resource : resources) {
		String filename = resource.getFilename();
		if (filename.endsWith(".groovy")) {
			loadBeanDefinitions(resource);
		}
		else if (filename.endsWith(".xml")) {
			this.xmlBeanDefinitionReader.loadBeanDefinitions(resource);
		}
	}
}
 
Example #11
Source File: LocalSessionFactoryBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new LocalSessionFactoryBuilder for the given DataSource.
 * @param dataSource the JDBC DataSource that the resulting Hibernate SessionFactory should be using
 * (may be {@code null})
 * @param resourceLoader the ResourceLoader to load application classes from
 */
@SuppressWarnings("deprecation")  // to be able to build against Hibernate 4.3
public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader) {
	getProperties().put(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
	if (dataSource != null) {
		getProperties().put(Environment.DATASOURCE, dataSource);
	}
	// APP_CLASSLOADER is deprecated as of Hibernate 4.3 but we need to remain compatible with 4.0+
	getProperties().put(AvailableSettings.APP_CLASSLOADER, resourceLoader.getClassLoader());
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #12
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 #13
Source File: LookoutAllBootstrap.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
/**
 * copy configs from classpath to external fileSystem
 *
 * @param bootName
 * @throws IOException
 */
private static void copyConfigFiles(String bootName) throws IOException {
    Path tempDirectory = Files.createTempDirectory(bootName + "-configs");
    JSONObject configs = new JSONObject();
    configs.put("configDir", tempDirectory.toAbsolutePath().toString());
    String configsStr = configs.toJSONString();
    System.setProperty("sofaark.configs", configsStr);
    LOGGER.info("set system property sofaark.configs = {}", configsStr);

    // We now use ResourcePatternResolver from spring-core to help us find all properties in a directory
    Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(
        new ClassRelativeResourceLoader(LookoutAllBootstrap.class)).getResources(
        "classpath:app-configs/*/*.properties");
    for (Resource resource : resources) {
        String uri = resource.getURI().toString();
        int slashIndex1 = uri.lastIndexOf('/');
        int slashIndex0 = uri.lastIndexOf('/', slashIndex1 - 1);
        String app = uri.substring(slashIndex0 + 1, slashIndex1);
        String configName = uri.substring(slashIndex1 + 1);

        Path appConfigPath = tempDirectory.resolve(app);
        appConfigPath.toFile().mkdirs();
        Path targetPath = appConfigPath.resolve(configName);
        LOGGER.info("copy {} to {}", uri, targetPath);
        Files.copy(resource.getInputStream(), targetPath);
    }
}
 
Example #14
Source File: LocalSessionFactoryBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new LocalSessionFactoryBuilder for the given DataSource.
 * @param dataSource the JDBC DataSource that the resulting Hibernate SessionFactory should be using
 * (may be {@code null})
 * @param resourceLoader the ResourceLoader to load application classes from
 */
public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader) {
	getProperties().put(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
	if (dataSource != null) {
		getProperties().put(Environment.DATASOURCE, dataSource);
	}
	getProperties().put(AvailableSettings.CLASSLOADERS, Collections.singleton(resourceLoader.getClassLoader()));
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #15
Source File: JsonFileResourceMetadataStatementsProviderSpringTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Bean
public JsonFileResourceMetadataStatementsProvider jsonFileResourceMetadataItemListProvider(ResourceLoader resourceLoader) throws IOException {
    JsonFileResourceMetadataStatementsProvider provider = new JsonFileResourceMetadataStatementsProvider(objectConverter);
    Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:metadata/test-tools/*.json");
    provider.setResources(Arrays.asList(resources));
    return provider;
}
 
Example #16
Source File: LocalSessionFactoryBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new LocalSessionFactoryBuilder for the given DataSource.
 * @param dataSource the JDBC DataSource that the resulting Hibernate SessionFactory should be using
 * (may be {@code null})
 * @param resourceLoader the ResourceLoader to load application classes from
 */
@SuppressWarnings("deprecation")  // to be able to build against Hibernate 4.3
public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader) {
	getProperties().put(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
	if (dataSource != null) {
		getProperties().put(Environment.DATASOURCE, dataSource);
	}
	// APP_CLASSLOADER is deprecated as of Hibernate 4.3 but we need to remain compatible with 4.0+
	getProperties().put(AvailableSettings.APP_CLASSLOADER, resourceLoader.getClassLoader());
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #17
Source File: LocalSessionFactoryBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new LocalSessionFactoryBuilder for the given DataSource.
 * @param dataSource the JDBC DataSource that the resulting Hibernate SessionFactory should be using
 * (may be {@code null})
 * @param resourceLoader the ResourceLoader to load application classes from
 * @param metadataSources the Hibernate MetadataSources service to use (e.g. reusing an existing one)
 * @since 4.3
 */
public LocalSessionFactoryBuilder(
		@Nullable DataSource dataSource, ResourceLoader resourceLoader, MetadataSources metadataSources) {

	super(metadataSources);

	getProperties().put(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
	if (dataSource != null) {
		getProperties().put(AvailableSettings.DATASOURCE, dataSource);
	}

	// Hibernate 5.1/5.2: manually enforce connection release mode ON_CLOSE (the former default)
	try {
		// Try Hibernate 5.2
		AvailableSettings.class.getField("CONNECTION_HANDLING");
		getProperties().put("hibernate.connection.handling_mode", "DELAYED_ACQUISITION_AND_HOLD");
	}
	catch (NoSuchFieldException ex) {
		// Try Hibernate 5.1
		try {
			AvailableSettings.class.getField("ACQUIRE_CONNECTIONS");
			getProperties().put("hibernate.connection.release_mode", "ON_CLOSE");
		}
		catch (NoSuchFieldException ex2) {
			// on Hibernate 5.0.x or lower - no need to change the default there
		}
	}

	getProperties().put(AvailableSettings.CLASSLOADERS, Collections.singleton(resourceLoader.getClassLoader()));
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #18
Source File: LocalSessionFactoryBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a new LocalSessionFactoryBuilder for the given DataSource.
 * @param dataSource the JDBC DataSource that the resulting Hibernate SessionFactory should be using
 * (may be {@code null})
 * @param resourceLoader the ResourceLoader to load application classes from
 * @param metadataSources the Hibernate MetadataSources service to use (e.g. reusing an existing one)
 * @since 4.3
 */
public LocalSessionFactoryBuilder(
		@Nullable DataSource dataSource, ResourceLoader resourceLoader, MetadataSources metadataSources) {

	super(metadataSources);

	getProperties().put(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
	if (dataSource != null) {
		getProperties().put(AvailableSettings.DATASOURCE, dataSource);
	}

	// Hibernate 5.1/5.2: manually enforce connection release mode ON_CLOSE (the former default)
	try {
		// Try Hibernate 5.2
		AvailableSettings.class.getField("CONNECTION_HANDLING");
		getProperties().put("hibernate.connection.handling_mode", "DELAYED_ACQUISITION_AND_HOLD");
	}
	catch (NoSuchFieldException ex) {
		// Try Hibernate 5.1
		try {
			AvailableSettings.class.getField("ACQUIRE_CONNECTIONS");
			getProperties().put("hibernate.connection.release_mode", "ON_CLOSE");
		}
		catch (NoSuchFieldException ex2) {
			// on Hibernate 5.0.x or lower - no need to change the default there
		}
	}

	getProperties().put(AvailableSettings.CLASSLOADERS, Collections.singleton(resourceLoader.getClassLoader()));
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #19
Source File: JeesuiteMybatisConfiguration.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()).getResources(mapperLocations);
	String group = "default";
	MybatisMapperParser.addMapperLocations(group,resources);
	MybatisConfigs.addProperties(group, properties.getProperties());
	JeesuiteMybatisRegistry.register(group,sqlSessionFactory.getConfiguration());
}
 
Example #20
Source File: DatabaseConfiguration.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);
    String databaseType = initDatabaseType(dataSource);
    if (databaseType == null) {
        throw new FlowableException("couldn't deduct database type");
    }

    try {
        Properties properties = new Properties();
        properties.put("prefix", modelerAppProperties.getDataSourcePrefix());
        properties.put("blobType", "BLOB");
        properties.put("boolValue", "TRUE");

        properties.load(this.getClass().getClassLoader().getResourceAsStream("org/flowable/db/properties/" + databaseType + ".properties"));

        sqlSessionFactoryBean.setConfigurationProperties(properties);
        sqlSessionFactoryBean
                .setMapperLocations(ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:/META-INF/modeler-mybatis-mappings/*.xml"));
        sqlSessionFactoryBean.afterPropertiesSet();
        return sqlSessionFactoryBean.getObject();
    } catch (Exception e) {
        throw new FlowableException("Could not create sqlSessionFactory", e);
    }

}
 
Example #21
Source File: BeetlFrameworkConfig.java    From feiqu-opensource with Apache License 2.0 5 votes vote down vote up
/**
     *内容模板配置
     * @return
     */
    @Bean(name = "beetlContentTemplateConfig")
    public BeetlGroupUtilConfiguration getContentBeetlUtilConfiguration() {
        BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
        ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader());

        beetlGroupUtilConfiguration.setConfigFileResource(patternResolver.getResource("classpath:beetl.properties"));
//        ClasspathResourceLoader cploder = new ClasspathResourceLoader("/elasticsearch");
//        beetlGroupUtilConfiguration.setResourceLoader(cploder);
//        beetlGroupUtilConfiguration.setRoot("/");
        beetlGroupUtilConfiguration.init();

        return beetlGroupUtilConfiguration;
    }
 
Example #22
Source File: HibernateMappingContextConfiguration.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(applicationContext);
    String dsName = ConnectionSource.DEFAULT.equals(dataSourceName) ? "dataSource" : "dataSource_" + dataSourceName;
    Properties properties = getProperties();

    if(applicationContext.containsBean(dsName)) {
        properties.put(Environment.DATASOURCE, applicationContext.getBean(dsName));
    }
    properties.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, currentSessionContext.getName());
    properties.put(AvailableSettings.CLASSLOADERS, applicationContext.getClassLoader());
}
 
Example #23
Source File: SortedResourcesFactoryBean.java    From effectivejava with Apache License 2.0 4 votes vote down vote up
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #24
Source File: TestContextResourceUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Convert the supplied paths to classpath resource paths.
 *
 * <p>For each of the supplied paths:
 * <ul>
 * <li>A plain path &mdash; for example, {@code "context.xml"} &mdash; will
 * be treated as a classpath resource that is relative to the package in
 * which the specified class is defined.
 * <li>A path starting with a slash will be treated as an absolute path
 * within the classpath, for example: {@code "/org/example/schema.sql"}.
 * <li>A path which is prefixed with a URL protocol (e.g.,
 * {@link ResourceUtils#CLASSPATH_URL_PREFIX classpath:},
 * {@link ResourceUtils#FILE_URL_PREFIX file:}, {@code http:}, etc.) will be
 * {@link StringUtils#cleanPath cleaned} but otherwise unmodified.
 *
 * @param clazz the class with which the paths are associated
 * @param paths the paths to be converted
 * @return a new array of converted resource paths
 * @see #convertToResources
 */
public static String[] convertToClasspathResourcePaths(Class<?> clazz, String... paths) {
	String[] convertedPaths = new String[paths.length];
	for (int i = 0; i < paths.length; i++) {
		String path = paths[i];
		if (path.startsWith(SLASH)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path;
		}
		else if (!ResourcePatternUtils.isUrl(path)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + SLASH
					+ StringUtils.cleanPath(ClassUtils.classPackageAsResourcePath(clazz) + SLASH + path);
		}
		else {
			convertedPaths[i] = StringUtils.cleanPath(path);
		}
	}
	return convertedPaths;
}
 
Example #25
Source File: SortedResourcesFactoryBean.java    From effectivejava with Apache License 2.0 4 votes vote down vote up
public SortedResourcesFactoryBean(ResourceLoader resourceLoader, List<String> locations) {
	this.locations = locations;
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #26
Source File: WicketDependencyVersionChecker.java    From wicket-spring-boot with Apache License 2.0 4 votes vote down vote up
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #27
Source File: HibernateMappingContextSessionFactoryBean.java    From gorm-hibernate5 with Apache License 2.0 4 votes vote down vote up
public void setResourceLoader(ResourceLoader resourceLoader) {
    resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #28
Source File: DefaultPersistenceUnitManager.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #29
Source File: AnnotationSessionFactoryBean.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #30
Source File: SortedResourcesFactoryBean.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public SortedResourcesFactoryBean(ResourceLoader resourceLoader, List<String> locations) {
	this.locations = locations;
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}