Example usage for org.springframework.core.io.support EncodedResource getReader

List of usage examples for org.springframework.core.io.support EncodedResource getReader

Introduction

In this page you can find the example usage for org.springframework.core.io.support EncodedResource getReader.

Prototype

public Reader getReader() throws IOException 

Source Link

Document

Open a java.io.Reader for the specified resource, using the specified #getCharset() Charset or #getEncoding() encoding (if any).

Usage

From source file:com.porvak.bracket.social.jdbc.versioned.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');
            }/*from ww  w .  j  av  a2 s .  co m*/
            scriptBuilder.append(currentStatement);
        }
        currentStatement = lnr.readLine();
    }
    return scriptBuilder.toString();
}

From source file:be.jacobsvanroy.springsqlunit.util.ScriptUtils.java

/**
 * Read a script from the provided resource, using the supplied comment prefix
 * and statement separator, and build a {@code String} containing the lines.
 * <p>Lines <em>beginning</em> with the comment prefix are excluded from the
 * results; however, line comments anywhere else &mdash; for example, within
 * a statement &mdash; will be included in the results.
 *
 * @param resource      the {@code EncodedResource} containing the script
 *                      to be processed/*  ww w.j  a va 2  s . com*/
 * @param commentPrefix the prefix that identifies comments in the SQL script &mdash;
 *                      typically "--"
 * @param separator     the statement separator in the SQL script &mdash; typically ";"
 * @return a {@code String} containing the script lines
 * @throws IOException in case of I/O errors
 */
private static String readScript(EncodedResource resource, String commentPrefix, String separator)
        throws IOException {
    LineNumberReader lnr = new LineNumberReader(resource.getReader());
    try {
        return readScript(lnr, commentPrefix, separator);
    } finally {
        lnr.close();
    }
}

From source file:com.sfxie.extension.spring4.properties.PropertiesLoaderUtils.java

/**
 * Actually load properties from the given EncodedResource into the given Properties instance.
 * @param props the Properties instance to load into
 * @param resource the resource to load from
 * @param persister the PropertiesPersister to use
 * @throws IOException in case of I/O errors
 *///from   w  w w. ja va2 s  . co  m
static void fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister)
        throws IOException {

    InputStream stream = null;
    Reader reader = null;
    try {
        String filename = resource.getResource().getFilename();
        if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
            stream = resource.getInputStream();
            persister.loadFromXml(props, stream);
        } else if (resource.requiresReader()) {
            reader = resource.getReader();
            persister.load(props, reader);
        } else {
            stream = resource.getInputStream();
            persister.load(props, stream);
        }
    } finally {
        if (stream != null) {
            stream.close();
        }
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.github.javarch.persistence.orm.test.DataBaseTestBuilder.java

private String readNextSqlScript(Resource rs) throws IOException {
    EncodedResource encoded = new EncodedResource(rs);
    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');
            }//from   w  w  w .ja v  a2  s . co m
            scriptBuilder.append(currentStatement);
        }
        currentStatement = lnr.readLine();
    }
    return scriptBuilder.toString();
}

From source file:net.noday.core.dao.AppDao.java

/**
 * sql/* w w  w . ja v  a2 s . c  om*/
 * // TODO ?????
 * @param sqlFilePath
 */
private void executeSql(String sqlFilePath) {
    if (sqlFilePath == null) {
        throw new AppStartupException("sql[" + sqlFilePath + "]?");
    }
    try {
        log.info("[" + sqlFilePath + "]");
        Resource sqlRes = new ClassPathResource(sqlFilePath);
        EncodedResource encRes = new EncodedResource(sqlRes, "UTF-8");
        String sqls = null;
        sqls = FileCopyUtils.copyToString(encRes.getReader());
        String[] sqlArr = sqls.split(";");
        log.info("");
        for (String sql : sqlArr) {
            log.info(sql);
            jdbc.execute(sql);
        }
        log.info("?");
    } catch (IOException e) {
        log.error("?[" + sqlFilePath + "]", e);
        throw new AppStartupException("?[" + sqlFilePath + "]", e);
    } catch (Exception e) {
        log.error("[" + sqlFilePath + "]", e);
        throw new AppStartupException("[" + sqlFilePath + "]", e);
    }
}

From source file:com.excilys.ebi.bank.jdbc.SimpleBatchResourceDatabasePopulator.java

/**
 * Execute the given SQL script.//  w w w .  j a va  2 s  .com
 * <p>
 * The script will normally be loaded by classpath. There should be one
 * statement per line. Any {@link #setSeparator(String) statement
 * separators} will be removed.
 * <p>
 * <b>Do not use this method to execute DDL if you expect rollback.</b>
 *
 * @param connection
 *            the JDBC Connection with which to perform JDBC operations
 * @param resource
 *            the resource (potentially associated with a specific encoding)
 *            to load the SQL script from
 * @param continueOnError
 *            whether or not to continue without throwing an exception in
 *            the event of an error
 * @param ignoreFailedDrops
 *            whether of not to continue in the event of specifically an
 *            error on a <code>DROP</code>
 */
private void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError,
        boolean ignoreFailedDrops) throws SQLException, IOException {

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Executing SQL script from " + resource);
    }

    long startTime = System.currentTimeMillis();
    Iterator<String> statements = IOUtils.lineIterator(resource.getReader());
    int lineNumber = 0;

    boolean initialAutoCommitState = connection.getAutoCommit();

    connection.setAutoCommit(false);
    Statement stmt = connection.createStatement();
    try {
        while (statements.hasNext()) {
            String statement = statements.next();
            lineNumber++;
            try {
                stmt.addBatch(statement);

                if (lineNumber % batchSize == 0) {
                    stmt.executeBatch();
                    connection.commit();
                }
            } catch (SQLException ex) {
                boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop");
                if (continueOnError || (dropStatement && ignoreFailedDrops)) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Failed to execute SQL script statement at line " + lineNumber
                                + " of resource " + resource + ": " + statement, ex);
                    }
                } else {
                    Exception nextException = ex.getNextException();
                    throw new ScriptStatementFailedException(statement, lineNumber, resource,
                            nextException != null ? nextException : ex);
                }
            }
        }
    } finally {
        stmt.executeBatch();
        connection.commit();

        connection.setAutoCommit(initialAutoCommitState);

        try {
            stmt.close();
        } catch (Throwable ex) {
            LOGGER.debug("Could not close JDBC Statement", ex);
        }
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Done executing SQL script from " + resource + " in " + elapsedTime + " ms.");
    }
}

From source file:org.axonframework.eventhandling.scheduling.quartz.QuartzTableMaker.java

private void executeSqlScript(String sqlResourcePath) throws DataAccessException {
    EncodedResource resource = new EncodedResource(applicationContext.getResource(sqlResourcePath), "UTF-8");
    List<String> statements = new LinkedList<String>();
    try {//from ww  w .  java  2s  . c  om
        LineNumberReader lnr = new LineNumberReader(resource.getReader());
        String script = JdbcTestUtils.readScript(lnr);
        char delimiter = ';';
        if (!JdbcTestUtils.containsSqlScriptDelimiters(script, delimiter)) {
            delimiter = '\n';
        }
        JdbcTestUtils.splitSqlScript(script, delimiter, statements);
        for (String statement : statements) {
            this.entityManager.createNativeQuery(statement).executeUpdate();
        }
    } catch (IOException ex) {
        throw new DataAccessResourceFailureException("Failed to open SQL script '" + sqlResourcePath + "'", ex);
    }
}

From source file:org.axonframework.spring.eventhandling.scheduling.quartz.QuartzTableMaker.java

private void executeSqlScript(String sqlResourcePath) throws DataAccessException {
    EncodedResource resource = new EncodedResource(applicationContext.getResource(sqlResourcePath), "UTF-8");
    List<String> statements = new LinkedList<>();
    try {// w  ww  . jav  a2 s .c  om
        LineNumberReader lnr = new LineNumberReader(resource.getReader());
        String script = JdbcTestUtils.readScript(lnr);
        char delimiter = ';';
        if (!JdbcTestUtils.containsSqlScriptDelimiters(script, delimiter)) {
            delimiter = '\n';
        }
        JdbcTestUtils.splitSqlScript(script, delimiter, statements);
        for (String statement : statements) {
            this.entityManager.createNativeQuery(statement).executeUpdate();
        }
    } catch (IOException ex) {
        throw new DataAccessResourceFailureException("Failed to open SQL script '" + sqlResourcePath + "'", ex);
    }
}

From source file:org.springframework.beans.factory.groovy.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
 *//*w  ww .  ja v a  2s .  c  om*/
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(getBeanClassLoader(), 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;
}

From source file:org.springframework.jdbc.datasource.init.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
 *///  w  w w .  ja  v a  2s  . c o  m
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();
    }
}