Example usage for javax.xml.transform.stream StreamSource getInputStream

List of usage examples for javax.xml.transform.stream StreamSource getInputStream

Introduction

In this page you can find the example usage for javax.xml.transform.stream StreamSource getInputStream.

Prototype

public InputStream getInputStream() 

Source Link

Document

Get the byte stream that was set with setByteStream.

Usage

From source file:org.dita.dost.util.XMLUtils.java

/** Close source. */
public static void close(final Source input) throws IOException {
    if (input != null && input instanceof StreamSource) {
        final StreamSource s = (StreamSource) input;
        final InputStream i = s.getInputStream();
        if (i != null) {
            i.close();/*w w w  . j a v a  2  s  . c  om*/
        } else {
            final Reader w = s.getReader();
            if (w != null) {
                w.close();
            }
        }
    }
}

From source file:org.geoserver.rest.util.IOUtils.java

/**
 * Convert the input from the provided {@link Reader} into a {@link String}.
 * //w ww  .j  a v a  2  s .  c  o  m
 * @param inputStream the {@link Reader} to copy from.
 * @return a {@link String} that contains the content of the provided {@link Reader}.
 * @throws IOException in case something bad happens.
 */
public static String getStringFromStreamSource(StreamSource src) throws IOException {

    inputNotNull(src);
    InputStream inputStream = src.getInputStream();
    if (inputStream != null) {
        return getStringFromStream(inputStream);
    } else {

        final Reader r = src.getReader();
        return getStringFromReader(r);
    }
}

From source file:org.jboss.bpm.console.server.util.DOMUtils.java

public static Element sourceToElement(Source source) throws IOException {
    Element retElement = null;//from ww  w.  j a v  a2 s  .com

    try {
        if (source instanceof StreamSource) {
            StreamSource streamSource = (StreamSource) source;

            InputStream ins = streamSource.getInputStream();
            if (ins != null) {
                retElement = DOMUtils.parse(ins);
            } else {
                Reader reader = streamSource.getReader();
                retElement = DOMUtils.parse(new InputSource(reader));
            }
        } else if (source instanceof DOMSource) {
            DOMSource domSource = (DOMSource) source;
            Node node = domSource.getNode();
            if (node instanceof Element) {
                retElement = (Element) node;
            } else if (node instanceof Document) {
                retElement = ((Document) node).getDocumentElement();
            } else {
                throw new RuntimeException("Unsupported Node type: " + node.getClass().getName());
            }
        } else if (source instanceof SAXSource) {
            // The fact that JAXBSource derives from SAXSource is an implementation detail.
            // Thus in general applications are strongly discouraged from accessing methods defined on SAXSource.
            // The XMLReader object obtained by the getXMLReader method shall be used only for parsing the InputSource object returned by the getInputSource method.

            TransformerFactory tf = TransformerFactory.newInstance();
            ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.transform(source, new StreamResult(baos));
            retElement = DOMUtils.parse(new ByteArrayInputStream(baos.toByteArray()));
        } else {
            throw new RuntimeException("Source type not implemented: " + source.getClass().getName());
        }

    } catch (TransformerException ex) {
        IOException ioex = new IOException();
        ioex.initCause(ex);
        throw ioex;
    }

    return retElement;
}

From source file:org.kuali.coeus.common.impl.print.PrintingServiceImpl.java

/**
 * This method receives a {@link Printable} object, generates XML for it, transforms into PDF after applying style-sheet and
 * returns the PDF bytes as {@link AttachmentDataSource}
 * /*from w ww  . j  a  va2  s .  com*/
 * @param printableArtifact to be printed
 * @return {@link AttachmentDataSource} PDF bytes
 * @throws PrintingException in case of any errors occur during printing process
 */
protected Map<String, byte[]> getPrintBytes(Printable printableArtifact) throws PrintingException {
    try {
        Map<String, byte[]> streamMap = printableArtifact.renderXML();
        try {
            String loggingEnable = kualiConfigurationService
                    .getPropertyValueAsString(Constants.PRINT_LOGGING_ENABLE);
            if (loggingEnable != null && Boolean.parseBoolean(loggingEnable))
                logPrintDetails(streamMap);
        } catch (Exception ex) {
            LOG.error(ex.getMessage());
        }

        Map<String, byte[]> pdfByteMap = new LinkedHashMap<String, byte[]>();

        FopFactory fopFactory = FopFactory.newInstance();

        int xslCount = 0;
        // Apply all the style sheets to the xml document and generate the
        // PDF bytes
        if (printableArtifact.getXSLTemplates() != null) {
            for (Source source : printableArtifact.getXSLTemplates()) {
                xslCount++;
                StreamSource xslt = (StreamSource) source;
                if (xslt.getInputStream() == null || xslt.getInputStream().available() <= 0) {
                    LOG.error("Stylesheet is not available");
                } else {
                    createPdfWithFOP(streamMap, pdfByteMap, fopFactory, xslCount, xslt, printableArtifact);
                }
            }
        } else if (printableArtifact.getXSLTemplateWithBookmarks() != null) {
            Map<String, Source> templatesWithBookmarks = printableArtifact.getXSLTemplateWithBookmarks();
            for (Map.Entry<String, Source> templatesWithBookmark : templatesWithBookmarks.entrySet()) {
                StreamSource xslt = (StreamSource) templatesWithBookmark.getValue();
                createPdfWithFOP(streamMap, pdfByteMap, fopFactory, xslCount, xslt,
                        templatesWithBookmark.getKey(), printableArtifact);
            }

        }

        // Add all the attachments.
        if (printableArtifact.getAttachments() != null) {
            pdfByteMap.putAll(printableArtifact.getAttachments());
        }
        return pdfByteMap;
    } catch (FOPException e) {
        LOG.error(e.getMessage(), e);
        throw new PrintingException(e.getMessage(), e);
    } catch (TransformerConfigurationException e) {
        LOG.error(e.getMessage(), e);
        throw new PrintingException(e.getMessage(), e);
    } catch (TransformerException e) {
        LOG.error(e.getMessage(), e);
        throw new PrintingException(e.getMessage(), e);
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new PrintingException(e.getMessage(), e);
    }

}

From source file:org.kuali.coeus.s2sgen.impl.print.S2SPrintingServiceImpl.java

/**
 * This method receives a {@link S2SPrintable} object, generates XML for it, transforms into PDF after applying style-sheet and
 * returns the PDF bytes//from w  w w.  j a  va  2s . c  o  m
 *
 * @param printableArtifact to be printed
 * @return PDF bytes
 */
protected Map<String, byte[]> getPrintBytes(S2SPrintable printableArtifact) {
    try {
        Map<String, byte[]> streamMap = printableArtifact.renderXML();
        try {
            String loggingEnable = s2SConfigurationService
                    .getValueAsString(ConfigurationConstants.PRINT_LOGGING_ENABLE);
            if (loggingEnable != null && Boolean.parseBoolean(loggingEnable))
                logPrintDetails(streamMap);
        } catch (Exception ex) {
            LOG.error(ex.getMessage());
        }

        Map<String, byte[]> pdfByteMap = new LinkedHashMap<String, byte[]>();

        FopFactory fopFactory = FopFactory.newInstance();

        int xslCount = 0;
        // Apply all the style sheets to the xml document and generate the
        // PDF bytes
        if (printableArtifact.getXSLTemplates() != null) {
            for (Source source : printableArtifact.getXSLTemplates()) {
                xslCount++;
                StreamSource xslt = (StreamSource) source;
                if (xslt.getInputStream() == null || xslt.getInputStream().available() <= 0) {
                    LOG.error("Stylesheet is not available");
                } else {
                    createPdfWithFOP(streamMap, pdfByteMap, fopFactory, xslCount, xslt, printableArtifact);
                }
            }
        } else if (printableArtifact.getXSLTemplateWithBookmarks() != null) {
            Map<String, Source> templatesWithBookmarks = printableArtifact.getXSLTemplateWithBookmarks();
            for (Map.Entry<String, Source> templatesWithBookmark : templatesWithBookmarks.entrySet()) {
                StreamSource xslt = (StreamSource) templatesWithBookmark.getValue();
                createPdfWithFOP(streamMap, pdfByteMap, fopFactory, xslCount, xslt,
                        templatesWithBookmark.getKey(), printableArtifact);
            }

        }

        // Add all the attachments.
        if (printableArtifact.getAttachments() != null) {
            pdfByteMap.putAll(printableArtifact.getAttachments());
        }
        return pdfByteMap;
    } catch (FOPException | TransformerException | IOException e) {
        throw new S2SException(e.getMessage(), e);
    }
}

From source file:org.springframework.oxm.jaxb.Jaxb2Marshaller.java

@SuppressWarnings("deprecation") // on JDK 9
private Source processSource(Source source) {
    if (StaxUtils.isStaxSource(source) || source instanceof DOMSource) {
        return source;
    }//from  w  ww  .  j a v a 2  s. c o  m

    XMLReader xmlReader = null;
    InputSource inputSource = null;

    if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;
        xmlReader = saxSource.getXMLReader();
        inputSource = saxSource.getInputSource();
    } else if (source instanceof StreamSource) {
        StreamSource streamSource = (StreamSource) source;
        if (streamSource.getInputStream() != null) {
            inputSource = new InputSource(streamSource.getInputStream());
        } else if (streamSource.getReader() != null) {
            inputSource = new InputSource(streamSource.getReader());
        } else {
            inputSource = new InputSource(streamSource.getSystemId());
        }
    }

    try {
        if (xmlReader == null) {
            xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
        }
        xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
        String name = "http://xml.org/sax/features/external-general-entities";
        xmlReader.setFeature(name, isProcessExternalEntities());
        if (!isProcessExternalEntities()) {
            xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
        }
        return new SAXSource(xmlReader, inputSource);
    } catch (SAXException ex) {
        logger.warn("Processing of external entities could not be disabled", ex);
        return source;
    }
}

From source file:org.springframework.oxm.support.AbstractMarshaller.java

/**
 * Template method for handling {@code StreamSource}s.
 * <p>This implementation delegates to {@code unmarshalInputStream} or {@code unmarshalReader}.
 * @param streamSource the {@code StreamSource}
 * @return the object graph//from w  w w  .  j  ava2 s .c o m
 * @throws IOException if an I/O exception occurs
 * @throws XmlMappingException if the given source cannot be mapped to an object
 */
protected Object unmarshalStreamSource(StreamSource streamSource) throws XmlMappingException, IOException {
    if (streamSource.getInputStream() != null) {
        if (isProcessExternalEntities() && isSupportDtd()) {
            return unmarshalInputStream(streamSource.getInputStream());
        } else {
            InputSource inputSource = new InputSource(streamSource.getInputStream());
            inputSource.setEncoding(getDefaultEncoding());
            return unmarshalSaxSource(new SAXSource(inputSource));
        }
    } else if (streamSource.getReader() != null) {
        if (isProcessExternalEntities() && isSupportDtd()) {
            return unmarshalReader(streamSource.getReader());
        } else {
            return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getReader())));
        }
    } else {
        return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getSystemId())));
    }
}

From source file:org.theospi.portfolio.shared.control.ContentResourceUriResolver.java

public Source resolve(String href, String base) throws TransformerException {
    try {//from w w w  . ja  v  a2 s .c  o  m
        String accessUrl = getServerConfigurationService().getAccessUrl();
        String url = href.replaceAll(accessUrl, "");

        // We depend on these resolving as content entities (e.g., /content/group/<site> or /content/user/<user>),
        // so provide some assistance and consistency with metaobj resolution.

        // Check if this already resolves as a content entity and, if not, try again by prepending /content/.
        Reference ref = getEntityManager().newReference(url);
        Object entity = ref.getEntity();
        if (entity == null || !(entity instanceof ContentResource)) {
            if (!url.startsWith("/content/")) {
                url = "/content" + (url.startsWith("/") ? "" : "/") + url;
                ref = getEntityManager().newReference(url);
                entity = ref.getEntity();
            }
            if (entity == null || !(entity instanceof ContentResource)) {
                String msg = "Could not resolve URI as a content resource: " + href;
                logger.info(msg);
                throw new TransformerException(msg);
            }
        }

        ContentResource res = (ContentResource) entity;
        StreamSource strs = new StreamSource(res.streamContent());
        SAXSource ss = new SAXSource(new InputSource(strs.getInputStream()));
        CatalogResolver resolver = new CatalogResolver();
        String appUrl = getServerConfigurationService().getServerUrl();
        try {
            resolver.getCatalog().parseCatalog(appUrl + "/osp-common-tool/dtd/catalog.xml");
            XMLReader xread = XMLReaderFactory.createXMLReader();
            xread.setEntityResolver(resolver);
            ss.setXMLReader(xread);
        } catch (MalformedURLException e) {
            logger.error(e);
        } catch (IOException e) {
            logger.error(e);
        } catch (SAXException e) {
            logger.error(e);
        }

        return ss;
    } catch (ServerOverloadException e) {
        logger.error("", e);
    }
    return null;
}

From source file:org.toobsframework.transformpipeline.domain.BaseXMLTransformer.java

protected InputSource getInputSource(String xsl) throws TransformerException {
    StreamSource source = ((StreamSource) uriResolver.resolve(xsl + ".xsl", ""));
    InputSource iSource = new InputSource(source.getInputStream());
    iSource.setSystemId(source.getSystemId());
    return iSource;
}