Example usage for org.springframework.core.io ClassPathResource getInputStream

List of usage examples for org.springframework.core.io ClassPathResource getInputStream

Introduction

In this page you can find the example usage for org.springframework.core.io ClassPathResource getInputStream.

Prototype

@Override
public InputStream getInputStream() throws IOException 

Source Link

Document

This implementation opens an InputStream for the given class path resource.

Usage

From source file:edu.unc.lib.dl.schematron.SchematronValidator.java

/**
 * Use this to initialize the configured schemas. Generate stylesheet
 * implementations of ISO Schematron files and preload them into Transformer
 * Templates for quick use.// w  w w. j  a  va2  s.  com
 */
public void loadSchemas() {
    templates = new HashMap<String, Templates>();
    // Load up a transformer and the ISO Schematron to XSL templates.
    Templates isoSVRLTemplates = null;
    ClassPathResource svrlRes = new ClassPathResource("/edu/unc/lib/dl/schematron/iso_svrl.xsl",
            SchematronValidator.class);
    Source svrlrc;
    try {
        svrlrc = new StreamSource(svrlRes.getInputStream());
    } catch (IOException e1) {
        throw new Error("Cannot load iso_svrl.xsl", e1);
    }
    TransformerFactory factory = null;
    try {
        factory = new TransformerFactoryImpl();
        // enable relative classpath-based URIs
        factory.setURIResolver(new URIResolver() {
            public Source resolve(String href, String base) throws TransformerException {
                ClassPathResource svrlRes = new ClassPathResource(href, SchematronValidator.class);
                Source result;
                try {
                    result = new StreamSource(svrlRes.getInputStream());
                } catch (IOException e1) {
                    throw new TransformerException("Cannot resolve " + href, e1);
                }
                return result;
            }
        });
        isoSVRLTemplates = factory.newTemplates(svrlrc);
    } catch (TransformerFactoryConfigurationError e) {
        log.error("Error setting up transformer factory.", e);
        throw new Error("Error setting up transformer factory", e);
    } catch (TransformerConfigurationException e) {
        log.error("Error setting up transformer.", e);
        throw new Error("Error setting up transformer", e);
    }

    // Get a transformer
    Transformer t = null;
    try {
        t = isoSVRLTemplates.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new Error("There was a problem configuring the transformer.", e);
    }

    for (String schema : schemas.keySet()) {
        // make XSLT out of Schematron for each schema
        Resource resource = schemas.get(schema);
        Source schematron = null;
        try {
            schematron = new StreamSource(resource.getInputStream());
        } catch (IOException e) {
            throw new Error("Cannot load resource for schema \"" + schema + "\" at " + resource.getDescription()
                    + resource.toString());
        }
        JDOMResult res = new JDOMResult();
        try {
            t.transform(schematron, res);
        } catch (TransformerException e) {
            throw new Error("Schematron issue: There were problems transforming Schematron to XSL.", e);
        }

        // compile templates object for each profile
        try {
            Templates schemaTemplates = factory.newTemplates(new JDOMSource(res.getDocument()));
            templates.put(schema, schemaTemplates);
        } catch (TransformerConfigurationException e) {
            throw new Error("There was a problem configuring the transformer.", e);
        }
    }

}

From source file:org.sakaiproject.sitestats.impl.DBHelper.java

public void preloadDefaultReports() {
    HibernateCallback hcb = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Connection c = null;/*from   ww w. j  a  v  a 2s  . c om*/
            InputStreamReader isr = null;
            BufferedReader br = null;
            try {
                ClassPathResource defaultReports = new ClassPathResource(dbVendor + "/default_reports.sql");
                LOG.info("init(): - preloading sitestats default reports");
                isr = new InputStreamReader(defaultReports.getInputStream());
                br = new BufferedReader(isr);

                c = session.connection();
                String sqlLine = null;
                while ((sqlLine = br.readLine()) != null) {
                    sqlLine = sqlLine.trim();
                    if (!sqlLine.equals("") && !sqlLine.startsWith("--")) {
                        if (sqlLine.endsWith(";")) {
                            sqlLine = sqlLine.substring(0, sqlLine.indexOf(";"));
                        }
                        Statement st = null;
                        try {
                            st = c.createStatement();
                            st.execute(sqlLine);
                        } catch (SQLException e) {
                            if (!"23000".equals(e.getSQLState())) {
                                LOG.warn("Failed to preload default report: " + sqlLine, e);
                            }
                        } catch (Exception e) {
                            LOG.warn("Failed to preload default report: " + sqlLine, e);
                        } finally {
                            if (st != null)
                                st.close();
                        }
                    }
                }

            } catch (HibernateException e) {
                LOG.error("Error while preloading default reports", e);
            } catch (Exception e) {
                LOG.error("Error while preloading default reports", e);
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                    }
                }
                if (isr != null) {
                    try {
                        isr.close();
                    } catch (IOException e) {
                    }
                }
                if (c != null) {
                    c.close();
                }
            }
            return null;
        }
    };
    getHibernateTemplate().execute(hcb);
}

From source file:org.alfresco.textgen.TextGenerator.java

public TextGenerator(String configPath) {
    ClassPathResource cpr = new ClassPathResource(configPath);
    if (!cpr.exists()) {
        throw new RuntimeException("No resource found: " + configPath);
    }//from   w  w  w.  j ava  2s  .  c  o  m
    InputStream is = null;
    InputStreamReader r = null;
    BufferedReader br = null;
    try {
        int lineNumber = 0;
        is = cpr.getInputStream();
        r = new InputStreamReader(is, "UTF-8");
        br = new BufferedReader(r);

        String line;
        while ((line = br.readLine()) != null) {
            lineNumber++;
            if (lineNumber == 1) {
                // skip header
                continue;
            }
            String[] split = line.split("\t");

            if (split.length != 7) {
                //System.out.println("Skipping "+lineNumber);
                continue;
            }

            String word = split[1].replaceAll("\\*", "");
            String mode = split[3].replaceAll("\\*", "");
            long frequency = Long.parseLong(split[4].replaceAll("#", "").trim());

            // Single varient
            if (mode.equals(":")) {
                if (!ignore(word)) {
                    wordGenerator.addWord(splitAlternates(word), frequency == 0 ? 1 : frequency);
                }
            } else {
                if (word.equals("@")) {
                    // varient
                    if (!ignore(mode)) {
                        wordGenerator.addWord(splitAlternates(mode), frequency == 0 ? 1 : frequency);
                    }
                } else {
                    //System.out.println("Skipping totla and using varients for " + word + " @ " + lineNumber);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to load resource " + configPath);
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (Exception e) {
            }
        }
        if (r != null) {
            try {
                r.close();
            } catch (Exception e) {
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.gvmax.web.api.WebAppAPI.java

private void loadThirdParty() throws IOException {
    ClassPathResource res = new ClassPathResource("thirdparty.properties");
    InputStream in = res.getInputStream();
    try {//from  w  w  w  .ja  va2s. co  m
        thirdParties.load(in);
    } finally {
        IOUtil.close(in);
    }
    for (Entry<Object, Object> entry : thirdParties.entrySet()) {
        logger.info("Thirdparty: " + entry.getValue() + " registered.");
    }
}

From source file:com.turbospaces.api.AbstractSpaceConfiguration.java

/**
 * 1. initialize jchannel/*  w w  w.java  2 s .  co  m*/
 * 2. initialize conversion service
 * 3. initialize mapping context
 * 4. initialize kryo
 */
@Override
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
    logger.info("Initializing JSpace configuration: group = {}", getGroup());

    if (getJChannel() == null) {
        ClassPathResource largeClusterCfg = new ClassPathResource("turbospaces-jgroups-udp.xml");
        InputStream inputStream = largeClusterCfg.getInputStream();
        setjChannel(new JChannel(inputStream));
        inputStream.close();
    }
    getJChannel().setDiscardOwnMessages(true);

    if (getMemoryManager() == null)
        setMemoryManager(new UnsafeMemoryManager());
    if (getMappingContext() == null)
        if (applicationContext != null)
            setMappingContext(applicationContext.getBean(AbstractMappingContext.class));

    if (getListeningExecutorService() == null)
        setExecutorService(Executors.newFixedThreadPool(1 << 6, new ThreadFactoryBuilder().setDaemon(false)
                .setNameFormat("jspace-execpool-thread-%s").build()));
    if (getScheduledExecutorService() == null)
        setScheduledExecutorService(Executors.newScheduledThreadPool(1 << 2, new ThreadFactoryBuilder()
                .setDaemon(true).setNameFormat("jspace-scheduledpool-thread-%s").build()));

    Preconditions.checkState(mappingContext != null, MAPPING_CONTEXT_IS_NOT_REGISTERED);

    Collection<BasicPersistentEntity> persistentEntities = mappingContext.getPersistentEntities();
    for (BasicPersistentEntity e : persistentEntities)
        boFor(e.getType());

    if (kryo == null)
        kryo = new DecoratedKryo();
    SpaceUtility.registerSpaceClasses(this, kryo);
}

From source file:org.intalio.deploy.deployment.impl.ClusteredDeployServiceDeployTest.java

public void setUp() throws Exception {
    PropertyConfigurator.configure(new File(TestUtils.getTestBase(), "log4j.properties").getAbsolutePath());
    Utils.deleteRecursively(_deployDir);

    XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("clustered-test.xml"));
    cluster = (ClusterProxy) factory.getBean("cluster");
    cluster.startUpProcesses();//from www  .ja va 2s . com
    Thread.sleep(6000);

    cluster.setNodes((List<ClusteredNode>) factory.getBean("nodes"));

    // setup database
    DataSource ds = cluster.getDataSource();

    ClassPathResource script = new ClassPathResource("deploy.derby.sql");
    if (script == null)
        throw new IOException("Unable to find file: deploy.derby.sql");
    SQLScript sql = new SQLScript(script.getInputStream(), ds);
    sql.setIgnoreErrors(true);
    sql.setInteractive(false);
    sql.executeScript();

    Connection c = ds.getConnection();
    EasyStatement.execute(c, "DELETE FROM DEPLOY_RESOURCES");
    EasyStatement.execute(c, "DELETE FROM DEPLOY_COMPONENTS");
    EasyStatement.execute(c, "DELETE FROM DEPLOY_ASSEMBLIES");
    c.close();
}

From source file:org.flywaydb.test.dbunit.DBUnitTestExecutionListener.java

/**
 * Implementation of loadFiles//  w  ww  .j a  v a 2  s. c om
 *
 * @param testContext
 * @param dbUnitAnnotation
 * @throws Exception
 */
private void loadFiles(final TestContext testContext, final DBUnitSupport dbUnitAnnotation) throws Exception {
    final String[] loadFiles = dbUnitAnnotation.loadFilesForRun();

    if (loadFiles != null && loadFiles.length > 0) {
        // we have some files to load
        String executionInfo = ExecutionListenerHelper.getExecutionInformation(testContext);

        if (logger.isDebugEnabled()) {
            logger.debug("******** Load files  '" + executionInfo + "'.");

        }

        for (int i = 0; i < loadFiles.length; i += 2) {
            final String operationName = loadFiles[i];
            final String fileResource = loadFiles[i + 1];

            if (logger.isDebugEnabled()) {
                logger.debug("******** load file '" + executionInfo + "' op='" + operationName + "' - '"
                        + fileResource + "'.");
            }

            final DatabaseOperation operation = getOperation(operationName);

            final ClassPathResource resource = new ClassPathResource(fileResource);

            final InputStream is = resource.getInputStream();

            try {

                // now we try to load the data into database
                final DataSource ds = getSaveDataSource(testContext);

                final IDatabaseConnection con = getConnection(ds, testContext);
                // Issue 16 fix leaking database connection - will look better with Java 7 Closable
                try {
                    final FlatXmlDataSet dataSet = getFileDataSet(is);
                    operation.execute(con, dataSet);
                } finally {
                    if (logger.isDebugEnabled()) {
                        logger.debug("******** Close database connection " + con);
                    }
                    con.close();
                }
            } finally {
                if (is != null) {
                    // avoid memory leak in streams
                    is.close();
                }
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("******** Finished load files '" + executionInfo + "'.");

        }
    }
}

From source file:org.intalio.deploy.deployment.impl.DeployServiceDeployTest.java

public void setUp() throws Exception {
    PropertyConfigurator.configure(new File(TestUtils.getTestBase(), "log4j.properties").getAbsolutePath());

    Utils.deleteRecursively(_deployDir);

    manager = new MockComponentManager("MockEngine");

    service = loadDeploymentService("test1.xml");
    service.setDeployDirectory(_deployDir.getAbsolutePath());
    service.init();//from   w  ww.  j av a 2s  . c o  m

    DataSource ds = service.getDataSource();

    ClassPathResource script = new ClassPathResource("deploy.derby.sql");
    if (script == null)
        throw new IOException("Unable to find file: deploy.derby.sql");
    SQLScript sql = new SQLScript(script.getInputStream(), ds);
    sql.setIgnoreErrors(true);
    sql.setInteractive(false);
    sql.executeScript();

    Connection c = ds.getConnection();
    EasyStatement.execute(c, "DELETE FROM DEPLOY_RESOURCES");
    EasyStatement.execute(c, "DELETE FROM DEPLOY_COMPONENTS");
    EasyStatement.execute(c, "DELETE FROM DEPLOY_ASSEMBLIES");
    c.close();
}