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

The following examples show how to use org.springframework.core.io.support.EncodedResource. 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: SQLiteUpgrade.java    From wind-im with Apache License 2.0 6 votes vote down vote up
/**
 * 通过sql脚本初始化数据库表
 *
 * @param conn
 * @throws SQLException
 */
private static void doInitWork(Connection conn) throws SQLException {
    try {
        // 生成临时sql文件加载数据库sql执行脚本,
        File sqlFile = new File(WINDCHAT_SQLITE_SQL);
        if (!sqlFile.exists()) {
            FileUtils.writeResourceToFile("/" + WINDCHAT_SQLITE_SQL, sqlFile);
        }

        // 初始化数据库表
        File file = new File(WINDCHAT_SQLITE_SQL);
        if (!file.exists()) {
            throw new FileNotFoundException("init mysql with sql script file is not exists");
        }

        FileSystemResource rc = new FileSystemResource(file);
        EncodedResource encodeRes = new EncodedResource(rc, "GBK");
        ScriptUtils.executeSqlScript(conn, encodeRes);
        SqlLog.info("windchat init sqlite with sql-script finish");

        file.delete();
    } catch (Exception e) {
        throw new SQLException(e);
    }
}
 
Example #2
Source File: SmtpMailer.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
private static JavaMailSender toMailSender(Map<ConfigurationKeys, ConfigurationManager.MaybeConfiguration> conf) {
    JavaMailSenderImpl r = new CustomJavaMailSenderImpl();
    r.setDefaultEncoding("UTF-8");

    r.setHost(conf.get(SMTP_HOST).getRequiredValue());
    r.setPort(Integer.parseInt(conf.get(SMTP_PORT).getRequiredValue()));
    r.setProtocol(conf.get(SMTP_PROTOCOL).getRequiredValue());
    r.setUsername(conf.get(SMTP_USERNAME).getValueOrDefault(null));
    r.setPassword(conf.get(SMTP_PASSWORD).getValueOrDefault(null));

    String properties = conf.get(SMTP_PROPERTIES).getValueOrDefault(null);

    if (properties != null) {
        try {
            Properties prop = PropertiesLoaderUtils.loadProperties(new EncodedResource(new ByteArrayResource(
                    properties.getBytes(StandardCharsets.UTF_8)), "UTF-8"));
            r.setJavaMailProperties(prop);
        } catch (IOException e) {
            log.warn("error while setting the mail sender properties", e);
        }
    }
    return r;
}
 
Example #3
Source File: ResourceLoadFactory.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    PropertySource<?> propSource = null;
    String propName = name;
    if (StringUtils.isEmpty(propName)) {
        propName = getNameForResource(resource.getResource());
    }
    if (resource.getResource().exists()) {
        String fileName = resource.getResource().getFilename();
        for (PropertySourceLoader loader : loaders) {
            if (checkFileType(fileName, loader.getFileExtensions())) {
                List<PropertySource<?>> propertySources = loader.load(propName, resource.getResource());
                if (!propertySources.isEmpty()) {
                    propSource = propertySources.get(0);
                }
            }
        }
    } else {
        throw new FileNotFoundException(propName + "对应文件'" + resource.getResource().getFilename() + "'不存在");
    }
    return propSource;
}
 
Example #4
Source File: I18nUtil.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
public static Properties loadI18nProp(){
    if (prop != null) {
        return prop;
    }
    try {
        // build i18n prop
        String i18nFile = "i18n/message.properties";

        // load prop
        Resource resource = new ClassPathResource(i18nFile);
        EncodedResource encodedResource = new EncodedResource(resource,"UTF-8");
        prop = PropertiesLoaderUtils.loadProperties(encodedResource);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return prop;
}
 
Example #5
Source File: I18nUtil.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
public static Properties loadI18nProp() {
    if (prop != null) {
        return prop;
    }
    try {
        // build i18n prop
        String i18n = XxlJobAdminConfig.getAdminConfig().getI18n();
        i18n = StringUtils.isNotBlank(i18n) ? ("_" + i18n) : i18n;
        String i18nFile = MessageFormat.format("i18n/message{0}.properties", i18n);

        // load prop
        Resource resource = new ClassPathResource(i18nFile);
        EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
        prop = PropertiesLoaderUtils.loadProperties(encodedResource);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return prop;
}
 
Example #6
Source File: I18nUtil.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
public static Properties loadI18nProp() {
    if (prop != null) {
        return prop;
    }
    try {
        // build i18n prop
        String i18n = XxlJobAdminConfig.getAdminConfig().getI18n();
        i18n = StringUtils.isNotBlank(i18n) ? ("_" + i18n) : i18n;
        String i18nFile = MessageFormat.format("i18n/message{0}.properties", i18n);

        // load prop
        Resource resource = new ClassPathResource(i18nFile);
        EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
        prop = PropertiesLoaderUtils.loadProperties(encodedResource);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return prop;
}
 
Example #7
Source File: InitDatabaseConnection.java    From openzaly with Apache License 2.0 6 votes vote down vote up
private static void initDatabaseTable(Connection conn) throws SQLException {
	try {
		// 生成临时sql文件加载数据库sql执行脚本,
		File sqlFile = new File(OPENZALY_MYSQL_SQL);
		if (!sqlFile.exists()) {
			FileUtils.writeResourceToFile("/" + OPENZALY_MYSQL_SQL, sqlFile);
		}

		// 初始化数据库表
		File file = new File(OPENZALY_MYSQL_SQL);
		if (!file.exists()) {
			throw new FileNotFoundException("init mysql with sql script file is not exists");
		}

		FileSystemResource rc = new FileSystemResource(file);
		EncodedResource encodeRes = new EncodedResource(rc, "GBK");
		ScriptUtils.executeSqlScript(conn, encodeRes);
		SqlLog.info("openzaly init mysql database with sql-script finish");

		file.delete();
	} catch (Exception e) {
		throw new SQLException(e);
	}
}
 
Example #8
Source File: SQLiteUpgrade.java    From openzaly with Apache License 2.0 6 votes vote down vote up
/**
 * 通过sql脚本初始化数据库表
 * 
 * @param conn
 * @throws SQLException
 */
private static void doInitWork(Connection conn) throws SQLException {
	try {
		// 生成临时sql文件加载数据库sql执行脚本,
		File sqlFile = new File(OPENZALY_SQLITE_SQL);
		if (!sqlFile.exists()) {
			FileUtils.writeResourceToFile("/" + OPENZALY_SQLITE_SQL, sqlFile);
		}

		// 初始化数据库表
		File file = new File(OPENZALY_SQLITE_SQL);
		if (!file.exists()) {
			throw new FileNotFoundException("init mysql with sql script file is not exists");
		}

		FileSystemResource rc = new FileSystemResource(file);
		EncodedResource encodeRes = new EncodedResource(rc, "GBK");
		ScriptUtils.executeSqlScript(conn, encodeRes);
		SqlLog.info("openzaly init sqlite with sql-script finish");

		file.delete();
	} catch (Exception e) {
		throw new SQLException(e);
	}
}
 
Example #9
Source File: DropPostgreSQLPublicSchemaTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    if (drop) {
        try {
            transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> {
                Session session = entityManager.unwrap(Session.class);
                session.doWork(connection -> {
                    ScriptUtils.executeSqlScript(connection,
                        new EncodedResource(
                            new ClassPathResource(
                                String.format("flyway/scripts/%1$s/drop/drop.sql", databaseType)
                            )
                        ),
                        true, true,
                        ScriptUtils.DEFAULT_COMMENT_PREFIX,
                        ScriptUtils.DEFAULT_BLOCK_COMMENT_START_DELIMITER,
                        ScriptUtils.DEFAULT_BLOCK_COMMENT_END_DELIMITER,
                        ScriptUtils.DEFAULT_COMMENT_PREFIX);
                });
                return null;
            });
        } catch (TransactionException e) {
            LOGGER.error("Failure", e);
        }
    }
}
 
Example #10
Source File: ApplicationContextExpressionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void resourceInjection() throws IOException {
	System.setProperty("logfile", "do_not_delete_me.txt");
	try (AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ResourceInjectionBean.class)) {
		ResourceInjectionBean resourceInjectionBean = ac.getBean(ResourceInjectionBean.class);
		Resource resource = new ClassPathResource("do_not_delete_me.txt");
		assertEquals(resource, resourceInjectionBean.resource);
		assertEquals(resource.getURL(), resourceInjectionBean.url);
		assertEquals(resource.getURI(), resourceInjectionBean.uri);
		assertEquals(resource.getFile(), resourceInjectionBean.file);
		assertArrayEquals(FileCopyUtils.copyToByteArray(resource.getInputStream()),
				FileCopyUtils.copyToByteArray(resourceInjectionBean.inputStream));
		assertEquals(FileCopyUtils.copyToString(new EncodedResource(resource).getReader()),
				FileCopyUtils.copyToString(resourceInjectionBean.reader));
	}
	finally {
		System.getProperties().remove("logfile");
	}
}
 
Example #11
Source File: InitDatabaseConnection.java    From openzaly with Apache License 2.0 6 votes vote down vote up
private static void initDatabaseTable(Connection conn) throws SQLException {
	try {
		// 生成临时sql文件加载数据库sql执行脚本,
		File sqlFile = new File(OPENZALY_MYSQL_SQL);
		if (!sqlFile.exists()) {
			FileUtils.writeResourceToFile("/" + OPENZALY_MYSQL_SQL, sqlFile);
		}

		// 初始化数据库表
		File file = new File(OPENZALY_MYSQL_SQL);
		if (!file.exists()) {
			throw new FileNotFoundException("init mysql with sql script file is not exists");
		}

		FileSystemResource rc = new FileSystemResource(file);
		EncodedResource encodeRes = new EncodedResource(rc, "GBK");
		ScriptUtils.executeSqlScript(conn, encodeRes);
		SqlLog.info("openzaly init mysql database with sql-script finish");

		file.delete();
	} catch (Exception e) {
		throw new SQLException(e);
	}
}
 
Example #12
Source File: XmlBeanDefinitionReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Load bean definitions from the specified XML file.
 * @param encodedResource the resource descriptor for the XML file,
 * allowing to specify an encoding to use for parsing the file
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
	Assert.notNull(encodedResource, "EncodedResource must not be null");
	if (logger.isInfoEnabled()) {
		logger.info("Loading XML bean definitions from " + encodedResource.getResource());
	}

	Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
	if (currentResources == null) {
		currentResources = new HashSet<EncodedResource>(4);
		this.resourcesCurrentlyBeingLoaded.set(currentResources);
	}
	if (!currentResources.add(encodedResource)) {
		throw new BeanDefinitionStoreException(
				"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
	}
	try {
		InputStream inputStream = encodedResource.getResource().getInputStream();
		try {
			InputSource inputSource = new InputSource(inputStream);
			if (encodedResource.getEncoding() != null) {
				inputSource.setEncoding(encodedResource.getEncoding());
			}
			return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
		}
		finally {
			inputStream.close();
		}
	}
	catch (IOException ex) {
		throw new BeanDefinitionStoreException(
				"IOException parsing XML document from " + encodedResource.getResource(), ex);
	}
	finally {
		currentResources.remove(encodedResource);
		if (currentResources.isEmpty()) {
			this.resourcesCurrentlyBeingLoaded.remove();
		}
	}
}
 
Example #13
Source File: ResourceDatabasePopulator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @see #execute(DataSource)
 */
@Override
public void populate(Connection connection) throws ScriptException {
	Assert.notNull(connection, "Connection must not be null");
	for (Resource script : this.scripts) {
		EncodedResource encodedScript = new EncodedResource(script, this.sqlScriptEncoding);
		ScriptUtils.executeSqlScript(connection, encodedScript, this.continueOnError, this.ignoreFailedDrops,
				this.commentPrefix, this.separator, this.blockCommentStartDelimiter, this.blockCommentEndDelimiter);
	}
}
 
Example #14
Source File: ResourceDatabasePopulator.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @see #execute(DataSource)
 */
@Override
public void populate(Connection connection) throws ScriptException {
	Assert.notNull(connection, "Connection must not be null");
	for (Resource script : this.scripts) {
		EncodedResource encodedScript = new EncodedResource(script, this.sqlScriptEncoding);
		ScriptUtils.executeSqlScript(connection, encodedScript, this.continueOnError, this.ignoreFailedDrops,
				this.commentPrefix, this.separator, this.blockCommentStartDelimiter, this.blockCommentEndDelimiter);
	}
}
 
Example #15
Source File: YamlPropertySourceFactory.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(encodedResource.getResource());

    Properties properties = factory.getObject();

    return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
 
Example #16
Source File: CompensablePropertySourceFactory.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
	if (name == null) {
		name = String.format("%s@%s", CompensablePropertySource.class, System.identityHashCode(resource));
	} // end-if (name == null)

	return new CompensablePropertySource(name, resource);
}
 
Example #17
Source File: YamlPropertySourceFactory.java    From spring-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    log.info("name is {}, resource is {}", name, resource);
    Properties propertiesFromYaml = loadYamlIntoProperties(resource);
    String sourceName = name != null ? name : resource.getResource().getFilename();
    log.info("sourceName is {}", sourceName);
    return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
 
Example #18
Source File: YamlPropertySourceFactory.java    From moon-api-gateway with MIT License 5 votes vote down vote up
@Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    String filename = resource.getResource().getFilename();

    if (filename != null && filename.endsWith(YML_FILE_EXTENSION)) {
        return name != null ? new YamlResourcePropertySource(name, resource) : new YamlResourcePropertySource(getNameForResource(resource.getResource()), resource);
    }

    return (name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource));
}
 
Example #19
Source File: ReaderEditor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void setAsText(String text) throws IllegalArgumentException {
	this.resourceEditor.setAsText(text);
	Resource resource = (Resource) this.resourceEditor.getValue();
	try {
		setValue(resource != null ? new EncodedResource(resource).getReader() : null);
	}
	catch (IOException ex) {
		throw new IllegalArgumentException("Failed to retrieve Reader for " + resource, ex);
	}
}
 
Example #20
Source File: XmlBeanDefinitionReader.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Load bean definitions from the specified XML file.
 * @param encodedResource the resource descriptor for the XML file,
 * allowing to specify an encoding to use for parsing the file
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
	Assert.notNull(encodedResource, "EncodedResource must not be null");
	if (logger.isTraceEnabled()) {
		logger.trace("Loading XML bean definitions from " + encodedResource);
	}

	Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
	if (currentResources == null) {
		currentResources = new HashSet<>(4);
		this.resourcesCurrentlyBeingLoaded.set(currentResources);
	}
	if (!currentResources.add(encodedResource)) {
		throw new BeanDefinitionStoreException(
				"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
	}
	try {
		InputStream inputStream = encodedResource.getResource().getInputStream();
		try {
			InputSource inputSource = new InputSource(inputStream);
			if (encodedResource.getEncoding() != null) {
				inputSource.setEncoding(encodedResource.getEncoding());
			}
			return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
		}
		finally {
			inputStream.close();
		}
	}
	catch (IOException ex) {
		throw new BeanDefinitionStoreException(
				"IOException parsing XML document from " + encodedResource.getResource(), ex);
	}
	finally {
		currentResources.remove(encodedResource);
		if (currentResources.isEmpty()) {
			this.resourcesCurrentlyBeingLoaded.remove();
		}
	}
}
 
Example #21
Source File: XmlBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testRefToSingleton() throws Exception {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
	reader.loadBeanDefinitions(new EncodedResource(REFTYPES_CONTEXT, "ISO-8859-1"));

	TestBean jen = (TestBean) xbf.getBean("jenny");
	TestBean dave = (TestBean) xbf.getBean("david");
	TestBean jenks = (TestBean) xbf.getBean("jenks");
	ITestBean davesJen = dave.getSpouse();
	ITestBean jenksJen = jenks.getSpouse();
	assertTrue("1 jen instance", davesJen == jenksJen);
	assertTrue("1 jen instance", davesJen == jen);
}
 
Example #22
Source File: EncodedFileSystemResourceLoaderDemo.java    From geekbang-lessons with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    String currentJavaFilePath = "/" + System.getProperty("user.dir") + "/thinking-in-spring/resource/src/main/java/org/geekbang/thinking/in/spring/resource/EncodedFileSystemResourceLoaderDemo.java";
    // 新建一个 FileSystemResourceLoader 对象
    FileSystemResourceLoader resourceLoader = new FileSystemResourceLoader();
    // FileSystemResource => WritableResource => Resource
    Resource resource = resourceLoader.getResource(currentJavaFilePath);
    EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
    // 字符输入流
    try (Reader reader = encodedResource.getReader()) {
        System.out.println(IOUtils.toString(reader));
    }
}
 
Example #23
Source File: GroovyBeanDefinitionReader.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Load bean definitions from the specified Groovy script.
 * @param encodedResource the resource descriptor for the Groovy script,
 * allowing to specify an encoding to use for parsing the file
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
	Closure beans = new Closure(this){
		public Object call(Object[] args) {
			invokeBeanDefiningClosure((Closure) args[0]);
			return null;
		}
	};
	Binding binding = new Binding() {
		@Override
		public void setVariable(String name, Object value) {
			if (currentBeanDefinition !=null) {
				applyPropertyToBeanDefinition(name, value);
			}
			else {
				super.setVariable(name, value);
			}
		}
	};
	binding.setVariable("beans", beans);

	int countBefore = getRegistry().getBeanDefinitionCount();
	try {
		GroovyShell shell = new GroovyShell(getResourceLoader().getClassLoader(), binding);
		shell.evaluate(encodedResource.getReader(), encodedResource.getResource().getFilename());
	}
	catch (Throwable ex) {
		throw new BeanDefinitionParsingException(new Problem("Error evaluating Groovy script: " + ex.getMessage(),
				new Location(encodedResource.getResource()), null, ex));
	}
	return getRegistry().getBeanDefinitionCount() - countBefore;
}
 
Example #24
Source File: CompensablePropertySource.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
public CompensablePropertySource(String name, EncodedResource source) {
	super(name, source);

	EncodedResource encoded = (EncodedResource) this.getSource();
	AbstractResource resource = (AbstractResource) encoded.getResource();
	String path = resource.getFilename();

	if (StringUtils.isBlank(path)) {
		return;
	}

	String[] values = path.split(":");
	if (values.length != 2) {
		return;
	}

	String protocol = values[0];
	String resName = values[1];
	if ("bytetcc".equalsIgnoreCase(protocol) == false) {
		return;
	} else if ("loadbalancer.config".equalsIgnoreCase(resName) == false) {
		return;
	}

	this.enabled = true;

}
 
Example #25
Source File: StaticApplicationContextMulticasterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected ConfigurableApplicationContext createContext() throws Exception {
	StaticApplicationContext parent = new StaticApplicationContext();
	Map<String, String> m = new HashMap<String, String>();
	m.put("name", "Roderick");
	parent.registerPrototype("rod", TestBean.class, new MutablePropertyValues(m));
	m.put("name", "Albert");
	parent.registerPrototype("father", TestBean.class, new MutablePropertyValues(m));
	parent.registerSingleton(StaticApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
			TestApplicationEventMulticaster.class, null);
	parent.refresh();
	parent.addApplicationListener(parentListener) ;

	parent.getStaticMessageSource().addMessage("code1", Locale.getDefault(), "message1");

	this.sac = new StaticApplicationContext(parent);
	sac.registerSingleton("beanThatListens", BeanThatListens.class, new MutablePropertyValues());
	sac.registerSingleton("aca", ACATester.class, new MutablePropertyValues());
	sac.registerPrototype("aca-prototype", ACATester.class, new MutablePropertyValues());
	PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(sac.getDefaultListableBeanFactory());
	Resource resource = new ClassPathResource("testBeans.properties", getClass());
	reader.loadBeanDefinitions(new EncodedResource(resource, "ISO-8859-1"));
	sac.refresh();
	sac.addApplicationListener(listener);

	sac.getStaticMessageSource().addMessage("code2", Locale.getDefault(), "message2");

	return sac;
}
 
Example #26
Source File: ReaderEditor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void setAsText(String text) throws IllegalArgumentException {
	this.resourceEditor.setAsText(text);
	Resource resource = (Resource) this.resourceEditor.getValue();
	try {
		setValue(resource != null ? new EncodedResource(resource).getReader() : null);
	}
	catch (IOException ex) {
		throw new IllegalArgumentException("Failed to retrieve Reader for " + resource, ex);
	}
}
 
Example #27
Source File: TransactionPropertySource.java    From ByteJTA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public TransactionPropertySource(String name, EncodedResource source) {
	super(name, source);

	EncodedResource encoded = (EncodedResource) this.getSource();
	AbstractResource resource = (AbstractResource) encoded.getResource();
	String path = resource.getFilename();

	if (StringUtils.isBlank(path)) {
		return;
	}

	String[] values = path.split(":");
	if (values.length != 2) {
		return;
	}

	String protocol = values[0];
	String resName = values[1];
	if ("bytejta".equalsIgnoreCase(protocol) == false) {
		return;
	} else if ("loadbalancer.config".equalsIgnoreCase(resName) == false) {
		return;
	}

	this.enabled = true;

}
 
Example #28
Source File: CustomPropertySourceFactoryTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Override
public org.springframework.core.env.PropertySource<?> createPropertySource(String s,
		EncodedResource encodedResource) throws IOException {

	Properties properties = new XsuaaServicesParser(vcapJsonString).parseCredentials();

	properties.put("clientid", "customClientId");
	properties.put("clientsecret", "customClientSecret");
	properties.put("uaadomain", "overwriteUaaDomain");

	return XsuaaServicePropertySourceFactory.create("custom", properties);
}
 
Example #29
Source File: ConfigurationClassParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Process the given <code>@PropertySource</code> annotation metadata.
 * @param propertySource metadata for the <code>@PropertySource</code> annotation found
 * @throws IOException if loading a property source failed
 */
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
	String name = propertySource.getString("name");
	if (!StringUtils.hasLength(name)) {
		name = null;
	}
	String encoding = propertySource.getString("encoding");
	if (!StringUtils.hasLength(encoding)) {
		encoding = null;
	}
	String[] locations = propertySource.getStringArray("value");
	Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
	boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

	Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
	PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
			DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));

	for (String location : locations) {
		try {
			String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
			Resource resource = this.resourceLoader.getResource(resolvedLocation);
			addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
		}
		catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
			// Placeholders not resolvable or resource not found when trying to open it
			if (ignoreResourceNotFound) {
				if (logger.isInfoEnabled()) {
					logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
				}
			}
			else {
				throw ex;
			}
		}
	}
}
 
Example #30
Source File: JdbcTestUtilsIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void executeSqlScriptsAndcountRowsInTableWhere() throws Exception {

	for (String script : Arrays.asList("schema.sql", "data.sql")) {
		Resource resource = new ClassPathResource(script, getClass());
		JdbcTestUtils.executeSqlScript(this.jdbcTemplate, new EncodedResource(resource), false);
	}

	assertEquals(1, JdbcTestUtils.countRowsInTableWhere(jdbcTemplate, "person", "name = 'bob'"));
}