serializerbase.java

来自「JAVA 所有包」· Java 代码 · 共 1,384 行 · 第 1/3 页

JAVA
1,384
字号
/* * 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: SerializerBase.java,v 1.5 2006/04/14 12:09:19 sunithareddy Exp $ */package com.sun.org.apache.xml.internal.serializer;import java.io.IOException;import java.util.Vector;import javax.xml.transform.SourceLocator;import javax.xml.transform.Transformer;import com.sun.org.apache.xml.internal.serializer.utils.MsgKey;import com.sun.org.apache.xml.internal.serializer.utils.Utils;import org.xml.sax.Attributes;import org.xml.sax.ContentHandler;import org.xml.sax.Locator;import org.xml.sax.SAXException;import org.xml.sax.SAXParseException;import org.xml.sax.ext.Locator2;/** * This class acts as a base class for the XML "serializers" * and the stream serializers. * It contains a number of common fields and methods. *  * @xsl.usage internal */public abstract class SerializerBase    implements SerializationHandler, SerializerConstants{        /**     * To fire off the end element trace event     * @param name Name of element     */    protected void fireEndElem(String name)        throws org.xml.sax.SAXException    {        if (m_tracer != null)        {            flushMyWriter();            m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_ENDELEMENT,name, (Attributes)null);        }     	        	    	    }    /**     * Report the characters trace event     * @param chars  content of characters     * @param start  starting index of characters to output     * @param length  number of characters to output     */    protected void fireCharEvent(char[] chars, int start, int length)        throws org.xml.sax.SAXException    {        if (m_tracer != null)        {            flushMyWriter();            m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CHARACTERS, chars, start,length);        }     	        	    	    }    /**     * true if we still need to call startDocumentInternal() 	 */    protected boolean m_needToCallStartDocument = true;     /** True if a trailing "]]>" still needs to be written to be     * written out. Used to merge adjacent CDATA sections     */    protected boolean m_cdataTagOpen = false;    /**     * All the attributes of the current element, collected from     * startPrefixMapping() calls, or addAddtribute() calls, or      * from the SAX attributes in a startElement() call.     */    protected AttributesImplSerializer m_attributes = new AttributesImplSerializer();    /**     * Tells if we're in an EntityRef event.     */    protected boolean m_inEntityRef = false;    /** This flag is set while receiving events from the external DTD */    protected boolean m_inExternalDTD = false;    /**     * The System ID for the doc type.     */    private String m_doctypeSystem;    /**     * The public ID for the doc type.     */    private String m_doctypePublic;    /**     * Flag to tell that we need to add the doctype decl, which we can't do     * until the first element is encountered.     */    boolean m_needToOutputDocTypeDecl = true;    /**     * The character encoding.  Must match the encoding used for the     * printWriter.     */    private String m_encoding = null;    /**     * Tells if we should write the XML declaration.     */    private boolean m_shouldNotWriteXMLHeader = false;    /**     * The standalone value for the doctype.     */    private String m_standalone;    /**     * True if standalone was specified.     */    protected boolean m_standaloneWasSpecified = false;    /**     * Flag to tell if indenting (pretty-printing) is on.     */    protected boolean m_doIndent = false;    /**     * Amount to indent.     */    protected int m_indentAmount = 0;    /**     * Tells the XML version, for writing out to the XML decl.     */    private String m_version = null;    /**     * The mediatype.  Not used right now.     */    private String m_mediatype;    /**     * The transformer that was around when this output handler was created (if     * any).     */    private Transformer m_transformer;    /**      * Pairs of local names and corresponding URIs of CDATA sections. This list     * comes from the cdata-section-elements attribute. Every second one is a     * local name, and every other second one is the URI for the local name.      */    protected Vector m_cdataSectionElements = null;    /**     * Namespace support, that keeps track of currently defined      * prefix/uri mappings. As processed elements come and go, so do     * the associated mappings for that element.     */    protected NamespaceMappings m_prefixMap;        /**     * Handle for firing generate events.  This interface may be implemented     * by the referenced transformer object.     */    protected SerializerTrace m_tracer;        protected SourceLocator m_sourceLocator;        /**     * The writer to send output to. This field is only used in the ToStream     * serializers, but exists here just so that the fireStartDoc() and     * other fire... methods can flush this writer when tracing.     */    protected java.io.Writer m_writer = null;        /**     * A reference to "stack frame" corresponding to     * the current element. Such a frame is pushed at a startElement()     * and popped at an endElement(). This frame contains information about     * the element, such as its namespace URI.      */    protected ElemContext m_elemContext = new ElemContext();        /**     * A utility buffer for converting Strings passed to     * character() methods to character arrays.     * Reusing this buffer means not creating a new character array     * everytime and it runs faster.     */    protected char[] m_charsBuff = new char[60];        /**     * A utility buffer for converting Strings passed to     * attribute methods to character arrays.     * Reusing this buffer means not creating a new character array     * everytime and it runs faster.     */    protected char[] m_attrBuff = new char[30];        private Locator m_locator = null;        protected boolean m_needToCallSetDocumentInfo = true;        /**     * Receive notification of a comment.     *      * @see ExtendedLexicalHandler#comment(String)     */    public void comment(String data) throws SAXException    {        final int length = data.length();        if (length > m_charsBuff.length)        {            m_charsBuff = new char[length * 2 + 1];        }        data.getChars(0, length, m_charsBuff, 0);        comment(m_charsBuff, 0, length);    }    /**     * If at runtime, when the qname of the attribute is     * known, another prefix is specified for the attribute, then we can     * patch or hack the name with this method. For     * a qname of the form "ns?:otherprefix:name", this function patches the     * qname by simply ignoring "otherprefix".     * TODO: This method is a HACK! We do not have access to the     * XML file, it sometimes generates a NS prefix of the form "ns?" for     * an attribute.     */    protected String patchName(String qname)    {                final int lastColon = qname.lastIndexOf(':');        if (lastColon > 0) {            final int firstColon = qname.indexOf(':');            final String prefix = qname.substring(0, firstColon);            final String localName = qname.substring(lastColon + 1);        // If uri is "" then ignore prefix            final String uri = m_prefixMap.lookupNamespace(prefix);            if (uri != null && uri.length() == 0) {                return localName;            }            else if (firstColon != lastColon) {                return prefix + ':' + localName;            }        }        return qname;            }    /**     * Returns the local name of a qualified name. If the name has no prefix,     * then it works as the identity (SAX2).     * @param qname the qualified name      * @return the name, but excluding any prefix and colon.     */    protected static String getLocalName(String qname)    {        final int col = qname.lastIndexOf(':');        return (col > 0) ? qname.substring(col + 1) : qname;    }    /**     * Receive an object for locating the origin of SAX document events.     *     * @param locator An object that can return the location of any SAX document     * event.     *      * Receive an object for locating the origin of SAX document events.     *     * <p>SAX parsers are strongly encouraged (though not absolutely     * required) to supply a locator: if it does so, it must supply     * the locator to the application by invoking this method before     * invoking any of the other methods in the DocumentHandler     * interface.</p>     *     * <p>The locator allows the application to determine the end     * position of any document-related event, even if the parser is     * not reporting an error.  Typically, the application will     * use this information for reporting its own errors (such as     * character content that does not match an application's     * business rules).  The information returned by the locator     * is probably not sufficient for use with a search engine.</p>     *     * <p>Note that the locator will return correct information only     * during the invocation of the events in this interface.  The     * application should not attempt to use it at any other time.</p>     */    public void setDocumentLocator(Locator locator)    {        m_locator = locator;    }    /**     * Adds the given attribute to the set of collected attributes , but only if     * there is a currently open element.     *      * An element is currently open if a startElement() notification has     * occured but the start of the element has not yet been written to the     * output.  In the stream case this means that we have not yet been forced     * to close the elements opening tag by another notification, such as a     * character notification.     *      * @param uri the URI of the attribute     * @param localName the local name of the attribute     * @param rawName    the qualified name of the attribute     * @param type the type of the attribute (probably CDATA)     * @param value the value of the attribute     * @param XSLAttribute true if this attribute is coming from an xsl:attriute element     * @see ExtendedContentHandler#addAttribute(String, String, String, String, String)     */    public void addAttribute(        String uri,        String localName,        String rawName,        String type,        String value,        boolean XSLAttribute)        throws SAXException    {        if (m_elemContext.m_startTagOpen)        {            addAttributeAlways(uri, localName, rawName, type, value, XSLAttribute);        }    }        /**     * Adds the given attribute to the set of attributes, even if there is     * no currently open element. This is useful if a SAX startPrefixMapping()     * should need to add an attribute before the element name is seen.     *      * @param uri the URI of the attribute     * @param localName the local name of the attribute     * @param rawName   the qualified name of the attribute     * @param type the type of the attribute (probably CDATA)     * @param value the value of the attribute     * @param XSLAttribute true if this attribute is coming from an xsl:attribute element     * @return true if the attribute was added,      * false if an existing value was replaced.     */    public boolean addAttributeAlways(        String uri,        String localName,        String rawName,        String type,        String value,        boolean XSLAttribute)    {        boolean was_added;//            final int index =//                (localName == null || uri == null) ?//                m_attributes.getIndex(rawName):m_attributes.getIndex(uri, localName);                    int index;//            if (localName == null || uri == null){//                index = m_attributes.getIndex(rawName);//            }//            else {//                index = m_attributes.getIndex(uri, localName);//            }                        if (localName == null || uri == null || uri.length() == 0)                index = m_attributes.getIndex(rawName);            else {                index = m_attributes.getIndex(uri,localName);            }            if (index >= 0)            {                /* We've seen the attribute before.                 * We may have a null uri or localName, but all                 * we really want to re-set is the value anyway.                 */                m_attributes.setValue(index,value);                was_added = false;            }            else            {                // the attribute doesn't exist yet, create it                m_attributes.addAttribute(uri, localName, rawName, type, value);                was_added = true;            }            return was_added;            }      /**     *  Adds  the given attribute to the set of collected attributes,      * but only if there is a currently open element.     *     * @param name the attribute's qualified name     * @param value the value of the attribute     */    public void addAttribute(String name, final String value)    {        if (m_elemContext.m_startTagOpen)        {            final String patchedName = patchName(name);            final String localName = getLocalName(patchedName);            final String uri = getNamespaceURI(patchedName, false);            addAttributeAlways(uri,localName, patchedName, "CDATA", value, false);         }    }        /**     * Adds the given xsl:attribute to the set of collected attributes,      * but only if there is a currently open element.     *     * @param name the attribute's qualified name (prefix:localName)     * @param value the value of the attribute     * @param uri the URI that the prefix of the name points to     */    public void addXSLAttribute(String name, final String value, final String uri)    {        if (m_elemContext.m_startTagOpen)        {            final String patchedName = patchName(name);            final String localName = getLocalName(patchedName);            addAttributeAlways(uri,localName, patchedName, "CDATA", value, true);         }    }     /**     * Add the given attributes to the currently collected ones. These     * attributes are always added, regardless of whether on not an element     * is currently open.     * @param atts List of attributes to add to this list     */    public void addAttributes(Attributes atts) throws SAXException    {        int nAtts = atts.getLength();        for (int i = 0; i < nAtts; i++)        {            String uri = atts.getURI(i);            if (null == uri)                uri = "";

⌨️ 快捷键说明

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