tostream.java

来自「JAVA 所有包」· Java 代码 · 共 2,016 行 · 第 1/5 页

JAVA
2,016
字号
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//* * $Id: ToStream.java,v 1.4 2005/11/10 06:43:26 suresh_emailid Exp $ */package com.sun.org.apache.xml.internal.serializer;import java.io.IOException;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.io.Writer;import java.util.Properties;import java.util.StringTokenizer;import java.util.Vector;import javax.xml.transform.ErrorListener;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerException;import com.sun.org.apache.xml.internal.serializer.utils.MsgKey;import com.sun.org.apache.xml.internal.serializer.utils.Utils;import com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException;import org.w3c.dom.Node;import org.xml.sax.Attributes;import org.xml.sax.ContentHandler;import org.xml.sax.SAXException;//import com.sun.media.sound.IESecurity;/** * This abstract class is a base class for other stream  * serializers (xml, html, text ...) that write output to a stream. *  * @xsl.usage internal */abstract public class ToStream extends SerializerBase{    private static final String COMMENT_BEGIN = "<!--";    private static final String COMMENT_END = "-->";    /** Stack to keep track of disabling output escaping. */    protected BoolStack m_disableOutputEscapingStates = new BoolStack();    /**     * The encoding information associated with this serializer.     * Although initially there is no encoding,     * there is a dummy EncodingInfo object that will say     * that every character is in the encoding. This is useful     * for a serializer that is in temporary output state and has     * no associated encoding. A serializer in final output state     * will have an encoding, and will worry about whether      * single chars or surrogate pairs of high/low chars form     * characters in the output encoding.      */    EncodingInfo m_encodingInfo = new EncodingInfo(null,null);        /**     * Method reference to the sun.io.CharToByteConverter#canConvert method     * for this encoding.  Invalid if m_charToByteConverter is null.     */    java.lang.reflect.Method m_canConvertMeth;    /**     * Boolean that tells if we already tried to get the converter.     */    boolean m_triedToGetConverter = false;    /**     * Opaque reference to the sun.io.CharToByteConverter for this     * encoding.     */    Object m_charToByteConverter = null;      /**     * Stack to keep track of whether or not we need to     * preserve whitespace.     *      * Used to push/pop values used for the field m_ispreserve, but     * m_ispreserve is only relevant if m_doIndent is true.     * If m_doIndent is false this field has no impact.     *      */    protected BoolStack m_preserves = new BoolStack();    /**     * State flag to tell if preservation of whitespace     * is important.      *      * Used only in shouldIndent() but only if m_doIndent is true.     * If m_doIndent is false this flag has no impact.     *      */    protected boolean m_ispreserve = false;    /**     * State flag that tells if the previous node processed     * was text, so we can tell if we should preserve whitespace.     *      * Used in endDocument() and shouldIndent() but     * only if m_doIndent is true.      * If m_doIndent is false this flag has no impact.     */    protected boolean m_isprevtext = false;    /**     * The maximum character size before we have to resort     * to escaping.     */    protected int m_maxCharacter = Encodings.getLastPrintable();    /**     * The system line separator for writing out line breaks.     * The default value is from the system property,     * but this value can be set through the xsl:output     * extension attribute xalan:line-separator.     */    protected char[] m_lineSep =        System.getProperty("line.separator").toCharArray();            /**     * True if the the system line separator is to be used.     */        protected boolean m_lineSepUse = true;        /**     * The length of the line seperator, since the write is done     * one character at a time.     */    protected int m_lineSepLen = m_lineSep.length;    /**     * Map that tells which characters should have special treatment, and it     *  provides character to entity name lookup.     */    protected CharInfo m_charInfo;    /** True if we control the buffer, and we should flush the output on endDocument. */    boolean m_shouldFlush = true;    /**     * Add space before '/>' for XHTML.     */    protected boolean m_spaceBeforeClose = false;    /**     * Flag to signal that a newline should be added.     *      * Used only in indent() which is called only if m_doIndent is true.     * If m_doIndent is false this flag has no impact.     */    boolean m_startNewLine;    /**     * Tells if we're in an internal document type subset.     */    protected boolean m_inDoctype = false;    /**       * Flag to quickly tell if the encoding is UTF8.       */    boolean m_isUTF8 = false;    /** The xsl:output properties. */    protected Properties m_format;    /**     * remembers if we are in between the startCDATA() and endCDATA() callbacks     */    protected boolean m_cdataStartCalled = false;        /**     * If this flag is true DTD entity references are not left as-is,     * which is exiting older behavior.     */    private boolean m_expandDTDEntities = true;      /**     * Default constructor     */    public ToStream()    {    }    /**     * This helper method to writes out "]]>" when closing a CDATA section.     *     * @throws org.xml.sax.SAXException     */    protected void closeCDATA() throws org.xml.sax.SAXException    {        try        {            m_writer.write(CDATA_DELIMITER_CLOSE);            // write out a CDATA section closing "]]>"            m_cdataTagOpen = false; // Remember that we have done so.        }        catch (IOException e)        {            throw new SAXException(e);        }    }    /**     * Serializes the DOM node. Throws an exception only if an I/O     * exception occured while serializing.     *     * @param node Node to serialize.     * @throws IOException An I/O exception occured while serializing     */    public void serialize(Node node) throws IOException    {        try        {            TreeWalker walker =                new TreeWalker(this);            walker.traverse(node);        }        catch (org.xml.sax.SAXException se)        {            throw new WrappedRuntimeException(se);        }    }    /**     * Return true if the character is the high member of a surrogate pair.     *     * NEEDSDOC @param c     *     * NEEDSDOC ($objectName$) @return     */    static final boolean isUTF16Surrogate(char c)    {        return (c & 0xFC00) == 0xD800;    }    /**     * Taken from XSLTC      */    private boolean m_escaping = true;    /**     * Flush the formatter's result stream.     *     * @throws org.xml.sax.SAXException     */    protected final void flushWriter() throws org.xml.sax.SAXException    {        final java.io.Writer writer = m_writer;        if (null != writer)        {            try            {                if (writer instanceof WriterToUTF8Buffered)                {                    if (m_shouldFlush)                         ((WriterToUTF8Buffered) writer).flush();                    else                         ((WriterToUTF8Buffered) writer).flushBuffer();                }                if (writer instanceof WriterToASCI)                {                    if (m_shouldFlush)                        writer.flush();                }                else                {                    // Flush always.                     // Not a great thing if the writer was created                     // by this class, but don't have a choice.                    writer.flush();                }            }            catch (IOException ioe)            {                throw new org.xml.sax.SAXException(ioe);            }        }    }    /**     * Get the output stream where the events will be serialized to.     *     * @return reference to the result stream, or null of only a writer was     * set.     */    public OutputStream getOutputStream()    {        if (m_writer instanceof WriterToUTF8Buffered)            return ((WriterToUTF8Buffered) m_writer).getOutputStream();        if (m_writer instanceof WriterToASCI)            return ((WriterToASCI) m_writer).getOutputStream();        else            return null;    }    // Implement DeclHandler    /**     *   Report an element type declaration.     *       *   <p>The content model will consist of the string "EMPTY", the     *   string "ANY", or a parenthesised group, optionally followed     *   by an occurrence indicator.  The model will be normalized so     *   that all whitespace is removed,and will include the enclosing     *   parentheses.</p>     *       *   @param name The element type name.     *   @param model The content model as a normalized string.     *   @exception SAXException The application may raise an exception.     */    public void elementDecl(String name, String model) throws SAXException    {        // Do not inline external DTD        if (m_inExternalDTD)            return;        try        {            final java.io.Writer writer = m_writer;            DTDprolog();            writer.write("<!ELEMENT ");            writer.write(name);            writer.write(' ');            writer.write(model);            writer.write('>');            writer.write(m_lineSep, 0, m_lineSepLen);        }        catch (IOException e)        {            throw new SAXException(e);        }    }    /**     * Report an internal entity declaration.     *     * <p>Only the effective (first) declaration for each entity     * will be reported.</p>     *     * @param name The name of the entity.  If it is a parameter     *        entity, the name will begin with '%'.     * @param value The replacement text of the entity.     * @exception SAXException The application may raise an exception.     * @see #externalEntityDecl     * @see org.xml.sax.DTDHandler#unparsedEntityDecl     */    public void internalEntityDecl(String name, String value)        throws SAXException    {        // Do not inline external DTD        if (m_inExternalDTD)            return;        try        {            DTDprolog();            outputEntityDecl(name, value);        }        catch (IOException e)        {            throw new SAXException(e);        }    }    /**     * Output the doc type declaration.     *     * @param name non-null reference to document type name.     * NEEDSDOC @param value     *     * @throws org.xml.sax.SAXException     */    void outputEntityDecl(String name, String value) throws IOException    {        final java.io.Writer writer = m_writer;        writer.write("<!ENTITY ");        writer.write(name);        writer.write(" \"");

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?