Example usage for org.xml.sax InputSource getCharacterStream

List of usage examples for org.xml.sax InputSource getCharacterStream

Introduction

In this page you can find the example usage for org.xml.sax InputSource getCharacterStream.

Prototype

public Reader getCharacterStream() 

Source Link

Document

Get the character stream for this input source.

Usage

From source file:com.netspective.commons.xml.ParseContext.java

public void doExternalTransformations() throws TransformerConfigurationException, TransformerException,
        ParserConfigurationException, SAXException, IOException {
    // re-create the input source because the original stream is already closed
    InputSource inputSource = recreateInputSource();

    Source activeSource = inputSource.getByteStream() != null ? new StreamSource(inputSource.getByteStream())
            : new StreamSource(inputSource.getCharacterStream());
    activeSource.setSystemId(inputSource.getSystemId());

    Writer activeResultBuffer = new StringWriter();
    Result activeResult = new StreamResult(activeResultBuffer);
    activeResult.setSystemId(activeResultBuffer.getClass().getName());

    TransformerFactory factory = TransformerFactory.newInstance();
    int lastTransformer = transformSources.length - 1;
    for (int i = 0; i <= lastTransformer; i++) {
        Transformer transformer = factory.newTransformer(transformSources[i]);
        transformer.transform(activeSource, activeResult);

        if (i < lastTransformer) {
            activeSource = new StreamSource(new StringReader(activeResultBuffer.toString()));
            activeResultBuffer = new StringWriter();
            activeResult = new StreamResult(activeResultBuffer);
        }/*from   ww w .  j  a v  a  2s .c o m*/
    }

    // now that all the transformations have been performed, we want to reset our input source to the final
    // transformation
    init(createInputSource(activeResultBuffer.toString()));
}

From source file:com.atlassian.jira.bc.dataimport.DefaultDataImportService.java

private void closeInputSource(InputSource is) {
    if (is != null) {
        IOUtils.closeQuietly(is.getByteStream());
        IOUtils.closeQuietly(is.getCharacterStream());
    }/*from  www. ja v a  2 s. c  o  m*/
}

From source file:com.mirth.connect.plugins.datatypes.delimited.DelimitedReader.java

public void parse(InputSource input) throws SAXException, IOException {

    // Parsing overview
    ///* w w w . ja  v a2  s .c  o  m*/
    // The incoming stream is a single message which is a collection of one
    // or more records.
    // Each record is a collection of columns. Columns can be either fixed
    // width, or delimited.
    // Records are delimited.
    // Each record is assumed to contain the same number and type of
    // columns.
    //
    // The following user configurable options affect the behavior of the
    // parser:
    // o columnWidths The array of fixed column widths.
    // o columnDelimiter The characters that delimit (separate) the
    // columns.
    // o recordDelimiter The characters that delimit (separate) each
    // record.
    // o quoteToken The characters that are used to quote a column value.
    // o escapeWithDoubleQuote Iff true, embedded quotes are escaped with
    // two consecutive quotes.
    // Otherwise, the quote escape characters escape embedded quote
    // characters.
    // o quoteEscapeToken The characters used to escape a quote (or itself).
    // o ignoreCR Iff true, all incoming \r characters are ignored and not
    // processed.
    //
    // The following user configurable options affect the behavior of the
    // output:
    // o columnNames A list of column names (taken from either file header,
    // or supplied by user).
    BufferedReader in = new BufferedReader(input.getCharacterStream());

    // Start the document
    String documentHead = "delimited";
    ContentHandler contentHandler = getContentHandler();
    contentHandler.startDocument();

    // Output <delimited>
    contentHandler.startElement("", documentHead, "", null);

    // While the parser gets records from the message
    ArrayList<String> record;
    int recordNo = 1;
    while ((record = getRecord(in, null)) != null) {

        // Output <rowN>
        if (serializationProperties.isNumberedRows()) {
            contentHandler.startElement("", "row" + recordNo, "", null);
        } else {
            contentHandler.startElement("", "row", "", null);
        }

        // For each column
        for (int i = 0; i < record.size(); i++) {

            String columnName;
            if (serializationProperties.getColumnNames() != null
                    && i < serializationProperties.getColumnNames().length) {
                // User specified column name
                columnName = serializationProperties.getColumnNames()[i];
            } else {
                // Default column name
                columnName = "column" + (i + 1);
            }
            // Output <columnN>
            contentHandler.startElement("", columnName, "", null);

            // Output column value
            contentHandler.characters(record.get(i).toCharArray(), 0, record.get(i).length());

            // Output </columnN>
            contentHandler.endElement("", columnName, "");
        }

        // Output </rowN>
        if (serializationProperties.isNumberedRows()) {
            contentHandler.endElement("", "row" + recordNo, "");
        } else {
            contentHandler.endElement("", "row", "");
        }

        recordNo++;
    }

    // Output </delimited>
    contentHandler.endElement("", documentHead, "");

    // End the document
    contentHandler.endDocument();
}

From source file:org.apache.axis.SOAPPart.java

/**
 * Sets the content of the <CODE>SOAPEnvelope</CODE> object
 * with the data from the given <CODE>Source</CODE> object.
 * @param   source javax.xml.transform.Source</CODE> object with the data to
 *     be set//from ww  w.ja v a2s  .com
 * @throws  SOAPException if there is a problem in
 *     setting the source
 * @see #getContent() getContent()
 */
public void setContent(Source source) throws SOAPException {
    if (source == null)
        throw new SOAPException(Messages.getMessage("illegalArgumentException00"));

    // override the checks in HandlerChainImpl for JAXRPCHandler kludge
    MessageContext ctx = getMessage().getMessageContext();
    if (ctx != null) {
        ctx.setProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION, Boolean.TRUE);
    }

    contentSource = source;
    InputSource in = org.apache.axis.utils.XMLUtils.sourceToInputSource(contentSource);
    InputStream is = in.getByteStream();
    if (is != null) {
        setCurrentMessage(is, FORM_INPUTSTREAM);
    } else {
        Reader r = in.getCharacterStream();
        if (r == null) {
            throw new SOAPException(Messages.getMessage("noCharacterOrByteStream"));
        }
        BufferedReader br = new BufferedReader(r);
        String line = null;
        StringBuffer sb = new StringBuffer();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            throw new SOAPException(Messages.getMessage("couldNotReadFromCharStream"), e);
        }
        setCurrentMessage(sb.toString(), FORM_STRING);
    }
}

From source file:org.apache.axis.utils.XMLUtils.java

/**
 * Create a new document from the given URI, use the username and password
 * if the URI requires authentication./*from  w w w.j  av  a 2s .  c  om*/
 * @param uri the resource to get
 * @param username basic auth username
 * @param password basic auth password
 * @throws ParserConfigurationException if construction problems occur
 * @throws SAXException if the document has xml sax problems
 * @throws IOException if i/o exceptions occur
 */
public static Document newDocument(String uri, String username, String password)
        throws ParserConfigurationException, SAXException, IOException {
    InputSource ins = XMLUtils.getInputSourceFromURI(uri, username, password);
    Document doc = XMLUtils.newDocument(ins);
    // Close the Stream
    if (ins.getByteStream() != null) {
        ins.getByteStream().close();
    } else if (ins.getCharacterStream() != null) {
        ins.getCharacterStream().close();
    }
    return doc;
}

From source file:org.apache.cocoon.components.language.markup.xsp.SOAPHelper.java

public XScriptObject invoke() throws ProcessingException {
    HttpConnection conn = null;/*  www  . ja  v a 2  s  .com*/

    try {
        if (action == null || action.length() == 0) {
            action = "\"\"";
        }

        String host = url.getHost();
        int port = url.getPort();

        if (System.getProperty("http.proxyHost") != null) {
            String proxyHost = System.getProperty("http.proxyHost");
            int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
            conn = new HttpConnection(proxyHost, proxyPort, host, port);
        } else {
            conn = new HttpConnection(host, port);
        }

        PostMethod method = new PostMethod(url.getFile());
        String request;

        try {
            // Write the SOAP request body
            if (xscriptObject instanceof XScriptObjectInlineXML) {
                // Skip overhead
                request = ((XScriptObjectInlineXML) xscriptObject).getContent();
            } else {
                StringBuffer bodyBuffer = new StringBuffer();
                InputSource saxSource = xscriptObject.getInputSource();

                Reader r = null;
                // Byte stream or character stream?
                if (saxSource.getByteStream() != null) {
                    r = new InputStreamReader(saxSource.getByteStream());
                } else {
                    r = saxSource.getCharacterStream();
                }

                try {
                    char[] buffer = new char[1024];
                    int len;
                    while ((len = r.read(buffer)) > 0)
                        bodyBuffer.append(buffer, 0, len);
                } finally {
                    if (r != null) {
                        r.close();
                    }
                }

                request = bodyBuffer.toString();
            }

        } catch (Exception ex) {
            throw new ProcessingException("Error assembling request", ex);
        }

        method.setRequestHeader(new Header("Content-type", "text/xml; charset=\"utf-8\""));
        method.setRequestHeader(new Header("SOAPAction", action));
        method.setRequestBody(request);

        if (authorization != null && !authorization.equals("")) {
            method.setRequestHeader(
                    new Header("Authorization", "Basic " + SourceUtil.encodeBASE64(authorization)));
        }

        method.execute(new HttpState(), conn);

        String ret = method.getResponseBodyAsString();
        int startOfXML = ret.indexOf("<?xml");
        if (startOfXML == -1) { // No xml?!
            throw new ProcessingException("Invalid response - no xml");
        }

        return new XScriptObjectInlineXML(xscriptManager, ret.substring(startOfXML));
    } catch (Exception ex) {
        throw new ProcessingException("Error invoking remote service: " + ex, ex);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception ex) {
        }
    }
}

From source file:org.apache.cocoon.components.language.markup.xsp.XSPSOAPHelper.java

public XScriptObject invoke() throws ProcessingException {
    HttpConnection conn = null;//from   ww  w  . j  a v a2  s  . co  m

    try {
        if (this.action == null || this.action.length() == 0) {
            this.action = "\"\"";
        }

        String host = this.url.getHost();
        int port = this.url.getPort();
        Protocol protocol = Protocol.getProtocol(this.url.getProtocol());

        if (System.getProperty("http.proxyHost") != null) {
            String proxyHost = System.getProperty("http.proxyHost");
            int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
            conn = new HttpConnection(proxyHost, proxyPort, host, null, port, protocol);
        } else {
            conn = new HttpConnection(host, port, protocol);
        }
        conn.setSoTimeout(1000 * timeoutSeconds);

        PostMethod method = new PostMethod(this.url.getFile());
        String request;

        try {
            // Write the SOAP request body
            if (this.xscriptObject instanceof XScriptObjectInlineXML) {
                // Skip overhead
                request = ((XScriptObjectInlineXML) this.xscriptObject).getContent();
            } else {
                StringBuffer bodyBuffer = new StringBuffer();
                InputSource saxSource = this.xscriptObject.getInputSource();

                Reader r = null;
                // Byte stream or character stream?
                if (saxSource.getByteStream() != null) {
                    r = new InputStreamReader(saxSource.getByteStream());
                } else {
                    r = saxSource.getCharacterStream();
                }

                try {
                    char[] buffer = new char[1024];
                    int len;
                    while ((len = r.read(buffer)) > 0) {
                        bodyBuffer.append(buffer, 0, len);
                    }
                } finally {
                    if (r != null) {
                        r.close();
                    }
                }

                request = bodyBuffer.toString();
            }

        } catch (Exception ex) {
            throw new ProcessingException("Error assembling request", ex);
        }

        method.setRequestHeader(new Header("Content-type", "text/xml; charset=utf-8"));
        method.setRequestHeader(new Header("SOAPAction", this.action));
        method.setRequestBody(request);

        if (this.authorization != null && !this.authorization.equals("")) {
            method.setRequestHeader(
                    new Header("Authorization", "Basic " + SourceUtil.encodeBASE64(this.authorization)));
        }

        method.execute(new HttpState(), conn);

        String contentType = method.getResponseHeader("Content-type").toString();
        // Check if charset given, if not, use defaultResponseEncoding
        // (cannot just use getResponseCharSet() as it fills in
        // "ISO-8859-1" if the charset is not specified)
        String charset = contentType.indexOf("charset=") == -1 ? this.defaultResponseEncoding
                : method.getResponseCharSet();
        String ret = new String(method.getResponseBody(), charset);

        return new XScriptObjectInlineXML(this.xscriptManager, ret);
    } catch (ProcessingException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ProcessingException("Error invoking remote service: " + ex, ex);
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception ex) {
        }
    }
}

From source file:org.apache.ddlutils.io.DatabaseIO.java

/**
 * Reads the database model from the given input source.
 *
 * @param source The input source//w  ww .j  av  a 2s.  c o  m
 * @return The database model
 */
public Database read(InputSource source) throws DdlUtilsXMLException {
    return read(source.getCharacterStream());
}

From source file:org.apache.ddlutils.io.DataReader.java

/**
 * Reads the data from the given input source.
 *
 * @param source The input source/*  ww w. j ava  2 s.  co m*/
 */
public void read(InputSource source) throws DdlUtilsXMLException {
    read(source.getCharacterStream());
}

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Parse an XML document located using an {@link InputSource} using the
 * pooled document builder.//from   www  . j  a  va 2  s  .  c o  m
 */
public static Document sourceToDOM(Source inputSource) throws IOException {
    try {
        /*
        // Requires JDK 1.6+
        if (inputSource instanceof StAXSource) {
        StAXSource stax = (StAXSource) inputSource;
        //if (stax.getXMLEventReader() != null || sax.getXMLStreamReader() != null) {
        if (sax.getXMLStreamReader() != null) {
            return parse(stax.getXMLStreamReader());
        }
        }
        */
        if (inputSource instanceof SAXSource) {
            InputSource sax = ((SAXSource) inputSource).getInputSource();
            if (sax.getCharacterStream() != null || sax.getByteStream() != null) {
                return parse(((SAXSource) inputSource).getInputSource());
            }
        }
        if (inputSource instanceof DOMSource) {
            Node node = ((DOMSource) inputSource).getNode();
            if (node != null) {
                return toDOMDocument(node);
            }
        }
        if (inputSource instanceof StreamSource) {
            StreamSource stream = (StreamSource) inputSource;
            if (stream.getReader() != null || stream.getInputStream() != null) {
                return toDocumentFromStream((StreamSource) inputSource);
            }
        }
        DOMResult domresult = new DOMResult(newDocument());
        Transformer txer = getTransformer();
        txer.transform(inputSource, domresult);
        return (Document) domresult.getNode();
    } catch (SAXException e) {
        throwIOException(e);
    } catch (TransformerException e) {
        throwIOException(e);
    }
    throw new IllegalArgumentException("Cannot parse XML source: " + inputSource.getClass());
}