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

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

Introduction

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

Prototype

public Reader getReader() 

Source Link

Document

Get the character stream that was set with setReader.

Usage

From source file:Main.java

/**
 * Utility to get the bytes uri//from w ww  .  j  av  a 2s.  com
 *
 * @param source the resource to get
 */
public static InputSource sourceToInputSource(Source source) {
    if (source instanceof SAXSource) {
        return ((SAXSource) source).getInputSource();
    } else if (source instanceof DOMSource) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Node node = ((DOMSource) source).getNode();
        if (node instanceof Document) {
            node = ((Document) node).getDocumentElement();
        }
        Element domElement = (Element) node;
        ElementToStream(domElement, baos);
        InputSource isource = new InputSource(source.getSystemId());
        isource.setByteStream(new ByteArrayInputStream(baos.toByteArray()));
        return isource;
    } else if (source instanceof StreamSource) {
        StreamSource ss = (StreamSource) source;
        InputSource isource = new InputSource(ss.getSystemId());
        isource.setByteStream(ss.getInputStream());
        isource.setCharacterStream(ss.getReader());
        isource.setPublicId(ss.getPublicId());
        return isource;
    } else {
        return getInputSourceFromURI(source.getSystemId());
    }
}

From source file:it.geosolutions.tools.io.file.reader.TextReader.java

/**
 * Convert the input from the provided {@link Reader} into a {@link String}.
 * //from  w w w  .  j a v  a2 s. co 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 toString(StreamSource src) throws IOException {
    Objects.notNull(src);
    InputStream inputStream = src.getInputStream();
    if (inputStream != null) {
        return org.apache.commons.io.IOUtils.toString(inputStream);
    } else {

        final Reader r = src.getReader();
        return org.apache.commons.io.IOUtils.toString(r);
    }
}

From source file:it.geosolutions.tools.io.file.reader.TextReader.java

/**
 * Convert the input from the provided {@link Reader} into a {@link String}.
 * // ww  w  .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 toString(final StreamSource src, final String ecoding) throws IOException {
    Objects.notNull(src);
    InputStream inputStream = src.getInputStream();
    if (inputStream != null) {
        return org.apache.commons.io.IOUtils.toString(inputStream, ecoding);
    } else {

        final Reader r = src.getReader();
        return org.apache.commons.io.IOUtils.toString(r);
    }
}

From source file:net.sf.joost.trax.TrAXHelper.java

/**
 * Helpermethod for getting an InputSource from a StreamSource.
 * @param source <code>Source</code>
 * @return An <code>InputSource</code> object or null
 * @throws TransformerConfigurationException
 *///from   w  ww .ja va  2  s. com
protected static InputSource getInputSourceForStreamSources(Source source, ErrorListener errorListener)
        throws TransformerConfigurationException {

    if (DEBUG)
        log.debug("getting an InputSource from a StreamSource");
    InputSource input = null;
    String systemId = source.getSystemId();

    if (systemId == null) {
        systemId = "";
    }
    try {
        if (source instanceof StreamSource) {
            if (DEBUG)
                log.debug("Source is a StreamSource");
            StreamSource stream = (StreamSource) source;
            InputStream istream = stream.getInputStream();
            Reader reader = stream.getReader();
            // Create InputSource from Reader or InputStream in Source
            if (istream != null) {
                input = new InputSource(istream);
            } else {
                if (reader != null) {
                    input = new InputSource(reader);
                } else {
                    input = new InputSource(systemId);
                }
            }
        } else {
            //Source type is not supported
            if (errorListener != null) {
                try {
                    errorListener
                            .fatalError(new TransformerConfigurationException("Source is not a StreamSource"));
                    return null;
                } catch (TransformerException e2) {
                    if (DEBUG)
                        log.debug("Source is not a StreamSource");
                    throw new TransformerConfigurationException("Source is not a StreamSource");
                }
            }
            if (DEBUG)
                log.debug("Source is not a StreamSource");
            throw new TransformerConfigurationException("Source is not a StreamSource");
        }
        //setting systemId
        input.setSystemId(systemId);
        //          } catch (NullPointerException nE) {
        //              //catching NullPointerException
        //              if(errorListener != null) {
        //                  try {
        //                      errorListener.fatalError(
        //                              new TransformerConfigurationException(nE));
        //                      return null;
        //                  } catch( TransformerException e2) {
        //                      log.debug(nE);
        //                      throw new TransformerConfigurationException(nE.getMessage());
        //                  }
        //              }
        //              log.debug(nE);
        //              throw new TransformerConfigurationException(nE.getMessage());
    } catch (SecurityException sE) {
        //catching SecurityException
        if (errorListener != null) {
            try {
                errorListener.fatalError(new TransformerConfigurationException(sE));
                return null;
            } catch (TransformerException e2) {
                if (DEBUG)
                    log.debug(sE);
                throw new TransformerConfigurationException(sE.getMessage());
            }
        }
        if (DEBUG)
            log.debug(sE);
        throw new TransformerConfigurationException(sE.getMessage());
    }
    return (input);
}

From source file:com.mirth.connect.connectors.http.HttpMessageConverter.java

private static void processContent(DonkeyElement contentElement, Object content, ContentType contentType,
        boolean parseMultipart, BinaryContentTypeResolver resolver)
        throws DonkeyElementException, MessagingException, IOException {
    if (resolver == null) {
        resolver = defaultResolver;//from   www  .j  a  v a 2s .  c om
    }

    if (parseMultipart && content instanceof MimeMultipart) {
        contentElement.setAttribute("multipart", "yes");
        MimeMultipart multipart = (MimeMultipart) content;

        String boundary = contentType.getParameter("boundary");
        if (StringUtils.isNotBlank(boundary)) {
            contentElement.setAttribute("boundary", boundary);
        }

        if (StringUtils.isNotEmpty(multipart.getPreamble())) {
            contentElement.addChildElement("Preamble", multipart.getPreamble());
        }

        for (int partIndex = 0; partIndex < multipart.getCount(); partIndex++) {
            BodyPart part = multipart.getBodyPart(partIndex);
            DonkeyElement partElement = contentElement.addChildElement("Part");
            DonkeyElement headersElement = partElement.addChildElement("Headers");
            ContentType partContentType = contentType;

            for (Enumeration<javax.mail.Header> en = part.getAllHeaders(); en.hasMoreElements();) {
                javax.mail.Header header = en.nextElement();
                headersElement.addChildElement(header.getName(), header.getValue());

                if (header.getName().equalsIgnoreCase("Content-Type")) {
                    try {
                        partContentType = ContentType.parse(header.getValue());
                    } catch (RuntimeException e) {
                    }
                }
            }

            processContent(partElement.addChildElement("Content"), part.getContent(), partContentType, true,
                    resolver);
        }
    } else {
        contentElement.setAttribute("multipart", "no");
        String charset = getDefaultHttpCharset(
                contentType.getCharset() != null ? contentType.getCharset().name() : null);

        // Call the resolver to determine if the content should be Base64 encoded
        if (resolver.isBinaryContentType(contentType)) {
            contentElement.setAttribute("encoding", "Base64");
            byte[] contentByteArray = null;

            if (content instanceof StreamSource) {
                StreamSource streamSource = (StreamSource) content;
                if (streamSource.getInputStream() != null) {
                    contentByteArray = IOUtils.toByteArray(streamSource.getInputStream());
                } else if (streamSource.getReader() != null) {
                    contentByteArray = IOUtils.toString(streamSource.getReader()).getBytes(charset);
                }
            } else if (content instanceof InputStream) {
                contentByteArray = IOUtils.toByteArray((InputStream) content);
            } else if (content instanceof byte[]) {
                contentByteArray = (byte[]) content;
            }

            if (contentByteArray == null) {
                contentByteArray = (content != null ? content.toString() : "").getBytes(charset);
            }

            contentElement.setTextContent(new String(Base64Util.encodeBase64(contentByteArray), "US-ASCII"));
        } else {
            String contentText = null;

            if (content instanceof StreamSource) {
                StreamSource streamSource = (StreamSource) content;
                if (streamSource.getInputStream() != null) {
                    contentText = IOUtils.toString(streamSource.getInputStream(), charset);
                } else if (streamSource.getReader() != null) {
                    contentText = IOUtils.toString(streamSource.getReader());
                }
            } else if (content instanceof InputStream) {
                contentText = IOUtils.toString((InputStream) content, charset);
            } else if (content instanceof byte[]) {
                contentText = new String((byte[]) content, charset);
            }

            if (contentText == null) {
                contentText = content != null ? content.toString() : "";
            }

            contentElement.setTextContent(contentText);
        }
    }
}

From source file:Utils.java

public static Document readXml(StreamSource is) throws SAXException, IOException, ParserConfigurationException {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);// w w  w.  ja va 2s .c o  m
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);
    // dbf.setCoalescing(true);
    // dbf.setExpandEntityReferences(true);

    DocumentBuilder db = null;
    db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());

    // db.setErrorHandler( new MyErrorHandler());
    InputSource is2 = new InputSource();
    is2.setSystemId(is.getSystemId());
    is2.setByteStream(is.getInputStream());
    is2.setCharacterStream(is.getReader());

    return db.parse(is2);
}

From source file:biz.c24.io.spring.oxm.C24Marshaller.java

/**
 * Returns a C24 {@link XMLSource} for the given {@link StreamSource}. Will prefer the source's {@link Reader} over
 * its {@link InputStream}.//from   ww  w  . j  a  va2s. c  om
 * 
 * @param source
 * @return
 */
private XMLSource getXmlSourceFrom(StreamSource source) {

    Reader reader = source.getReader();
    return reader != null ? new XMLSource(reader) : new XMLSource(source.getInputStream());
}

From source file:it.cnr.icar.eric.server.cms.CanonicalXMLCatalogingService.java

protected void dumpStream(StreamSource ss) {
    BufferedReader br = null;/*from  ww w  .ja  v  a 2  s. c o  m*/

    try {
        InputStream inputStream = ss.getInputStream();
        Reader inputReader = ss.getReader();

        if (inputStream != null) {
            br = new BufferedReader(new InputStreamReader(inputStream));
        } else if (inputReader != null) {
            br = new BufferedReader(inputReader);
        }

        if (br == null) {
            System.err.println("No reader for StreamSource");

            return;
        }

        String line;

        while ((line = br.readLine()) != null) {
            System.err.print(line);
        }

        System.err.println();
    } catch (Exception e) {
        br = null;
    }
}

From source file:at.gv.egiz.slbinding.SLUnmarshaller.java

/**
 * @param source a StreamSource wrapping a Reader (!) for the marshalled Object
 * @return the unmarshalled Object//from w  w w  . j a v a  2  s.c o m
 * @throws XMLStreamException
 * @throws JAXBException
 */
public Object unmarshal(StreamSource source) throws XMLStreamException, JAXBException {
    Reader inputReader = source.getReader();

    /* Validate XML against XXE, XEE, and SSRF
     * 
     * This pre-validation step is required because com.sun.xml.stream.sjsxp-1.0.2 XML stream parser library does not 
     * support all XML parser features to prevent these types of attacks  
     */
    if (inputReader instanceof InputStreamReader) {
        try {
            //create copy of input stream
            InputStreamReader isReader = (InputStreamReader) inputReader;
            String encoding = isReader.getEncoding();
            byte[] backup = IOUtils.toByteArray(isReader, encoding);

            //validate input stream
            DOMUtils.validateXMLAgainstXXEAndSSRFAttacks(new ByteArrayInputStream(backup));

            //create new inputStreamReader for reak processing
            inputReader = new InputStreamReader(new ByteArrayInputStream(backup), encoding);

        } catch (XMLStreamException e) {
            log.error("XML data validation FAILED with msg: " + e.getMessage(), e);
            throw new XMLStreamException("XML data validation FAILED with msg: " + e.getMessage(), e);

        } catch (IOException e) {
            log.error("XML data validation FAILED with msg: " + e.getMessage(), e);
            throw new XMLStreamException("XML data validation FAILED with msg: " + e.getMessage(), e);

        }

    } else {
        log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        log.error(
                "Reader is not of type InputStreamReader -> can not make a copy of the InputStream --> extended XML validation is not possible!!! ");
        log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

    }

    /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     * parse XML with original functionality
     * 
     * This code implements the the original mocca XML processing by using 
     *  com.sun.xml.stream.sjsxp-1.0.2 XML stream parser library. Currently, this library is required to get full 
     *  security-layer specific XML processing. However, this lib does not fully support XXE, XEE and SSRF
     *  prevention mechanisms (e.g.: XMLInputFactory.SUPPORT_DTD flag is not used)    
     * 
     * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     */
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();

    //disallow DTD and external entities
    inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    inputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);

    XMLEventReader eventReader = inputFactory.createXMLEventReader(inputReader);
    RedirectEventFilter redirectEventFilter = new RedirectEventFilter();
    XMLEventReader filteredReader = inputFactory.createFilteredReader(eventReader, redirectEventFilter);

    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    ReportingValidationEventHandler validationEventHandler = new ReportingValidationEventHandler();
    unmarshaller.setEventHandler(validationEventHandler);

    unmarshaller.setListener(new RedirectUnmarshallerListener(redirectEventFilter));
    unmarshaller.setSchema(slSchema);

    Object object;
    try {
        log.trace("Before unmarshal().");
        object = unmarshaller.unmarshal(filteredReader);
        log.trace("After unmarshal().");
    } catch (UnmarshalException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to unmarshal security layer message.", e);
        } else {
            log.info("Failed to unmarshal security layer message."
                    + (e.getMessage() != null ? " " + e.getMessage() : ""));
        }

        if (validationEventHandler.getErrorEvent() != null) {
            ValidationEvent errorEvent = validationEventHandler.getErrorEvent();
            if (e.getLinkedException() == null) {
                e.setLinkedException(errorEvent.getLinkedException());
            }
        }
        throw e;
    }

    return object;

}

From source file:org.dataconservancy.packaging.tool.ser.JenaModelSerializer.java

/**
 * {@inheritDoc}/* w w  w  .  j  a va  2  s.c o m*/
 * <p>
 * Overridden in this implementation to always unmarshal an {@code InputStream} if it is available from {@code
 * streamSource}, instead of wrapping it with a SAX {@code InputSource}.
 * </p>
 *
 * @param streamSource {@inheritDoc}
 * @return {@inheritDoc}
 * @throws XmlMappingException {@inheritDoc}
 * @throws IOException {@inheritDoc}
 */
@Override
protected Object unmarshalStreamSource(StreamSource streamSource) throws XmlMappingException, IOException {
    InputStream in = streamSource.getInputStream();
    if (in != null) {
        return unmarshalInputStream(in);
    }

    Reader r = streamSource.getReader();
    if (r != null) {
        return unmarshalReader(streamSource.getReader());
    }

    return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getSystemId())));
}