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

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

Introduction

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

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream for the content of an underlying resource.

Usage

From source file:nl.flotsam.hamcrest.schema.relaxng.RelaxNGMatchers.java

/**
 * Creates a RelaxNG matcher based on a {@link Resource} object pointing to a RelaxNG schema. (XML Syntax)
 *///w w  w .ja  va  2s  .c  o m
public static TypeSafeDiagnosingMatcher<Object> isValidatedBy(Resource resource) {
    VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl();
    InputStream in = null;
    try {
        URI uri = resource.getURI();
        in = resource.getInputStream();
        if (uri == null) {
            return isValidatedBy(factory.compileSchema(in), resource.toString());
        } else {
            return isValidatedBy(factory.compileSchema(in, resource.getURI().toASCIIString()),
                    resource.getFilename());
        }
    } catch (Exception e) {
        throw new IllegalStateException("Failed to construct matcher", e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.dspace.servicemanager.spring.ResourceFinder.java

public static InputStream[] getInputStreams(List<String> paths) {
    List<Resource> rs = makeResources(paths);
    InputStream[] streams = new InputStream[rs.size()];
    for (int i = 0; i < rs.size(); i++) {
        Resource r = rs.get(i);
        try {/*from  w ww .  ja  va 2  s  . c  o  m*/
            streams[i] = r.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException("Failed to get inputstream for: " + r.getFilename(), e);
        }
    }
    return streams;
}

From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.JarUtils.java

/**
 * Dump the entries of a jar and return them as a String. This method can be
 * memory expensive depending on the jar size.
 * /*from w  ww.java 2  s  .c o  m*/
 * @param resource
 * @return
 */
public static String dumpJarContent(Resource resource) {
    try {
        return dumpJarContent(new JarInputStream(resource.getInputStream()));
    } catch (IOException ex) {
        return "reading from stream failed" + ex;
    }
}

From source file:net.unicon.cas.support.wsfederation.WsFederationUtils.java

/**
 * getSigningCredential loads up an X509Credential from a file.
 *
 * @param resource the signing certificate file
 * @return an X509 credential/*from ww w. ja v  a 2 s .  c  om*/
 */
public static X509Credential getSigningCredential(final Resource resource) {
    try (final InputStream inputStream = resource.getInputStream()) {
        //grab the certificate file
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(inputStream);

        //get the public key from the certificate
        final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
                certificate.getPublicKey().getEncoded());

        //generate public key to validate signatures
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        //add the public key
        final BasicX509Credential publicCredential = new BasicX509Credential();
        publicCredential.setPublicKey(publicKey);
        LOGGER.debug("getSigningCredential: key retrieved.");
        return publicCredential;
    } catch (final Exception ex) {
        LOGGER.error("I/O error retrieving the signing cert: {}", ex);
        return null;
    }
}

From source file:org.opennms.mock.snmp.PropsMockSnmpMOLoaderImpl.java

public static Properties loadProperties(Resource propertiesFile) {
    Properties moProps = new Properties();
    InputStream inStream = null;//from  w ww . j  a v a2s .  c om
    try {
        inStream = propertiesFile.getInputStream();
        moProps.load(inStream);
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    } finally {
        try {
            if (inStream != null)
                inStream.close();
        } catch (IOException e) {
        }
    }
    return moProps;
}

From source file:com.netflix.genie.agent.cli.UserConsole.java

/**
 * Load and print the Spring banner (if one is configured) to UserConsole.
 *
 * @param environment the Spring environment
 *///from   www .  j  ava  2s. c  o  m
static void printBanner(final Environment environment) {
    try {
        final String bannerLocation = environment.getProperty(BANNER_LOCATION_SPRING_PROPERTY_KEY);
        if (StringUtils.isNotBlank(bannerLocation)) {
            final ResourceLoader resourceLoader = new DefaultResourceLoader();
            final Resource resource = resourceLoader.getResource(bannerLocation);
            if (resource.exists()) {
                final String banner = StreamUtils.copyToString(resource.getInputStream(),
                        environment.getProperty(BANNER_CHARSET_SPRING_PROPERTY_KEY, Charset.class,
                                StandardCharsets.UTF_8));
                UserConsole.getLogger().info(banner);
            }
        }
    } catch (final Throwable t) {
        System.err.println("Failed to print banner: " + t.getMessage());
        t.printStackTrace(System.err);
    }
}

From source file:org.dspace.servicemanager.spring.ResourceFinder.java

public static InputStream getInputStream(String path) {
    Resource r = getResource(path);
    InputStream is = null;/*from w w w .j a va 2s . co  m*/
    try {
        is = r.getInputStream();
    } catch (IOException e) {
        throw new RuntimeException("Failed to get inputstream for: " + r.getFilename(), e);
    }
    return is;
}

From source file:org.openmrs.module.pihmalawi.activator.ReportInitializer.java

public static void loadSqlReports() {
    PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
    try {/*  w ww .jav a  2 s .com*/
        Resource[] resources = resourceResolver
                .getResources("classpath*:/org/openmrs/module/pihmalawi/reporting/reports/sql/*");
        if (resources != null) {
            for (Resource r : resources) {
                log.info("Loading " + r.getFilename());
                List<String> lineByLineContents = IOUtils.readLines(r.getInputStream(), "UTF-8");

                ReportDefinition rd = new ReportDefinition();
                String designUuid = null;
                StringBuilder sql = new StringBuilder();

                for (String line : lineByLineContents) {
                    if (line.startsWith("-- ##")) {
                        String[] keyValue = StringUtils.splitByWholeSeparator(line.substring(5, line.length()),
                                "=");
                        String key = keyValue[0].trim().toLowerCase();
                        String value = keyValue[1].trim();
                        if (key.equals("report_uuid")) {
                            rd.setUuid(value);
                        } else if (key.equals("report_name")) {
                            rd.setName(value);
                        } else if (key.equals("report_description")) {
                            rd.setDescription(value);
                        } else if (key.equals("parameter")) {
                            String[] paramElements = StringUtils.splitByWholeSeparator(value, "|");
                            Parameter p = new Parameter();
                            p.setName(paramElements[0]);
                            p.setLabel(paramElements[1]);
                            p.setType(Context.loadClass(paramElements[2]));
                            rd.addParameter(p);
                        } else if (key.equals("design_uuid")) {
                            designUuid = value;
                        }
                    }
                    sql.append(line).append(System.getProperty("line.separator"));
                }

                if (rd.getUuid() == null || rd.getName() == null || designUuid == null) {
                    throw new IllegalArgumentException("SQL resource" + r.getFilename()
                            + " must define a report_name, report_uuid and design_uuid at minimum");
                }

                MysqlCmdDataSetDefinition dsd = new MysqlCmdDataSetDefinition();
                dsd.setSql(sql.toString());
                dsd.setParameters(rd.getParameters());

                rd.addDataSetDefinition(r.getFilename(), Mapped.mapStraightThrough(dsd));

                List<ReportDesign> designs = new ArrayList<ReportDesign>();
                designs.add(ApzuReportUtil.createExcelDesign(designUuid, rd));

                ReportManagerUtil.setupReportDefinition(rd, designs, null);
            }
        }
    } catch (Exception e) {
        throw new IllegalStateException("Unable to load SQL reports from classpath", e);
    }
}

From source file:org.rivetlogic.utils.IntegrationUtils.java

public static BeanFactory getBeanFactory() throws IOException {
    if (beanFactory == null) {
        synchronized (beanFactoryLockObj) {
            if (beanFactory == null) {
                PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
                AbstractApplicationContext context = new ClassPathXmlApplicationContext(
                        "application-context.xml");

                Resource resource = new FileSystemResource("cma-cfg.properties");
                Properties properties = new Properties();
                properties.load(resource.getInputStream());

                configurer.setProperties(properties);

                context.addBeanFactoryPostProcessor(configurer);
                context.refresh();/*  w  ww.j ava2 s .  c  om*/

                beanFactory = context.getBeanFactory();
            }
        }
    }

    return beanFactory;
}

From source file:no.kantega.commons.util.XMLHelper.java

public static Document openDocument(Resource resource, EntityResolver er) throws InvalidFileException {
    try (InputStream is = resource.getInputStream()) {

        return openDocument(is, er, resource.getURI().getRawPath());
    } catch (IOException e) {
        throw new InvalidFileException("Error opening XML document from Resource", e);
    }/*from www .j av a  2 s .c  o  m*/
}