Java 类org.springframework.core.io.support.EncodedResource 实例源码

项目:xproject    文件:GlobalPropertySources.java   
protected void loadProperties(Properties props) throws IOException {
    if (this.locations != null) {
        for (Resource location : this.locations) {
            logger.info("Loading properties file from " + location);
            try {
                PropertiesLoaderUtils.fillProperties(props,
                        new EncodedResource(location, this.fileEncoding));
            } catch (IOException ex) {
                if (this.ignoreResourceNotFound) {
                    logger.warn("Could not load properties from " + location + ": " + ex.getMessage());
                } else {
                    throw ex;
                }
            }
        }
    }
}
项目:lams    文件:PropertiesBeanDefinitionReader.java   
/**
 * Load bean definitions from the specified properties file.
 * @param encodedResource the resource descriptor for the properties file,
 * allowing to specify an encoding to use for parsing the file
 * @param prefix a filter within the keys in the map: e.g. 'beans.'
 * (can be empty or {@code null})
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource, String prefix)
        throws BeanDefinitionStoreException {

    Properties props = new Properties();
    try {
        InputStream is = encodedResource.getResource().getInputStream();
        try {
            if (encodedResource.getEncoding() != null) {
                getPropertiesPersister().load(props, new InputStreamReader(is, encodedResource.getEncoding()));
            }
            else {
                getPropertiesPersister().load(props, is);
            }
        }
        finally {
            is.close();
        }
        return registerBeanDefinitions(props, prefix, encodedResource.getResource().getDescription());
    }
    catch (IOException ex) {
        throw new BeanDefinitionStoreException("Could not parse properties from " + encodedResource.getResource(), ex);
    }
}
项目:plugin-bt-jira    文件:JiraExportPluginResourceTest.java   
/**
 * Initialize data base with 'MDA' JIRA project.
 */
@BeforeClass
public static void initializeJiraDataBaseForSla() throws SQLException {
    final DataSource datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null);
    final Connection connection = datasource.getConnection();
    try {
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/sla/jira-create.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/sla/jira.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:plugin-bt-jira    文件:AbstractJiraTest.java   
/**
 * Initialize data base with 'MDA' JIRA project.
 */
@BeforeClass
public static void initializeJiraDataBase() throws SQLException {
    datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null);
    final Connection connection = datasource.getConnection();
    final JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
    try {
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/base-1/jira-create.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/base-1/jira.sql"), StandardCharsets.UTF_8));
        jdbcTemplate.queryForList("SELECT * FROM pluginversion WHERE ID = 10075");
    } finally {
        connection.close();
    }
}
项目:plugin-bt-jira    文件:JiraUpdateDaoTest.java   
/**
 * Initialize data base with 'MDA' JIRA project.
 */
@BeforeClass
public static void initializeJiraDataBaseForImport() throws SQLException {
    datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null);
    final Connection connection = datasource.getConnection();
    try {
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/base-1/jira-create.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/base-2/jira-create.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/upload/jira-create.sql"), StandardCharsets.UTF_8));

        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-1/jira.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:lodsve-framework    文件:ResourceBundleHolder.java   
private Properties getPropertiesFromFile(String baseName, Resource resource) {
    Properties properties = new Properties();

    String fileType = FileUtils.getFileExt(resource.getFilename());

    try {
        if (SUFFIX_OF_PROPERTIES.equals(fileType)) {
            //1.properties
            PropertiesLoaderUtils.fillProperties(properties, new EncodedResource(resource, "UTF-8"));
        } else if (SUFFIX_OF_TEXT.equals(fileType) || SUFFIX_OF_HTML.equals(fileType)) {
            //2.txt/html
            properties.put(baseName, ResourceUtils.getContent(resource));
        } else {
            //do nothing!
            logger.debug("this file '{}' is not properties, txt, html!", resource);
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return null;
    }

    return properties;
}
项目:lodsve-framework    文件:ParamsHome.java   
private static void initExtResources() {
    String filePath = System.getProperty(EXT_PARAMS_FILE_NAME);
    if (StringUtils.isBlank(filePath)) {
        return;
    }

    System.out.println(String.format("获取到%s路径为'{%s}'!", EXT_PARAMS_FILE_NAME, filePath));

    Resource resource = new FileSystemResource(filePath);
    if (!resource.exists()) {
        System.err.println(String.format("找不到外部文件'[%s]'!", filePath));
        return;
    }

    try {
        PropertiesLoaderUtils.fillProperties(EXT_PARAMS_PROPERTIES, new EncodedResource(resource, "UTF-8"));
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println(String.format("读取路径为'%s'的文件失败!失败原因是'%s'!", filePath, e.getMessage()));
    }
}
项目:spring4-understanding    文件:ApplicationContextExpressionTests.java   
@Test
public void resourceInjection() throws IOException {
    System.setProperty("logfile", "log4j.properties");
    try {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ResourceInjectionBean.class);
        ResourceInjectionBean resourceInjectionBean = ac.getBean(ResourceInjectionBean.class);
        Resource resource = new ClassPathResource("log4j.properties");
        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");
    }
}
项目:spring4-understanding    文件:PropertiesBeanDefinitionReader.java   
/**
 * Load bean definitions from the specified properties file.
 * @param encodedResource the resource descriptor for the properties file,
 * allowing to specify an encoding to use for parsing the file
 * @param prefix a filter within the keys in the map: e.g. 'beans.'
 * (can be empty or {@code null})
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource, String prefix)
        throws BeanDefinitionStoreException {

    Properties props = new Properties();
    try {
        InputStream is = encodedResource.getResource().getInputStream();
        try {
            if (encodedResource.getEncoding() != null) {
                getPropertiesPersister().load(props, new InputStreamReader(is, encodedResource.getEncoding()));
            }
            else {
                getPropertiesPersister().load(props, is);
            }
        }
        finally {
            is.close();
        }
        return registerBeanDefinitions(props, prefix, encodedResource.getResource().getDescription());
    }
    catch (IOException ex) {
        throw new BeanDefinitionStoreException("Could not parse properties from " + encodedResource.getResource(), ex);
    }
}
项目:sosoapi-base    文件:PropertiesUtils.java   
/**
 * 获取指定的资源对象
 * @param propertiesFilePath
 * @return
 */
public static Properties getProperties(String propertiesFilePath){
    Properties properties = null;
    try {
        logger.info("加载资源[" + propertiesFilePath + "] ...");

        properties = PropertiesLoaderUtils.loadProperties(new EncodedResource(new ClassPathResource(propertiesFilePath), "UTF-8"));
    } 
    catch (IOException e) {
        logger.error("加载资源[" + propertiesFilePath + "]失败");
        logger.error(e.getMessage());

        e.printStackTrace();
    }

    return properties;
}
项目:sosoapi-base    文件:ErrorCodePropertyConfigurer.java   
protected void build() {
    for (Resource location : this.locations) {
        if (location == null) {
            continue;
        }
        try {
            Properties prop = PropertiesLoaderUtils.loadProperties(new EncodedResource(location,"UTF-8"));
            for (Entry<Object, Object> entry : prop.entrySet()) {
                ErrorCodeTool.setProperty(entry.getKey().toString(), entry.getValue().toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
项目:class-guard    文件:ResourceDatabasePopulator.java   
/**
 * Read a script from the given resource and build a String containing the lines.
 * @param resource the resource to be read
 * @return {@code String} containing the script lines
 * @throws IOException in case of I/O errors
 */
private String readScript(EncodedResource resource) throws IOException {
    LineNumberReader lnr = new LineNumberReader(resource.getReader());
    try {
        String currentStatement = lnr.readLine();
        StringBuilder scriptBuilder = new StringBuilder();
        while (currentStatement != null) {
            if (StringUtils.hasText(currentStatement) &&
                    (this.commentPrefix != null && !currentStatement.startsWith(this.commentPrefix))) {
                if (scriptBuilder.length() > 0) {
                    scriptBuilder.append('\n');
                }
                scriptBuilder.append(currentStatement);
            }
            currentStatement = lnr.readLine();
        }
        maybeAddSeparatorToScript(scriptBuilder);
        return scriptBuilder.toString();
    }
    finally {
        lnr.close();
    }
}
项目:class-guard    文件:JdbcTestUtilsTests.java   
@Test
public void readAndSplitScriptContainingComments() throws Exception {

    EncodedResource resource = new EncodedResource(new ClassPathResource("test-data-with-comments.sql", getClass()));
    LineNumberReader lineNumberReader = new LineNumberReader(resource.getReader());

    String script = JdbcTestUtils.readScript(lineNumberReader);

    char delim = ';';
    List<String> statements = new ArrayList<String>();
    JdbcTestUtils.splitSqlScript(script, delim, statements);

    String statement1 = "insert into customer (id, name) values (1, 'Rod; Johnson'), (2, 'Adrian Collier')";
    String statement2 = "insert into orders(id, order_date, customer_id) values (1, '2008-01-02', 2)";
    String statement3 = "insert into orders(id, order_date, customer_id) values (1, '2008-01-02', 2)";
    // Statement 4 addresses the error described in SPR-9982.
    String statement4 = "INSERT INTO persons( person_id , name) VALUES( 1 , 'Name' )";

    assertEquals("wrong number of statements", 4, statements.size());
    assertEquals("statement 1 not split correctly", statement1, statements.get(0));
    assertEquals("statement 2 not split correctly", statement2, statements.get(1));
    assertEquals("statement 3 not split correctly", statement3, statements.get(2));
    assertEquals("statement 4 not split correctly", statement4, statements.get(3));
}
项目:class-guard    文件:PropertiesBeanDefinitionReader.java   
/**
 * Load bean definitions from the specified properties file.
 * @param encodedResource the resource descriptor for the properties file,
 * allowing to specify an encoding to use for parsing the file
 * @param prefix a filter within the keys in the map: e.g. 'beans.'
 * (can be empty or {@code null})
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource, String prefix)
        throws BeanDefinitionStoreException {

    Properties props = new Properties();
    try {
        InputStream is = encodedResource.getResource().getInputStream();
        try {
            if (encodedResource.getEncoding() != null) {
                getPropertiesPersister().load(props, new InputStreamReader(is, encodedResource.getEncoding()));
            }
            else {
                getPropertiesPersister().load(props, is);
            }
        }
        finally {
            is.close();
        }
        return registerBeanDefinitions(props, prefix, encodedResource.getResource().getDescription());
    }
    catch (IOException ex) {
        throw new BeanDefinitionStoreException("Could not parse properties from " + encodedResource.getResource(), ex);
    }
}
项目:alf.io    文件:SmtpMailer.java   
private JavaMailSender toMailSender(Event event) {
    JavaMailSenderImpl r = new CustomJavaMailSenderImpl();
    r.setDefaultEncoding("UTF-8");

    r.setHost(configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_HOST)));
    r.setPort(Integer.valueOf(configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_PORT))));
    r.setProtocol(configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_PROTOCOL)));
    r.setUsername(configurationManager.getStringConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_USERNAME), null));
    r.setPassword(configurationManager.getStringConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_PASSWORD), null));

    String properties = configurationManager.getStringConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_PROPERTIES), 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;
}
项目:spring-greenhouse-clickstart    文件:SqlDatabaseChange.java   
private static String readScript(Resource resource) throws IOException {
    EncodedResource encoded = resource instanceof EncodedResource ? (EncodedResource) resource : new EncodedResource(resource);
    LineNumberReader lnr = new LineNumberReader(encoded.getReader());
    String currentStatement = lnr.readLine();
    StringBuilder scriptBuilder = new StringBuilder();
    while (currentStatement != null) {
        if (StringUtils.hasText(currentStatement) && (SQL_COMMENT_PREFIX != null && !currentStatement.startsWith(SQL_COMMENT_PREFIX))) {
            if (scriptBuilder.length() > 0) {
                scriptBuilder.append('\n');
            }
            scriptBuilder.append(currentStatement);
        }
        currentStatement = lnr.readLine();
    }
    return scriptBuilder.toString();
}
项目:lams    文件:XmlBeanDefinitionReader.java   
/**
 * 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();
        }
    }
}
项目:lams    文件:GroovyBeanDefinitionReader.java   
/**
 * 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;
}
项目:stage-job    文件:PropertiesUtil.java   
public static String getString(String key) {
    Properties prop = null;
    try {
        Resource resource = new ClassPathResource(file_name);
        EncodedResource encodedResource = new EncodedResource(resource,"UTF-8");
        prop = PropertiesLoaderUtils.loadProperties(encodedResource);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    if (prop!=null) {
        return prop.getProperty(key);
    }
    return null;
}
项目:xxl-job    文件:PropertiesUtil.java   
public static String getString(String key) {
    Properties prop = null;
    try {
        Resource resource = new ClassPathResource(file_name);
        EncodedResource encodedResource = new EncodedResource(resource,"UTF-8");
        prop = PropertiesLoaderUtils.loadProperties(encodedResource);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    if (prop!=null) {
        return prop.getProperty(key);
    }
    return null;
}
项目:plugin-bt-jira    文件:JiraExportPluginResourceTest.java   
/**
 * Clean data base with 'MDA' JIRA project.
 */
@AfterClass
public static void cleanJiraDataBaseForSla() throws SQLException {
    final DataSource datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null);
    final Connection connection = datasource.getConnection();

    try {
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/sla/jira-drop.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:plugin-bt-jira    文件:AbstractJiraTest.java   
/**
 * Clean data base with 'MDA' JIRA project.
 */
@AfterClass
public static void cleanJiraDataBase() throws SQLException {
    final Connection connection = datasource.getConnection();

    try {
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/base-1/jira-drop.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:plugin-bt-jira    文件:AbstractJiraUploadTest.java   
/**
 * Initialize data base with 'MDA' JIRA project.
 */
@BeforeClass
public static void initializeJiraDataBaseForImport() throws SQLException {
    final DataSource datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null);
    final Connection connection = datasource.getConnection();
    try {
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/upload/jira-create.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:plugin-bt-jira    文件:AbstractJiraUploadTest.java   
/**
 * Clean data base with 'MDA' JIRA project.
 */
@AfterClass
public static void cleanJiraDataBaseForImport() throws SQLException {
    final DataSource datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null);
    final Connection connection = datasource.getConnection();

    try {
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira-drop.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:plugin-bt-jira    文件:AbstractJiraData3Test.java   
/**
 * Initialize data base with 'MDA' JIRA project.
 */
@BeforeClass
public static void initializeJiraDataBase3() throws SQLException {
    final Connection connection = datasource.getConnection();
    try {
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/base-3/jira-create.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-3/jira.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:plugin-bt-jira    文件:AbstractJiraData3Test.java   
/**
 * Clean data base with 'MDA' JIRA project.
 */
@AfterClass
public static void cleanJiraDataBase3() throws SQLException {
    final Connection connection = datasource.getConnection();

    try {
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-3/jira-drop.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:plugin-bt-jira    文件:JiraUpdateDaoTest.java   
/**
 * Clean data base with 'MDA' JIRA project.
 */
@AfterClass
public static void cleanJiraDataBaseForImport() throws SQLException {
    final Connection connection = datasource.getConnection();

    try {
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-1/jira-drop.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira-drop.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira-drop.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:plugin-bt-jira    文件:AbstractJiraDataTest.java   
/**
 * Initialize data base with 'MDA' JIRA project.
 */
@BeforeClass
public static void initializeJiraDataBase2() throws SQLException {
    final Connection connection = datasource.getConnection();
    try {
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/base-2/jira-create.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:plugin-bt-jira    文件:AbstractJiraDataTest.java   
/**
 * Clean data base with 'MDA' JIRA project.
 */
@AfterClass
public static void cleanJiraDataBase2() throws SQLException {
    final Connection connection = datasource.getConnection();

    try {
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira-drop.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:lodsve-framework    文件:EnvLoader.java   
private static void loadProperties(Properties prop, List<Resource> resources) {
    for (Resource resource : resources) {
        try {
            PropertiesLoaderUtils.fillProperties(prop, new EncodedResource(resource, "UTF-8"));
        } catch (IOException e) {
            throw new RuntimeException("load配置文件发生异常");
        }
    }
}
项目:lodsve-framework    文件:PropertiesConfigurationFactory.java   
private Properties loadProp(String... configLocations) {
    Properties prop = new Properties();
    prop.putAll(Env.getSystemEnvs());
    prop.putAll(Env.getEnvs());

    if (ArrayUtils.isEmpty(configLocations)) {
        ParamsHome.getInstance().coveredWithExtResource(prop);
        return prop;
    }


    for (String location : configLocations) {
        location = PropertyPlaceholderHelper.replacePlaceholder(location, true, Env.getEnvs());

        Resource resource = ResourceUtils.getResource(location);
        if (!resource.exists()) {
            continue;
        }

        try {
            PropertiesLoaderUtils.fillProperties(prop, new EncodedResource(resource, "UTF-8"));
        } catch (IOException e) {
            if (logger.isErrorEnabled()) {
                logger.error(String.format("fill properties with file '%s' error!", resource.getFilename()));
            }
        }
    }

    // 获取覆盖的值
    ParamsHome.getInstance().coveredWithExtResource(prop);
    return prop;
}
项目:lodsve-framework    文件:ParamsHome.java   
private boolean isDevMode() {
    String filePath = PARAMS_ROOT + File.separator + "framework" + File.separator + "application.properties";
    Resource resource = new FileSystemResource(filePath);
    if (!resource.exists()) {
        return false;
    }

    Properties prop = new Properties();
    try {
        PropertiesLoaderUtils.fillProperties(prop, new EncodedResource(resource, "UTF-8"));
        return Boolean.valueOf(prop.getProperty("application.devMode"));
    } catch (IOException e) {
        return false;
    }
}
项目:spring4-understanding    文件:StaticApplicationContextMulticasterTests.java   
@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;
}
项目:spring4-understanding    文件:XmlBeanFactoryTests.java   
@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);
}
项目:spring4-understanding    文件:GroovyBeanDefinitionReader.java   
/**
 * Load bean definitions from the specified Groovy script or XML file.
 * <p>Note that {@code ".xml"} files will be parsed as XML content; all other kinds
 * of resources will be parsed as Groovy scripts.
 * @param encodedResource the resource descriptor for the Groovy script or XML file,
 * allowing specification of 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 {
    // Check for XML files and redirect them to the "standard" XmlBeanDefinitionReader
    String filename = encodedResource.getResource().getFilename();
    if (StringUtils.endsWithIgnoreCase(filename, ".xml")) {
        return this.standardXmlBeanDefinitionReader.loadBeanDefinitions(encodedResource);
    }

    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(), "beans");
    }
    catch (Throwable ex) {
        throw new BeanDefinitionParsingException(new Problem("Error evaluating Groovy script: " + ex.getMessage(),
                new Location(encodedResource.getResource()), null, ex));
    }
    return getRegistry().getBeanDefinitionCount() - countBefore;
}
项目:spring4-understanding    文件:JdbcTestUtilsIntegrationTests.java   
@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'"));
}
项目:spring4-understanding    文件:ReaderEditor.java   
@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);
    }
}
项目:spring4-understanding    文件:XmlBeanDefinitionReader.java   
/**
 * 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();
        }
    }
}
项目:xxl-incubator    文件:PropertiesUtil.java   
/**
 * 加载Prop
 *
 * @param propertyFileName
 * @return
 */
public static Properties loadProperties2(String propertyFileName) {
    Properties prop = null;
    try {
        Resource resource = new ClassPathResource(propertyFileName);
        EncodedResource encodedResource = new EncodedResource(resource,"UTF-8");
        prop = PropertiesLoaderUtils.loadProperties(encodedResource);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return prop;
}
项目:spring    文件:ReaderEditor.java   
@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);
    }
}