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:org.biopax.validator.Main.java

protected static void runBatch(Validator validator, Collection<Resource> resources) throws IOException {

    //collect all reports in this object (only if --output option was used)
    final ValidatorResponse consolidatedReport = new ValidatorResponse();

    // Read from the batch and validate from file, id or url, line-by-line (stops on first empty line)
    for (Resource resource : resources) {
        Validation result = new Validation(new IdentifierImpl(), resource.getDescription(), autofix, null,
                maxErrors, profile);/*from  w ww  . j ava 2s.  c om*/
        result.setDescription(resource.getDescription());
        log.info("BioPAX DATA IMPORT FROM: " + result.getDescription());
        try {
            validator.importModel(result, resource.getInputStream());
            validator.validate(result);

            //if autofix is enabled, then do normalize too
            if (autofix) {
                Model model = (Model) result.getModel();
                Normalizer normalizer = new Normalizer();
                normalizer.setXmlBase(xmlBase); //if xmlBase is null, the model's one is used
                normalizer.normalize(model);
            }

            if (output != null)
                consolidatedReport.addValidationResult(result);

        } catch (Exception e) {
            log.error("failed", e);
        }

        final String filename = outFileName(result);
        PrintWriter writer;

        // save modified (normalized) biopax if the option was used
        if (autofix) {
            Model model = (Model) result.getModel();
            (new SimpleIOHandler()).convertToOWL(model, new FileOutputStream(filename + EXT));
        }

        // remove the BioPAX data before writing report
        result.setModel(null);
        result.setModelData(null);

        // save the individual validation results
        //unless the user specified the output file explicitly
        if (output == null || output.isEmpty()) {
            writer = new PrintWriter(filename + ".validation." + outFormat);
            Source xsltSrc = (outFormat.equalsIgnoreCase("html"))
                    ? new StreamSource(ctx.getResource("classpath:html-result.xsl").getInputStream())
                    : null;
            ValidatorUtils.write(result, writer, xsltSrc);
            writer.close();
        }

        validator.getResults().remove(result);
        log.info("Done with " + filename);
    }

    // save if the user specified the output file explicitly
    if (output != null) {
        Writer writer = new PrintWriter(output);
        Source xsltSrc = (outFormat.equalsIgnoreCase("html"))
                ? new StreamSource(ctx.getResource("classpath:html-result.xsl").getInputStream())
                : null;
        ValidatorUtils.write(consolidatedReport, writer, xsltSrc);
        writer.close();
    }
}

From source file:com.edgenius.core.util.FileUtil.java

/**
 * //  w w  w  . ja va2 s  .co  m
 * @param location
 * @return
 * @throws IOException 
 */
public static InputStream getFileInputStream(String location) throws IOException {
    //Don't user DefaultResourceLoader directly, as test it try to find host "c" if using method resource.getInputStream()
    // while location is "file://c:/var/test" etc.

    DefaultResourceLoader loader = new DefaultResourceLoader();
    Resource res = loader.getResource(location);
    if (ResourceUtils.isJarURL(res.getURL())) {
        //it is in jar file, we just assume it won't be changed in runtime, so below method is safe.
        try {
            return res.getInputStream();
        } catch (IOException e) {
            throw (e);
        }
    } else {
        //in Tomcat, the classLoader cache the input stream even using thread scope classloader, but it is still failed
        //if the reload in same thread. For example, DataRoot class save and reload in same thread when install.
        //So, we assume if the file is not inside jar file, we will always reload the file into a new InputStream from file system.

        //if it is not jar resource, then try to refresh the input stream by file system
        return new FileInputStream(res.getFile());
    }
}

From source file:com.microsoft.exchange.impl.ExchangeWebServicesClient.java

/**
 * /*from w  w  w  .java2 s. c o m*/
 * @param resource
 * @param password
 * @return
 */
protected static KeyStore getKeystoreFromResource(Resource resource, char[] password) {
    try {
        KeyStore k = KeyStore.getInstance(KeyStore.getDefaultType());
        k.load(resource.getInputStream(), password);
        return k;
    } catch (KeyStoreException e) {
        throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e);
    } catch (CertificateException e) {
        throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e);
    } catch (IOException e) {
        throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e);
    }

}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

protected static String readXMLString(Resource resource) throws IOException, ParserConfigurationException,
        SAXException, TransformerException, XPathExpressionException {
    final Document doc = parseXML(resource.getInputStream());
    byte[] data = XMLRewrite.toByteArray(doc, true);
    return new String(data);
}

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final Vaadlets unmarshal(final Reader aReader, final Resource theSchemaResource) {
    try {/*from   w  w  w .jav a 2 s .  com*/
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            unmarshaller.setSchema(schema);
        }
        return unmarshaller
                .unmarshal(XMLInputFactory.newInstance().createXMLStreamReader(aReader), Vaadlets.class)
                .getValue();
    } catch (final JAXBException | SAXException | XMLStreamException | FactoryConfigurationError
            | IOException e) {
        throw new RuntimeException("Can't unmarschal", e);
    }
}

From source file:com.themodernway.server.core.io.IO.java

public static final Stream<String> lines(final Resource resource) throws IOException {
    return IO.lines(resource.getInputStream(), true);
}

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final void marshal(final Writer aWriter, final Vaadlets vaadlets,
        final Resource theSchemaResource) {
    try {/*from  w w w  .j  a  va 2s  . c o m*/
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Marshaller marshaller = jc.createMarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            marshaller.setSchema(schema);
        }
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
                new com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper() {

                    @Override
                    public String getPreferredPrefix(final String namespaceUri, final String suggestion,
                            final boolean requirePrefix) {
                        final String subpackage = namespaceUri.replaceFirst("http://www.mymita.com/vaadlets/",
                                "");
                        if (subpackage.equals("1.0.0")) {
                            return "";
                        }
                        return Iterables.getFirst(newArrayList(Splitter.on("/").split(subpackage).iterator()),
                                "");
                    }
                });
        marshaller.marshal(
                new JAXBElement<Vaadlets>(new QName("http://www.mymita.com/vaadlets/1.0.0", "vaadlets", ""),
                        Vaadlets.class, vaadlets),
                aWriter);
    } catch (final JAXBException | SAXException | FactoryConfigurationError | IOException e) {
        throw new RuntimeException("Can't marschal", e);
    }
}

From source file:com.themodernway.server.core.io.IO.java

public static final Stream<String> lines(final Resource resource, final boolean greedy) throws IOException {
    return IO.lines(resource.getInputStream(), greedy);
}

From source file:com.themodernway.server.core.io.IO.java

public static final long copy(final Resource resource, final Writer output) throws IOException {
    try (InputStream stream = resource.getInputStream()) {
        return IO.copy(stream, output);
    }//from w ww  . j a v a 2 s .  c  om
}

From source file:com.themodernway.server.core.io.IO.java

public static final long copy(final Resource resource, final OutputStream output) throws IOException {
    try (InputStream stream = resource.getInputStream()) {
        return IO.copy(stream, output);
    }// w w  w  .  j  ava  2s .c o  m
}