serializerbase.java

来自「JAVA的一些源码 JAVA2 STANDARD EDITION DEVELO」· Java 代码 · 共 1,289 行 · 第 1/3 页

JAVA
1,289
字号
/* * 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.1.2.2 2006/09/27 18:40:59 spericas Exp $ */package com.sun.org.apache.xml.internal.serializer;import java.io.IOException;import java.util.Hashtable;import java.util.Stack;import java.util.Vector;import javax.xml.transform.SourceLocator;import javax.xml.transform.Transformer;import com.sun.org.apache.xml.internal.res.XMLErrorResources;import com.sun.org.apache.xml.internal.res.XMLMessages;import com.sun.org.apache.xml.internal.utils.BoolStack;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 javax.xml.XMLConstants;/** * This class acts as a base class for the XML "serializers" * and the stream serializers. * It contains a number of common fields and methods. * @author Santiago Pericas-Geertsen * @author G. Todd Miller  */abstract public class SerializerBase    implements SerializationHandler, SerializerConstants, com.sun.org.apache.xml.internal.dtm.ref.dom2dtm.DOM2DTM.CharacterNodeHandler{        /**     * 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];        /**     * Receive notification of a comment.     *      * @see com.sun.org.apache.xml.internal.serializer.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);    }    /**      * TODO: This method is a HACK! Since XSLTC does not have access to the      * XML file, it sometimes generates a NS prefix of the form "ns?" for      * an attribute. If at runtime, when the qname of the attribute is      * known, another prefix is specified for the attribute, then we can get      * a qname of the form "ns?:otherprefix:name". This function patches the      * qname by simply ignoring "otherprefix".      */    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)    {        return;        // I don't do anything with this yet.    }    /**     * 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     * @see com.sun.org.apache.xml.internal.serializer.ExtendedContentHandler#addAttribute(String, String, String, String, String)     */    public void addAttribute(        String uri,        String localName,        String rawName,        String type,        String value)        throws SAXException    {        if (m_elemContext.m_startTagOpen)        {            addAttributeAlways(uri, localName, rawName, type, value);        }    }        /**     * 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     */    public void addAttributeAlways(        String uri,        String localName,        String rawName,        String type,        String value)    {//            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);//            }            index = m_attributes.getIndex(rawName);            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);            }            else            {                // the attribute doesn't exist yet, create it                m_attributes.addAttribute(uri, localName, rawName, type, value);            }            }      /**     *  Adds  the given attribute to the set of collected attributes,      * but only if there is a currently open element.  This method is only     * called by XSLTC.     *     * @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);         }    }        /**     * Add the given attributes to the currently collected ones. These     * attributes are always added, regardless of whether on not an element     * is currently open.     *     * When the SAX feature http://xml.org/sax/features/namespace-prefixes     * is enabled, a SAX parser can report ns decls as attributes in the ""     * namespace. Since ns decls are handled via startPrefixMapping and     * endPrefixMapping they should be ignored here.     *     * @param atts List of attributes to add to this list     */    public void addAttributes(Attributes atts) throws SAXException    {        int nAtts = atts.getLength();

⌨️ 快捷键说明

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