下面列出了org.springframework.beans.factory.parsing.Location#org.springframework.core.io.support.EncodedResource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 通过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);
}
}
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);
}
}
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;
}
@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;
}
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;
}
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;
}
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;
}
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);
}
}
/**
* 通过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);
}
}
@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);
}
}
}
@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");
}
}
/**
* {@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);
}
}
@Test
public void testRefToSingleton() {
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);
}
/**
* {@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);
}
}
/**
* {@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, vars);
}
}
@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);
}
}
@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);
}
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (name == null) {
name = String.format("%[email protected]%s", CompensablePropertySource.class, System.identityHashCode(resource));
} // end-if (name == null)
return new CompensablePropertySource(name, resource);
}
@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);
}
}
/**
* 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();
}
}
}
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));
}
}
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;
}
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;
}
/**
* 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;
}
}
}
}
@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'"));
}
@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);
}
@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);
}
@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);
}
}
@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;
}
/**
* 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;
}