Example usage for org.xml.sax InputSource getByteStream

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

Introduction

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

Prototype

public InputStream getByteStream() 

Source Link

Document

Get the byte stream for this input source.

Usage

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

public XScriptObject invoke() throws ProcessingException {
    HttpConnection conn = null;// www.  j  a v a2s  .  co  m

    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  w w  w  .ja va2s  . c  om*/

    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.cocoon.components.xslt.TraxProcessor.java

/**
 * Called by the processor when it encounters an xsl:include, xsl:import, or
 * document() function./*w ww  .  jav  a2 s  .c o  m*/
 * 
 * @param href
 *            An href attribute, which may be relative or absolute.
 * @param base
 *            The base URI in effect when the href attribute was
 *            encountered.
 * 
 * @return A Source object, or null if the href cannot be resolved, and the
 *         processor should try to resolve the URI itself.
 * 
 * @throws TransformerException
 *             if an error occurs when trying to resolve the URI.
 */
public javax.xml.transform.Source resolve(String href, String base) throws TransformerException {
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("resolve(href = " + href + ", base = " + base + "); resolver = " + m_resolver);
    }

    Source xslSource = null;
    try {
        if (base == null || href.indexOf(":") > 1) {
            // Null base - href must be an absolute URL
            xslSource = m_resolver.resolveURI(href);
        } else if (href.length() == 0) {
            // Empty href resolves to base
            xslSource = m_resolver.resolveURI(base);
        } else {
            // is the base a file or a real m_url
            if (!base.startsWith("file:")) {
                int lastPathElementPos = base.lastIndexOf('/');
                if (lastPathElementPos == -1) {
                    // this should never occur as the base should
                    // always be protocol:/....
                    return null; // we can't resolve this
                } else {
                    xslSource = m_resolver.resolveURI(base.substring(0, lastPathElementPos) + "/" + href);
                }
            } else {
                File parent = new File(base.substring(5));
                File parent2 = new File(parent.getParentFile(), href);
                xslSource = m_resolver.resolveURI(parent2.toURL().toExternalForm());
            }
        }

        InputSource is = getInputSource(xslSource);

        if (getLogger().isDebugEnabled()) {
            getLogger().debug("xslSource = " + xslSource + ", system id = " + xslSource.getURI());
        }

        if (m_checkIncludes) {
            // Populate included validities
            List includes = (List) m_includesMap.get(base);
            if (includes != null) {
                SourceValidity included = xslSource.getValidity();
                if (included != null) {
                    includes.add(new Object[] { xslSource.getURI(), xslSource.getValidity() });
                } else {
                    // One of the included stylesheets is not cacheable
                    m_includesMap.remove(base);
                }
            }
        }

        return new StreamSource(is.getByteStream(), is.getSystemId());
    } catch (SourceException e) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Failed to resolve " + href + "(base = " + base + "), return null", e);
        }

        // CZ: To obtain the same behaviour as when the resource is
        // transformed by the XSLT Transformer we should return null here.
        return null;
    } catch (java.net.MalformedURLException mue) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Failed to resolve " + href + "(base = " + base + "), return null", mue);
        }

        return null;
    } catch (IOException ioe) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Failed to resolve " + href + "(base = " + base + "), return null", ioe);
        }

        return null;
    } finally {
        m_resolver.release(xslSource);
    }
}

From source file:org.apache.jackrabbit.core.nodetype.NodeTypeManagerImpl.java

/**
 * Registers the node types defined in the given XML stream.  This
 * is a trivial implementation that just invokes the existing
 * {@link NodeTypeReader} and {@link NodeTypeRegistry} methods and
 * heuristically creates the returned node type array.  It will also
 * register any namespaces defined in the input source that have not
 * already been registered.//from w w w .ja  v  a  2 s.  c  om
 *
 * {@inheritDoc}
 */
public NodeType[] registerNodeTypes(InputSource in) throws SAXException, RepositoryException {
    try {
        return registerNodeTypes(in.getByteStream(), TEXT_XML);
    } catch (IOException e) {
        throw new SAXException("Error reading node type stream", e);
    }
}

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

/**
 * Parse an XML document located using an {@link InputSource} using the
 * pooled document builder./*from w w  w  . j av a  2s  . com*/
 */
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());
}

From source file:org.apache.solr.common.util.TestSystemIdResolver.java

private void assertEntityResolving(SystemIdResolver resolver, String expectedSystemId, String base,
        String systemId) throws Exception {
    final InputSource is = resolver.resolveEntity(null, null, base, systemId);
    try {//from   ww  w. ja  va2s .c  om
        assertEquals("Resolved SystemId does not match", expectedSystemId, is.getSystemId());
    } finally {
        IOUtils.closeQuietly(is.getByteStream());
    }
}

From source file:org.apache.solr.core.Config.java

/**
 * Builds a config://from   www  . ja  v  a2s.c  o  m
 * <p>
 * Note that the 'name' parameter is used to obtain a valid input stream if no valid one is provided through 'is'.
 * If no valid stream is provided, a valid SolrResourceLoader instance should be provided through 'loader' so
 * the resource can be opened (@see SolrResourceLoader#openResource); if no SolrResourceLoader instance is provided, a default one
 * will be created.
 * </p>
 * <p>
 * Consider passing a non-null 'name' parameter in all use-cases since it is used for logging & exception reporting.
 * </p>
 * @param loader the resource loader used to obtain an input stream if 'is' is null
 * @param name the resource name used if the input stream 'is' is null
 * @param is the resource as a SAX InputSource
 * @param prefix an optional prefix that will be preprended to all non-absolute xpath expressions
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws java.io.IOException
 * @throws org.xml.sax.SAXException
 */
public Config(SolrResourceLoader loader, String name, InputSource is, String prefix)
        throws ParserConfigurationException, IOException, SAXException {
    if (loader == null) {
        loader = new SolrResourceLoader(null);
    }
    this.loader = loader;
    this.name = name;
    this.prefix = (prefix != null && !prefix.endsWith("/")) ? prefix + '/' : prefix;
    try {
        javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        if (is == null) {
            is = new InputSource(loader.openConfig(name));
            is.setSystemId(SystemIdResolver.createSystemIdFromResourceName(name));
        }

        // only enable xinclude, if a SystemId is available
        if (is.getSystemId() != null) {
            try {
                dbf.setXIncludeAware(true);
                dbf.setNamespaceAware(true);
            } catch (UnsupportedOperationException e) {
                log.warn(name + " XML parser doesn't support XInclude option");
            }
        }

        final DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new SystemIdResolver(loader));
        db.setErrorHandler(xmllog);
        try {
            doc = db.parse(is);
        } finally {
            // some XML parsers are broken and don't close the byte stream (but they should according to spec)
            IOUtils.closeQuietly(is.getByteStream());
        }

        DOMUtil.substituteProperties(doc, loader.getCoreProperties());
    } catch (ParserConfigurationException e) {
        SolrException.log(log, "Exception during parsing file: " + name, e);
        throw e;
    } catch (SAXException e) {
        SolrException.log(log, "Exception during parsing file: " + name, e);
        throw e;
    } catch (SolrException e) {
        SolrException.log(log, "Error in " + name, e);
        throw e;
    }
}

From source file:org.apache.solr.handler.dataimport.DataImporter.java

public DIHConfiguration loadDataConfig(InputSource configFile) {

    DIHConfiguration dihcfg = null;/*w  w  w.ja  v  a2s . com*/
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        // only enable xinclude, if a a SolrCore and SystemId is present (makes no sense otherwise)
        if (core != null && configFile.getSystemId() != null) {
            try {
                dbf.setXIncludeAware(true);
                dbf.setNamespaceAware(true);
            } catch (UnsupportedOperationException e) {
                LOG.warn("XML parser doesn't support XInclude option");
            }
        }

        DocumentBuilder builder = dbf.newDocumentBuilder();
        if (core != null)
            builder.setEntityResolver(new SystemIdResolver(core.getResourceLoader()));
        builder.setErrorHandler(XMLLOG);
        Document document;
        try {
            document = builder.parse(configFile);
        } finally {
            // some XML parsers are broken and don't close the byte stream (but they should according to spec)
            IOUtils.closeQuietly(configFile.getByteStream());
        }

        dihcfg = readFromXml(document);
        LOG.info("Data Configuration loaded successfully");
    } catch (Exception e) {
        throw new DataImportHandlerException(SEVERE, "Data Config problem: " + e.getMessage(), e);
    }
    for (Entity e : dihcfg.getEntities()) {
        if (e.getAllAttributes().containsKey(SqlEntityProcessor.DELTA_QUERY)) {
            isDeltaImportSupported = true;
            break;
        }
    }
    return dihcfg;
}

From source file:org.apache.xmlgraphics.image.loader.util.ImageUtil.java

/**
 * Returns the InputStream of a Source object.
 * @param src the Source object//from ww  w .j  a  va  2s.com
 * @return the InputStream (or null if there's not InputStream available)
 */
public static InputStream getInputStream(Source src) {
    if (src instanceof StreamSource) {
        return ((StreamSource) src).getInputStream();
    } else if (src instanceof ImageSource) {
        return new ImageInputStreamAdapter(((ImageSource) src).getImageInputStream());
    } else if (src instanceof SAXSource) {
        InputSource is = ((SAXSource) src).getInputSource();
        if (is != null) {
            return is.getByteStream();
        }
    }
    return null;
}

From source file:org.apache.xmlgraphics.image.loader.util.ImageUtil.java

/**
 * Indicates whether the Source object has an InputStream instance.
 * @param src the Source object/* w  ww . j av a  2 s . c  o m*/
 * @return true if an InputStream is available
 */
public static boolean hasInputStream(Source src) {
    if (src instanceof StreamSource) {
        InputStream in = ((StreamSource) src).getInputStream();
        return (in != null);
    } else if (src instanceof ImageSource) {
        return hasImageInputStream(src);
    } else if (src instanceof SAXSource) {
        InputSource is = ((SAXSource) src).getInputSource();
        if (is != null) {
            return (is.getByteStream() != null);
        }
    }
    return false;
}