Search in sources :

Example 6 with Serializer

use of org.apache.xml.serializer.Serializer in project j2objc by google.

the class LSSerializerImpl method writeToURI.

/** 
     * Serializes the specified node to the specified URI and returns true if the Node 
     * was successfully serialized. 
     * 
     * @see org.w3c.dom.ls.LSSerializer#writeToURI(org.w3c.dom.Node, String)
     * @since DOM Level 3
     * @param nodeArg The Node to serialize.
     * @throws org.w3c.dom.ls.LSException SERIALIZE_ERR: Raised if the 
     * LSSerializer was unable to serialize the node.
     *      
     */
public boolean writeToURI(Node nodeArg, String uri) throws LSException {
    // If nodeArg is null, return false.  Should we throw and LSException instead?
    if (nodeArg == null) {
        return false;
    }
    // Obtain a reference to the serializer to use
    Serializer serializer = fXMLSerializer;
    serializer.reset();
    if (nodeArg != fVisitedNode) {
        // Determine the XML Document version of the Node 
        String xmlVersion = getXMLVersion(nodeArg);
        // Determine the encoding: 1.LSOutput.encoding,
        // 2.Document.inputEncoding, 3.Document.xmlEncoding.
        fEncoding = getInputEncoding(nodeArg);
        if (fEncoding == null) {
            fEncoding = fEncoding != null ? fEncoding : getXMLEncoding(nodeArg) == null ? "UTF-8" : getXMLEncoding(nodeArg);
        }
        serializer.getOutputFormat().setProperty("version", xmlVersion);
        // Set the output encoding and xml version properties
        fDOMConfigProperties.setProperty(DOMConstants.S_XERCES_PROPERTIES_NS + DOMConstants.S_XML_VERSION, xmlVersion);
        fDOMConfigProperties.setProperty(DOMConstants.S_XSL_OUTPUT_ENCODING, fEncoding);
        // serialized.
        if ((nodeArg.getNodeType() != Node.DOCUMENT_NODE || nodeArg.getNodeType() != Node.ELEMENT_NODE || nodeArg.getNodeType() != Node.ENTITY_NODE) && ((fFeatures & XMLDECL) != 0)) {
            fDOMConfigProperties.setProperty(DOMConstants.S_XSL_OUTPUT_OMIT_XML_DECL, DOMConstants.DOM3_DEFAULT_FALSE);
        }
        fVisitedNode = nodeArg;
    }
    // Update the serializer properties
    fXMLSerializer.setOutputFormat(fDOMConfigProperties);
    // 
    try {
        // "unsupported-encoding" fatal error is raised. ??
        if (uri == null) {
            String msg = Utils.messages.createMessage(MsgKey.ER_NO_OUTPUT_SPECIFIED, null);
            if (fDOMErrorHandler != null) {
                fDOMErrorHandler.handleError(new DOMErrorImpl(DOMError.SEVERITY_FATAL_ERROR, msg, MsgKey.ER_NO_OUTPUT_SPECIFIED));
            }
            throw new LSException(LSException.SERIALIZE_ERR, msg);
        } else {
            // REVISIT: Can this be used to get an absolute expanded URI
            String absoluteURI = SystemIDResolver.getAbsoluteURI(uri);
            URL url = new URL(absoluteURI);
            OutputStream urlOutStream = null;
            String protocol = url.getProtocol();
            String host = url.getHost();
            // (e.g., allow "HTTP" as well as "http").
            if (protocol.equalsIgnoreCase("file") && (host == null || host.length() == 0 || host.equals("localhost"))) {
                // do we also need to check for host.equals(hostname)
                urlOutStream = new FileOutputStream(getPathWithoutEscapes(url.getPath()));
            } else {
                // This should support URL's whose schemes are mentioned in
                // RFC1738 other than file
                URLConnection urlCon = url.openConnection();
                urlCon.setDoInput(false);
                urlCon.setDoOutput(true);
                urlCon.setUseCaches(false);
                urlCon.setAllowUserInteraction(false);
                // When writing to a HTTP URI, a HTTP PUT is performed.
                if (urlCon instanceof HttpURLConnection) {
                    HttpURLConnection httpCon = (HttpURLConnection) urlCon;
                    httpCon.setRequestMethod("PUT");
                }
                urlOutStream = urlCon.getOutputStream();
            }
            // set the OutputStream to that obtained from the systemId
            serializer.setOutputStream(urlOutStream);
        }
        // Use this hack till Xalan support JAXP1.3
        if (fDOMSerializer == null) {
            fDOMSerializer = (DOM3Serializer) serializer.asDOM3Serializer();
        }
        // Set the error handler on the DOM3Serializer interface implementation
        if (fDOMErrorHandler != null) {
            fDOMSerializer.setErrorHandler(fDOMErrorHandler);
        }
        // Set the filter on the DOM3Serializer interface implementation
        if (fSerializerFilter != null) {
            fDOMSerializer.setNodeFilter(fSerializerFilter);
        }
        // Set the NewLine character to be used
        fDOMSerializer.setNewLine(fEndOfLine.toCharArray());
        // Serializer your DOM, where node is an org.w3c.dom.Node
        // Assuming that Xalan's serializer can serialize any type of DOM
        // node
        fDOMSerializer.serializeDOM3(nodeArg);
    } catch (LSException lse) {
        // Rethrow LSException.
        throw lse;
    } catch (RuntimeException e) {
        throw (LSException) createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
    } catch (Exception e) {
        if (fDOMErrorHandler != null) {
            fDOMErrorHandler.handleError(new DOMErrorImpl(DOMError.SEVERITY_FATAL_ERROR, e.getMessage(), null, e));
        }
        throw (LSException) createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
    }
    return true;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) LSException(org.w3c.dom.ls.LSException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) LSException(org.w3c.dom.ls.LSException) DOMException(org.w3c.dom.DOMException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) LSSerializer(org.w3c.dom.ls.LSSerializer) Serializer(org.apache.xml.serializer.Serializer) DOM3Serializer(org.apache.xml.serializer.DOM3Serializer)

Example 7 with Serializer

use of org.apache.xml.serializer.Serializer in project j2objc by google.

the class TransformerIdentityImpl method startElement.

/**
   * Receive notification of the start of an element.
   *
   * <p>By default, do nothing.  Application writers may override this
   * method in a subclass to take specific actions at the start of
   * each element (such as allocating a new tree node or writing
   * output to a file).</p>
   *
   * @param uri The Namespace URI, or the empty string if the
   *        element has no Namespace URI or if Namespace
   *        processing is not being performed.
   * @param localName The local name (without prefix), or the
   *        empty string if Namespace processing is not being
   *        performed.
   * @param qName The qualified name (with prefix), or the
   *        empty string if qualified names are not available.
   * @param attributes The specified or defaulted attributes.
   * @throws org.xml.sax.SAXException Any SAX exception, possibly
   *            wrapping another exception.
   * @see org.xml.sax.ContentHandler#startElement
   *
   * @throws SAXException
   */
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    if (!m_foundFirstElement && null != m_serializer) {
        m_foundFirstElement = true;
        Serializer newSerializer;
        try {
            newSerializer = SerializerSwitcher.switchSerializerIfHTML(uri, localName, m_outputFormat.getProperties(), m_serializer);
        } catch (TransformerException te) {
            throw new SAXException(te);
        }
        if (newSerializer != m_serializer) {
            try {
                m_resultContentHandler = newSerializer.asContentHandler();
            } catch (// why?
            IOException ioe) {
                throw new SAXException(ioe);
            }
            if (m_resultContentHandler instanceof DTDHandler)
                m_resultDTDHandler = (DTDHandler) m_resultContentHandler;
            if (m_resultContentHandler instanceof LexicalHandler)
                m_resultLexicalHandler = (LexicalHandler) m_resultContentHandler;
            m_serializer = newSerializer;
        }
    }
    flushStartDoc();
    m_resultContentHandler.startElement(uri, localName, qName, attributes);
}
Also used : LexicalHandler(org.xml.sax.ext.LexicalHandler) IOException(java.io.IOException) DTDHandler(org.xml.sax.DTDHandler) TransformerException(javax.xml.transform.TransformerException) Serializer(org.apache.xml.serializer.Serializer) SAXException(org.xml.sax.SAXException)

Example 8 with Serializer

use of org.apache.xml.serializer.Serializer in project j2objc by google.

the class TransformerImpl method transformToString.

/**
   * Take the contents of a template element, process it, and
   * convert it to a string.
   *
   * @param elem The parent element whose children will be output
   * as a string.
   *
   * @return The stringized result of executing the elements children.
   *
   * @throws TransformerException
   * @xsl.usage advanced
   */
public String transformToString(ElemTemplateElement elem) throws TransformerException {
    ElemTemplateElement firstChild = elem.getFirstChildElem();
    if (null == firstChild)
        return "";
    if (elem.hasTextLitOnly() && m_optimizer) {
        return ((ElemTextLiteral) firstChild).getNodeValue();
    }
    // Save the current result tree handler.
    SerializationHandler savedRTreeHandler = this.m_serializationHandler;
    // Create a Serializer object that will handle the SAX events 
    // and build the ResultTreeFrag nodes.
    StringWriter sw = (StringWriter) m_stringWriterObjectPool.getInstance();
    m_serializationHandler = (ToTextStream) m_textResultHandlerObjectPool.getInstance();
    if (null == m_serializationHandler) {
        // if we didn't get one from the pool, go make a new one
        Serializer serializer = org.apache.xml.serializer.SerializerFactory.getSerializer(m_textformat.getProperties());
        m_serializationHandler = (SerializationHandler) serializer;
    }
    m_serializationHandler.setTransformer(this);
    m_serializationHandler.setWriter(sw);
    String result;
    try {
        /* Don't call startDocument, the SerializationHandler  will
         * generate its own internal startDocument call anyways
         */
        // this.m_serializationHandler.startDocument();
        // Do the transformation of the child elements.
        executeChildTemplates(elem, true);
        this.m_serializationHandler.endDocument();
        result = sw.toString();
    } catch (org.xml.sax.SAXException se) {
        throw new TransformerException(se);
    } finally {
        sw.getBuffer().setLength(0);
        try {
            sw.close();
        } catch (Exception ioe) {
        }
        m_stringWriterObjectPool.freeInstance(sw);
        m_serializationHandler.reset();
        m_textResultHandlerObjectPool.freeInstance(m_serializationHandler);
        // Restore the previous result tree handler.
        m_serializationHandler = savedRTreeHandler;
    }
    return result;
}
Also used : ElemTextLiteral(org.apache.xalan.templates.ElemTextLiteral) StringWriter(java.io.StringWriter) SAXException(org.xml.sax.SAXException) SerializationHandler(org.apache.xml.serializer.SerializationHandler) ElemTemplateElement(org.apache.xalan.templates.ElemTemplateElement) TransformerException(javax.xml.transform.TransformerException) SAXNotSupportedException(org.xml.sax.SAXNotSupportedException) SAXException(org.xml.sax.SAXException) TransformerException(javax.xml.transform.TransformerException) SAXNotRecognizedException(org.xml.sax.SAXNotRecognizedException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Serializer(org.apache.xml.serializer.Serializer)

Example 9 with Serializer

use of org.apache.xml.serializer.Serializer in project j2objc by google.

the class SerializerSwitcher method switchSerializerIfHTML.

/**
   * Switch to HTML serializer if element is HTML
   *
   *
   * @param transformer Non-null transformer instance
   * @param ns Namespace URI of the element
   * @param localName Local part of name of element
   *
   * @throws TransformerException
   */
public static void switchSerializerIfHTML(TransformerImpl transformer, String ns, String localName) throws TransformerException {
    if (null == transformer)
        return;
    if (((null == ns) || (ns.length() == 0)) && localName.equalsIgnoreCase("html")) {
        // Access at level of hashtable to see if the method has been set.
        if (null != transformer.getOutputPropertyNoDefault(OutputKeys.METHOD))
            return;
        // Getting the output properties this way won't cause a clone of 
        // the properties.
        Properties prevProperties = transformer.getOutputFormat().getProperties();
        // We have to make sure we get an output properties with the proper 
        // defaults for the HTML method.  The easiest way to do this is to 
        // have the OutputProperties class do it.
        OutputProperties htmlOutputProperties = new OutputProperties(Method.HTML);
        htmlOutputProperties.copyFrom(prevProperties, true);
        Properties htmlProperties = htmlOutputProperties.getProperties();
        try {
            //        Serializer oldSerializer = transformer.getSerializer();
            Serializer oldSerializer = null;
            if (null != oldSerializer) {
                Serializer serializer = SerializerFactory.getSerializer(htmlProperties);
                Writer writer = oldSerializer.getWriter();
                if (null != writer)
                    serializer.setWriter(writer);
                else {
                    OutputStream os = oldSerializer.getOutputStream();
                    if (null != os)
                        serializer.setOutputStream(os);
                }
                //          transformer.setSerializer(serializer);
                ContentHandler ch = serializer.asContentHandler();
                transformer.setContentHandler(ch);
            }
        } catch (java.io.IOException e) {
            throw new TransformerException(e);
        }
    }
}
Also used : OutputStream(java.io.OutputStream) OutputProperties(org.apache.xalan.templates.OutputProperties) Properties(java.util.Properties) OutputProperties(org.apache.xalan.templates.OutputProperties) Writer(java.io.Writer) ContentHandler(org.xml.sax.ContentHandler) TransformerException(javax.xml.transform.TransformerException) Serializer(org.apache.xml.serializer.Serializer)

Example 10 with Serializer

use of org.apache.xml.serializer.Serializer in project j2objc by google.

the class LSSerializerImpl method write.

/** 
     * Serializes the specified node to the specified LSOutput and returns true if the Node 
     * was successfully serialized. 
     * 
     * @see org.w3c.dom.ls.LSSerializer#write(org.w3c.dom.Node, org.w3c.dom.ls.LSOutput)
     * @since DOM Level 3
     * @param nodeArg The Node to serialize.
     * @throws org.w3c.dom.ls.LSException SERIALIZE_ERR: Raised if the 
     * LSSerializer was unable to serialize the node.
     *      
     */
public boolean write(Node nodeArg, LSOutput destination) throws LSException {
    // If the destination is null
    if (destination == null) {
        String msg = Utils.messages.createMessage(MsgKey.ER_NO_OUTPUT_SPECIFIED, null);
        if (fDOMErrorHandler != null) {
            fDOMErrorHandler.handleError(new DOMErrorImpl(DOMError.SEVERITY_FATAL_ERROR, msg, MsgKey.ER_NO_OUTPUT_SPECIFIED));
        }
        throw new LSException(LSException.SERIALIZE_ERR, msg);
    }
    // If nodeArg is null, return false.  Should we throw and LSException instead?
    if (nodeArg == null) {
        return false;
    }
    // Obtain a reference to the serializer to use
    // Serializer serializer = getXMLSerializer(xmlVersion);
    Serializer serializer = fXMLSerializer;
    serializer.reset();
    // If the node has not been seen
    if (nodeArg != fVisitedNode) {
        // Determine the XML Document version of the Node 
        String xmlVersion = getXMLVersion(nodeArg);
        // Determine the encoding: 1.LSOutput.encoding, 2.Document.inputEncoding, 3.Document.xmlEncoding. 
        fEncoding = destination.getEncoding();
        if (fEncoding == null) {
            fEncoding = getInputEncoding(nodeArg);
            fEncoding = fEncoding != null ? fEncoding : getXMLEncoding(nodeArg) == null ? "UTF-8" : getXMLEncoding(nodeArg);
        }
        // Note: The serializer defaults to UTF-8 when created
        if (!Encodings.isRecognizedEncoding(fEncoding)) {
            String msg = Utils.messages.createMessage(MsgKey.ER_UNSUPPORTED_ENCODING, null);
            if (fDOMErrorHandler != null) {
                fDOMErrorHandler.handleError(new DOMErrorImpl(DOMError.SEVERITY_FATAL_ERROR, msg, MsgKey.ER_UNSUPPORTED_ENCODING));
            }
            throw new LSException(LSException.SERIALIZE_ERR, msg);
        }
        serializer.getOutputFormat().setProperty("version", xmlVersion);
        // Set the output encoding and xml version properties
        fDOMConfigProperties.setProperty(DOMConstants.S_XERCES_PROPERTIES_NS + DOMConstants.S_XML_VERSION, xmlVersion);
        fDOMConfigProperties.setProperty(DOMConstants.S_XSL_OUTPUT_ENCODING, fEncoding);
        // serialized.
        if ((nodeArg.getNodeType() != Node.DOCUMENT_NODE || nodeArg.getNodeType() != Node.ELEMENT_NODE || nodeArg.getNodeType() != Node.ENTITY_NODE) && ((fFeatures & XMLDECL) != 0)) {
            fDOMConfigProperties.setProperty(DOMConstants.S_XSL_OUTPUT_OMIT_XML_DECL, DOMConstants.DOM3_DEFAULT_FALSE);
        }
        fVisitedNode = nodeArg;
    }
    // Update the serializer properties
    fXMLSerializer.setOutputFormat(fDOMConfigProperties);
    // 
    try {
        // The LSSerializer will use the LSOutput object to determine 
        // where to serialize the output to in the following order the  
        // first one that is not null and not an empty string will be    
        // used: 1.LSOutput.characterStream, 2.LSOutput.byteStream,   
        // 3. LSOutput.systemId 
        // 1.LSOutput.characterStream
        Writer writer = destination.getCharacterStream();
        if (writer == null) {
            // 2.LSOutput.byteStream
            OutputStream outputStream = destination.getByteStream();
            if (outputStream == null) {
                // 3. LSOutput.systemId
                String uri = destination.getSystemId();
                if (uri == null) {
                    String msg = Utils.messages.createMessage(MsgKey.ER_NO_OUTPUT_SPECIFIED, null);
                    if (fDOMErrorHandler != null) {
                        fDOMErrorHandler.handleError(new DOMErrorImpl(DOMError.SEVERITY_FATAL_ERROR, msg, MsgKey.ER_NO_OUTPUT_SPECIFIED));
                    }
                    throw new LSException(LSException.SERIALIZE_ERR, msg);
                } else {
                    // Expand the System Id and obtain an absolute URI for it.
                    String absoluteURI = SystemIDResolver.getAbsoluteURI(uri);
                    URL url = new URL(absoluteURI);
                    OutputStream urlOutStream = null;
                    String protocol = url.getProtocol();
                    String host = url.getHost();
                    // lower case in scheme names (e.g., allow "HTTP" as well as "http").
                    if (protocol.equalsIgnoreCase("file") && (host == null || host.length() == 0 || host.equals("localhost"))) {
                        // do we also need to check for host.equals(hostname)
                        urlOutStream = new FileOutputStream(getPathWithoutEscapes(url.getPath()));
                    } else {
                        // This should support URL's whose schemes are mentioned in 
                        // RFC1738 other than file
                        URLConnection urlCon = url.openConnection();
                        urlCon.setDoInput(false);
                        urlCon.setDoOutput(true);
                        urlCon.setUseCaches(false);
                        urlCon.setAllowUserInteraction(false);
                        // When writing to a HTTP URI, a HTTP PUT is performed.
                        if (urlCon instanceof HttpURLConnection) {
                            HttpURLConnection httpCon = (HttpURLConnection) urlCon;
                            httpCon.setRequestMethod("PUT");
                        }
                        urlOutStream = urlCon.getOutputStream();
                    }
                    // set the OutputStream to that obtained from the systemId
                    serializer.setOutputStream(urlOutStream);
                }
            } else {
                // 2.LSOutput.byteStream
                serializer.setOutputStream(outputStream);
            }
        } else {
            // 1.LSOutput.characterStream
            serializer.setWriter(writer);
        }
        // Use this hack till Xalan support JAXP1.3
        if (fDOMSerializer == null) {
            fDOMSerializer = (DOM3Serializer) serializer.asDOM3Serializer();
        }
        // Set the error handler on the DOM3Serializer interface implementation
        if (fDOMErrorHandler != null) {
            fDOMSerializer.setErrorHandler(fDOMErrorHandler);
        }
        // Set the filter on the DOM3Serializer interface implementation
        if (fSerializerFilter != null) {
            fDOMSerializer.setNodeFilter(fSerializerFilter);
        }
        // Set the NewLine character to be used
        fDOMSerializer.setNewLine(fEndOfLine.toCharArray());
        // Serializer your DOM, where node is an org.w3c.dom.Node
        // Assuming that Xalan's serializer can serialize any type of DOM node
        fDOMSerializer.serializeDOM3(nodeArg);
    } catch (UnsupportedEncodingException ue) {
        String msg = Utils.messages.createMessage(MsgKey.ER_UNSUPPORTED_ENCODING, null);
        if (fDOMErrorHandler != null) {
            fDOMErrorHandler.handleError(new DOMErrorImpl(DOMError.SEVERITY_FATAL_ERROR, msg, MsgKey.ER_UNSUPPORTED_ENCODING, ue));
        }
        throw (LSException) createLSException(LSException.SERIALIZE_ERR, ue).fillInStackTrace();
    } catch (LSException lse) {
        // Rethrow LSException.
        throw lse;
    } catch (RuntimeException e) {
        throw (LSException) createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
    } catch (Exception e) {
        if (fDOMErrorHandler != null) {
            fDOMErrorHandler.handleError(new DOMErrorImpl(DOMError.SEVERITY_FATAL_ERROR, e.getMessage(), null, e));
        }
        throw (LSException) createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
    }
    return true;
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) LSException(org.w3c.dom.ls.LSException) DOMException(org.w3c.dom.DOMException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpURLConnection(java.net.HttpURLConnection) FileOutputStream(java.io.FileOutputStream) LSException(org.w3c.dom.ls.LSException) StringWriter(java.io.StringWriter) Writer(java.io.Writer) LSSerializer(org.w3c.dom.ls.LSSerializer) Serializer(org.apache.xml.serializer.Serializer) DOM3Serializer(org.apache.xml.serializer.DOM3Serializer)

Aggregations

Serializer (org.apache.xml.serializer.Serializer)16 OutputStream (java.io.OutputStream)8 TransformerException (javax.xml.transform.TransformerException)8 IOException (java.io.IOException)6 StringWriter (java.io.StringWriter)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 Writer (java.io.Writer)6 DOM3Serializer (org.apache.xml.serializer.DOM3Serializer)6 DOMException (org.w3c.dom.DOMException)6 LSException (org.w3c.dom.ls.LSException)6 LSSerializer (org.w3c.dom.ls.LSSerializer)6 FileOutputStream (java.io.FileOutputStream)4 HttpURLConnection (java.net.HttpURLConnection)4 URL (java.net.URL)4 URLConnection (java.net.URLConnection)4 Properties (java.util.Properties)4 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)4 OutputProperties (org.apache.xalan.templates.OutputProperties)4 DTDHandler (org.xml.sax.DTDHandler)4 SAXException (org.xml.sax.SAXException)4