feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,430 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.util.xml.impl;
import jdk.internal.org.xml.sax.Attributes;
public class Attrs implements Attributes {
/**
* Attributes string array. Each individual attribute is represented by four
* strings: namespace URL(+0), qname(+1), local name(+2), value(+3),
* type(+4), declared["d"] and default["D"](+5). In order to find attribute
* by the attrubute index, the attribute index MUST be multiplied by 8. The
* result will point to the attribute namespace URL.
*/
/* pkg */ String[] mItems;
/**
* Number of attributes in the attributes string array.
*/
private char mLength;
/**
* current index
*/
private char mAttrIdx = 0;
/**
* Constructor.
*/
public Attrs() {
// The default number of attributies capacity is 8.
mItems = new String[(8 << 3)];
}
/**
* Sets up the number of attributes and ensure the capacity of the attribute
* string array.
*
* @param length The number of attributes in the object.
*/
public void setLength(char length) {
if (length > ((char) (mItems.length >> 3))) {
mItems = new String[length << 3];
}
mLength = length;
}
/**
* Return the number of attributes in the list.
*
* <p>Once you know the number of attributes, you can iterate through the
* list.</p>
*
* @return The number of attributes in the list.
* @see #getURI(int)
* @see #getLocalName(int)
* @see #getQName(int)
* @see #getType(int)
* @see #getValue(int)
*/
public int getLength() {
return mLength;
}
/**
* Look up an attribute's Namespace URI by index.
*
* @param index The attribute index (zero-based).
* @return The Namespace URI, or the empty string if none is available, or
* null if the index is out of range.
* @see #getLength
*/
public String getURI(int index) {
return ((index >= 0) && (index < mLength))
? (mItems[index << 3])
: null;
}
/**
* Look up an attribute's local name by index.
*
* @param index The attribute index (zero-based).
* @return The local name, or the empty string if Namespace processing is
* not being performed, or null if the index is out of range.
* @see #getLength
*/
public String getLocalName(int index) {
return ((index >= 0) && (index < mLength))
? (mItems[(index << 3) + 2])
: null;
}
/**
* Look up an attribute's XML 1.0 qualified name by index.
*
* @param index The attribute index (zero-based).
* @return The XML 1.0 qualified name, or the empty string if none is
* available, or null if the index is out of range.
* @see #getLength
*/
public String getQName(int index) {
if ((index < 0) || (index >= mLength)) {
return null;
}
return mItems[(index << 3) + 1];
}
/**
* Look up an attribute's type by index.
*
* <p>The attribute type is one of the strings "CDATA", "ID", "IDREF",
* "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", or "NOTATION"
* (always in upper case).</p>
*
* <p>If the parser has not read a declaration for the attribute, or if the
* parser does not report attribute types, then it must return the value
* "CDATA" as stated in the XML 1.0 Recommentation (clause 3.3.3,
* "Attribute-Value Normalization").</p>
*
* <p>For an enumerated attribute that is not a notation, the parser will
* report the type as "NMTOKEN".</p>
*
* @param index The attribute index (zero-based).
* @return The attribute's type as a string, or null if the index is out of
* range.
* @see #getLength
*/
public String getType(int index) {
return ((index >= 0) && (index < (mItems.length >> 3)))
? (mItems[(index << 3) + 4])
: null;
}
/**
* Look up an attribute's value by index.
*
* <p>If the attribute value is a list of tokens (IDREFS, ENTITIES, or
* NMTOKENS), the tokens will be concatenated into a single string with each
* token separated by a single space.</p>
*
* @param index The attribute index (zero-based).
* @return The attribute's value as a string, or null if the index is out of
* range.
* @see #getLength
*/
public String getValue(int index) {
return ((index >= 0) && (index < mLength))
? (mItems[(index << 3) + 3])
: null;
}
/**
* Look up the index of an attribute by Namespace name.
*
* @param uri The Namespace URI, or the empty string if the name has no
* Namespace URI.
* @param localName The attribute's local name.
* @return The index of the attribute, or -1 if it does not appear in the
* list.
*/
public int getIndex(String uri, String localName) {
char len = mLength;
for (char idx = 0; idx < len; idx++) {
if ((mItems[idx << 3]).equals(uri)
&& mItems[(idx << 3) + 2].equals(localName)) {
return idx;
}
}
return -1;
}
/**
* Look up the index of an attribute by Namespace name.
*
* @param uri The Namespace URI, or the empty string if the name has no
* Namespace URI. <code>null</code> value enforce the search by the local
* name only.
* @param localName The attribute's local name.
* @return The index of the attribute, or -1 if it does not appear in the
* list.
*/
/* pkg */ int getIndexNullNS(String uri, String localName) {
char len = mLength;
if (uri != null) {
for (char idx = 0; idx < len; idx++) {
if ((mItems[idx << 3]).equals(uri)
&& mItems[(idx << 3) + 2].equals(localName)) {
return idx;
}
}
} else {
for (char idx = 0; idx < len; idx++) {
if (mItems[(idx << 3) + 2].equals(localName)) {
return idx;
}
}
}
return -1;
}
/**
* Look up the index of an attribute by XML 1.0 qualified name.
*
* @param qName The qualified (prefixed) name.
* @return The index of the attribute, or -1 if it does not appear in the
* list.
*/
public int getIndex(String qName) {
char len = mLength;
for (char idx = 0; idx < len; idx++) {
if (mItems[(idx << 3) + 1].equals(qName)) {
return idx;
}
}
return -1;
}
/**
* Look up an attribute's type by Namespace name.
*
* <p>See {@link #getType(int) getType(int)} for a description of the
* possible types.</p>
*
* @param uri The Namespace URI, or the empty String if the name has no
* Namespace URI.
* @param localName The local name of the attribute.
* @return The attribute type as a string, or null if the attribute is not
* in the list or if Namespace processing is not being performed.
*/
public String getType(String uri, String localName) {
int idx = getIndex(uri, localName);
return (idx >= 0) ? (mItems[(idx << 3) + 4]) : null;
}
/**
* Look up an attribute's type by XML 1.0 qualified name.
*
* <p>See {@link #getType(int) getType(int)} for a description of the
* possible types.</p>
*
* @param qName The XML 1.0 qualified name.
* @return The attribute type as a string, or null if the attribute is not
* in the list or if qualified names are not available.
*/
public String getType(String qName) {
int idx = getIndex(qName);
return (idx >= 0) ? (mItems[(idx << 3) + 4]) : null;
}
/**
* Look up an attribute's value by Namespace name.
*
* <p>See {@link #getValue(int) getValue(int)} for a description of the
* possible values.</p>
*
* @param uri The Namespace URI, or the empty String if the name has no
* Namespace URI.
* @param localName The local name of the attribute.
* @return The attribute value as a string, or null if the attribute is not
* in the list.
*/
public String getValue(String uri, String localName) {
int idx = getIndex(uri, localName);
return (idx >= 0) ? (mItems[(idx << 3) + 3]) : null;
}
/**
* Look up an attribute's value by XML 1.0 qualified name.
*
* <p>See {@link #getValue(int) getValue(int)} for a description of the
* possible values.</p>
*
* @param qName The XML 1.0 qualified name.
* @return The attribute value as a string, or null if the attribute is not
* in the list or if qualified names are not available.
*/
public String getValue(String qName) {
int idx = getIndex(qName);
return (idx >= 0) ? (mItems[(idx << 3) + 3]) : null;
}
/**
* Returns false unless the attribute was declared in the DTD. This helps
* distinguish two kinds of attributes that SAX reports as CDATA: ones that
* were declared (and hence are usually valid), and those that were not (and
* which are never valid).
*
* @param index The attribute index (zero-based).
* @return true if the attribute was declared in the DTD, false otherwise.
* @exception java.lang.ArrayIndexOutOfBoundsException When the supplied
* index does not identify an attribute.
*/
public boolean isDeclared(int index) {
if ((index < 0) || (index >= mLength)) {
throw new ArrayIndexOutOfBoundsException("");
}
return ((mItems[(index << 3) + 5]) != null);
}
/**
* Returns false unless the attribute was declared in the DTD. This helps
* distinguish two kinds of attributes that SAX reports as CDATA: ones that
* were declared (and hence are usually valid), and those that were not (and
* which are never valid).
*
* @param qName The XML qualified (prefixed) name.
* @return true if the attribute was declared in the DTD, false otherwise.
* @exception java.lang.IllegalArgumentException When the supplied name does
* not identify an attribute.
*/
public boolean isDeclared(String qName) {
int idx = getIndex(qName);
if (idx < 0) {
throw new IllegalArgumentException("");
}
return ((mItems[(idx << 3) + 5]) != null);
}
/**
* Returns false unless the attribute was declared in the DTD. This helps
* distinguish two kinds of attributes that SAX reports as CDATA: ones that
* were declared (and hence are usually valid), and those that were not (and
* which are never valid).
*
* <p>Remember that since DTDs do not "understand" namespaces, the namespace
* URI associated with an attribute may not have come from the DTD. The
* declaration will have applied to the attribute's <em>qName</em>.
*
* @param uri The Namespace URI, or the empty string if the name has no
* Namespace URI.
* @param localName The attribute's local name.
* @return true if the attribute was declared in the DTD, false otherwise.
* @exception java.lang.IllegalArgumentException When the supplied names do
* not identify an attribute.
*/
public boolean isDeclared(String uri, String localName) {
int idx = getIndex(uri, localName);
if (idx < 0) {
throw new IllegalArgumentException("");
}
return ((mItems[(idx << 3) + 5]) != null);
}
/**
* Returns true unless the attribute value was provided by DTD defaulting.
*
* @param index The attribute index (zero-based).
* @return true if the value was found in the XML text, false if the value
* was provided by DTD defaulting.
* @exception java.lang.ArrayIndexOutOfBoundsException When the supplied
* index does not identify an attribute.
*/
public boolean isSpecified(int index) {
if ((index < 0) || (index >= mLength)) {
throw new ArrayIndexOutOfBoundsException("");
}
String str = mItems[(index << 3) + 5];
return ((str != null) ? (str.charAt(0) == 'd') : true);
}
/**
* Returns true unless the attribute value was provided by DTD defaulting.
*
* <p>Remember that since DTDs do not "understand" namespaces, the namespace
* URI associated with an attribute may not have come from the DTD. The
* declaration will have applied to the attribute's <em>qName</em>.
*
* @param uri The Namespace URI, or the empty string if the name has no
* Namespace URI.
* @param localName The attribute's local name.
* @return true if the value was found in the XML text, false if the value
* was provided by DTD defaulting.
* @exception java.lang.IllegalArgumentException When the supplied names do
* not identify an attribute.
*/
public boolean isSpecified(String uri, String localName) {
int idx = getIndex(uri, localName);
if (idx < 0) {
throw new IllegalArgumentException("");
}
String str = mItems[(idx << 3) + 5];
return ((str != null) ? (str.charAt(0) == 'd') : true);
}
/**
* Returns true unless the attribute value was provided by DTD defaulting.
*
* @param qName The XML qualified (prefixed) name.
* @return true if the value was found in the XML text, false if the value
* was provided by DTD defaulting.
* @exception java.lang.IllegalArgumentException When the supplied name does
* not identify an attribute.
*/
public boolean isSpecified(String qName) {
int idx = getIndex(qName);
if (idx < 0) {
throw new IllegalArgumentException("");
}
String str = mItems[(idx << 3) + 5];
return ((str != null) ? (str.charAt(0) == 'd') : true);
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.util.xml.impl;
import java.io.Reader;
/**
* A parsed entity input state.
*
* This class represents a parsed entity input state. The parser uses
* an instance of this class to manage input.
*/
public class Input {
/** The entity public identifier or null. */
public String pubid;
/** The entity systen identifier or null. */
public String sysid;
/** The encoding from XML declaration or null */
public String xmlenc;
/** The XML version from XML declaration or 0x0000 */
public char xmlver;
/** The entity reader. */
public Reader src;
/** The character buffer. */
public char[] chars;
/** The length of the character buffer. */
public int chLen;
/** The index of the next character to read. */
public int chIdx;
/** The next input in a chain. */
public Input next;
/**
* Constructor.
*
* @param buffsize The input buffer size.
*/
public Input(int buffsize) {
chars = new char[buffsize];
chLen = chars.length;
}
/**
* Constructor.
*
* @param buff The input buffer.
*/
public Input(char[] buff) {
chars = buff;
chLen = chars.length;
}
/**
* Constructor.
*/
public Input() {
}
}

View File

@@ -0,0 +1,122 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.util.xml.impl;
/**
* A name with value pair.
*
* This class keeps name with value pair with additional information and
* supports pair chaining.
*/
public class Pair {
/** The pair name. */
public String name;
/** The pair value. */
public String value;
/** The pair numeric value. */
public int num;
/** The characters of name. */
public char[] chars;
/** The pair identifier. */
public int id;
/** The list of associated pairs. */
public Pair list;
/** The next pair in a chain. */
public Pair next;
/**
* Creates a qualified name string from qualified name.
*
* @return The qualified name string.
*/
public String qname() {
return new String(chars, 1, chars.length - 1);
}
/**
* Creates a local name string from qualified name.
*
* @return The local name string.
*/
public String local() {
if (chars[0] != 0) {
return new String(chars, chars[0] + 1, chars.length - chars[0] - 1);
}
return new String(chars, 1, chars.length - 1);
}
/**
* Creates a prefix string from qualified name.
*
* @return The prefix string.
*/
public String pref() {
if (chars[0] != 0) {
return new String(chars, 1, chars[0] - 1);
}
return "";
}
/**
* Compares two qualified name prefixes.
*
* @param qname A qualified name.
* @return true if prefixes are equal.
*/
public boolean eqpref(char[] qname) {
if (chars[0] == qname[0]) {
char len = chars[0];
for (char i = 1; i < len; i += 1) {
if (chars[i] != qname[i]) {
return false;
}
}
return true;
}
return false;
}
/**
* Compares two qualified names.
*
* @param qname A qualified name.
* @return true if qualified names are equal.
*/
public boolean eqname(char[] qname) {
char len = (char) chars.length;
if (len == qname.length) {
for (char i = 0; i < len; i += 1) {
if (chars[i] != qname[i]) {
return false;
}
}
return true;
}
return false;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,695 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.util.xml.impl;
import java.io.IOException;
import java.io.InputStream;
import jdk.internal.org.xml.sax.ContentHandler;
import jdk.internal.org.xml.sax.DTDHandler;
import jdk.internal.org.xml.sax.EntityResolver;
import jdk.internal.org.xml.sax.ErrorHandler;
import jdk.internal.org.xml.sax.InputSource;
import jdk.internal.org.xml.sax.Locator;
import jdk.internal.org.xml.sax.SAXException;
import jdk.internal.org.xml.sax.SAXParseException;
import jdk.internal.org.xml.sax.XMLReader;
import jdk.internal.org.xml.sax.helpers.DefaultHandler;
/**
* XML non-validating push parser.
*
* This non-validating parser conforms to <a href="http://www.w3.org/TR/REC-xml"
* >Extensible Markup Language (XML) 1.0</a> and <a
* href="http://www.w3.org/TR/REC-xml-names" >"Namespaces in XML"</a>
* specifications. The API supported by the parser are <a
* href="http://java.sun.com/aboutJava/communityprocess/final/jsr030/index.html">CLDC
* 1.0</a> and <a href="http://www.jcp.org/en/jsr/detail?id=280">JSR-280</a>, a
* JavaME subset of <a href="http://java.sun.com/xml/jaxp/index.html">JAXP</a>
* and <a href="http://www.saxproject.org/">SAX2</a>.
*
* @see org.xml.sax.XMLReader
*/
final class ParserSAX
extends Parser implements XMLReader, Locator
{
public final static String FEATURE_NS =
"http://xml.org/sax/features/namespaces";
public final static String FEATURE_PREF =
"http://xml.org/sax/features/namespace-prefixes";
// SAX feature flags
private boolean mFNamespaces;
private boolean mFPrefixes;
// SAX handlers
private DefaultHandler mHand; // the default handler
private ContentHandler mHandCont; // the content handler
private DTDHandler mHandDtd; // the DTD handler
private ErrorHandler mHandErr; // the error handler
private EntityResolver mHandEnt; // the entity resolver
/**
* Constructor.
*/
public ParserSAX() {
super();
// SAX feature defaut values
mFNamespaces = true;
mFPrefixes = false;
// Default handler which will be used in case the application
// do not set one of handlers.
mHand = new DefaultHandler();
mHandCont = mHand;
mHandDtd = mHand;
mHandErr = mHand;
mHandEnt = mHand;
}
/**
* Return the current content handler.
*
* @return The current content handler, or null if none has been registered.
* @see #setContentHandler
*/
public ContentHandler getContentHandler() {
return (mHandCont != mHand) ? mHandCont : null;
}
/**
* Allow an application to register a content event handler.
*
* <p>If the application does not register a content handler, all content
* events reported by the SAX parser will be silently ignored.</p>
*
* <p>Applications may register a new or different handler in the middle of
* a parse, and the SAX parser must begin using the new handler
* immediately.</p>
*
* @param handler The content handler.
* @exception java.lang.NullPointerException If the handler argument is
* null.
* @see #getContentHandler
*/
public void setContentHandler(ContentHandler handler) {
if (handler == null) {
throw new NullPointerException();
}
mHandCont = handler;
}
/**
* Return the current DTD handler.
*
* @return The current DTD handler, or null if none has been registered.
* @see #setDTDHandler
*/
public DTDHandler getDTDHandler() {
return (mHandDtd != mHand) ? mHandDtd : null;
}
/**
* Allow an application to register a DTD event handler.
*
* <p>If the application does not register a DTD handler, all DTD events
* reported by the SAX parser will be silently ignored.</p>
*
* <p>Applications may register a new or different handler in the middle of
* a parse, and the SAX parser must begin using the new handler
* immediately.</p>
*
* @param handler The DTD handler.
* @exception java.lang.NullPointerException If the handler argument is
* null.
* @see #getDTDHandler
*/
public void setDTDHandler(DTDHandler handler) {
if (handler == null) {
throw new NullPointerException();
}
mHandDtd = handler;
}
/**
* Return the current error handler.
*
* @return The current error handler, or null if none has been registered.
* @see #setErrorHandler
*/
public ErrorHandler getErrorHandler() {
return (mHandErr != mHand) ? mHandErr : null;
}
/**
* Allow an application to register an error event handler.
*
* <p>If the application does not register an error handler, all error
* events reported by the SAX parser will be silently ignored; however,
* normal processing may not continue. It is highly recommended that all SAX
* applications implement an error handler to avoid unexpected bugs.</p>
*
* <p>Applications may register a new or different handler in the middle of
* a parse, and the SAX parser must begin using the new handler
* immediately.</p>
*
* @param handler The error handler.
* @exception java.lang.NullPointerException If the handler argument is
* null.
* @see #getErrorHandler
*/
public void setErrorHandler(ErrorHandler handler) {
if (handler == null) {
throw new NullPointerException();
}
mHandErr = handler;
}
/**
* Return the current entity resolver.
*
* @return The current entity resolver, or null if none has been registered.
* @see #setEntityResolver
*/
public EntityResolver getEntityResolver() {
return (mHandEnt != mHand) ? mHandEnt : null;
}
/**
* Allow an application to register an entity resolver.
*
* <p>If the application does not register an entity resolver, the XMLReader
* will perform its own default resolution.</p>
*
* <p>Applications may register a new or different resolver in the middle of
* a parse, and the SAX parser must begin using the new resolver
* immediately.</p>
*
* @param resolver The entity resolver.
* @exception java.lang.NullPointerException If the resolver argument is
* null.
* @see #getEntityResolver
*/
public void setEntityResolver(EntityResolver resolver) {
if (resolver == null) {
throw new NullPointerException();
}
mHandEnt = resolver;
}
/**
* Return the public identifier for the current document event.
*
* <p>The return value is the public identifier of the document entity or of
* the external parsed entity in which the markup triggering the event
* appears.</p>
*
* @return A string containing the public identifier, or null if none is
* available.
*
* @see #getSystemId
*/
public String getPublicId() {
return (mInp != null) ? mInp.pubid : null;
}
/**
* Return the system identifier for the current document event.
*
* <p>The return value is the system identifier of the document entity or of
* the external parsed entity in which the markup triggering the event
* appears.</p>
*
* <p>If the system identifier is a URL, the parser must resolve it fully
* before passing it to the application.</p>
*
* @return A string containing the system identifier, or null if none is
* available.
*
* @see #getPublicId
*/
public String getSystemId() {
return (mInp != null) ? mInp.sysid : null;
}
/**
* Return the line number where the current document event ends.
*
* @return Always returns -1 indicating the line number is not available.
*
* @see #getColumnNumber
*/
public int getLineNumber() {
return -1;
}
/**
* Return the column number where the current document event ends.
*
* @return Always returns -1 indicating the column number is not available.
*
* @see #getLineNumber
*/
public int getColumnNumber() {
return -1;
}
/**
* Parse an XML document from a system identifier (URI).
*
* <p>This method is a shortcut for the common case of reading a document
* from a system identifier. It is the exact equivalent of the
* following:</p>
*
* <pre>
* parse(new InputSource(systemId));
* </pre>
*
* <p>If the system identifier is a URL, it must be fully resolved by the
* application before it is passed to the parser.</p>
*
* @param systemId The system identifier (URI).
* @exception org.xml.sax.SAXException Any SAX exception, possibly wrapping
* another exception.
* @exception java.io.IOException An IO exception from the parser, possibly
* from a byte stream or character stream supplied by the application.
* @see #parse(org.xml.sax.InputSource)
*/
public void parse(String systemId) throws IOException, SAXException {
parse(new InputSource(systemId));
}
/**
* Parse an XML document.
*
* <p>The application can use this method to instruct the XML reader to
* begin parsing an XML document from any valid input source (a character
* stream, a byte stream, or a URI).</p>
*
* <p>Applications may not invoke this method while a parse is in progress
* (they should create a new XMLReader instead for each nested XML
* document). Once a parse is complete, an application may reuse the same
* XMLReader object, possibly with a different input source.</p>
*
* <p>During the parse, the XMLReader will provide information about the XML
* document through the registered event handlers.</p>
*
* <p>This method is synchronous: it will not return until parsing has
* ended. If a client application wants to terminate parsing early, it
* should throw an exception.</p>
*
* @param is The input source for the top-level of the XML document.
* @exception org.xml.sax.SAXException Any SAX exception, possibly wrapping
* another exception.
* @exception java.io.IOException An IO exception from the parser, possibly
* from a byte stream or character stream supplied by the application.
* @see org.xml.sax.InputSource
* @see #parse(java.lang.String)
* @see #setEntityResolver
* @see #setDTDHandler
* @see #setContentHandler
* @see #setErrorHandler
*/
public void parse(InputSource is) throws IOException, SAXException {
if (is == null) {
throw new IllegalArgumentException("");
}
// Set up the document
mInp = new Input(BUFFSIZE_READER);
mPh = PH_BEFORE_DOC; // before parsing
try {
setinp(is);
} catch (SAXException saxe) {
throw saxe;
} catch (IOException ioe) {
throw ioe;
} catch (RuntimeException rte) {
throw rte;
} catch (Exception e) {
panic(e.toString());
}
parse();
}
/**
* Parse the content of the given {@link java.io.InputStream} instance as
* XML using the specified {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param src InputStream containing the content to be parsed.
* @param handler The SAX DefaultHandler to use.
* @exception IOException If any IO errors occur.
* @exception IllegalArgumentException If the given InputStream or handler
* is null.
* @exception SAXException If the underlying parser throws a SAXException
* while parsing.
* @see org.xml.sax.helpers.DefaultHandler
*/
public void parse(InputStream src, DefaultHandler handler)
throws SAXException, IOException {
if ((src == null) || (handler == null)) {
throw new IllegalArgumentException("");
}
parse(new InputSource(src), handler);
}
/**
* Parse the content given {@link org.xml.sax.InputSource} as XML using the
* specified {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param is The InputSource containing the content to be parsed.
* @param handler The SAX DefaultHandler to use.
* @exception IOException If any IO errors occur.
* @exception IllegalArgumentException If the InputSource or handler is
* null.
* @exception SAXException If the underlying parser throws a SAXException
* while parsing.
* @see org.xml.sax.helpers.DefaultHandler
*/
public void parse(InputSource is, DefaultHandler handler)
throws SAXException, IOException
{
if ((is == null) || (handler == null)) {
throw new IllegalArgumentException("");
}
// Set up the handler
mHandCont = handler;
mHandDtd = handler;
mHandErr = handler;
mHandEnt = handler;
// Set up the document
mInp = new Input(BUFFSIZE_READER);
mPh = PH_BEFORE_DOC; // before parsing
try {
setinp(is);
} catch (SAXException | IOException | RuntimeException saxe) {
throw saxe;
} catch (Exception e) {
panic(e.toString());
}
parse();
}
/**
* Parse the XML document content using specified handlers and an input
* source.
*
* @exception IOException If any IO errors occur.
* @exception SAXException If the underlying parser throws a SAXException
* while parsing.
*/
@SuppressWarnings("fallthrough")
private void parse() throws SAXException, IOException {
init();
try {
mHandCont.setDocumentLocator(this);
mHandCont.startDocument();
if (mPh != PH_MISC_DTD) {
mPh = PH_MISC_DTD; // misc before DTD
}
int evt = EV_NULL;
// XML document prolog
do {
wsskip();
switch (evt = step()) {
case EV_ELM:
case EV_ELMS:
mPh = PH_DOCELM;
break;
case EV_COMM:
case EV_PI:
break;
case EV_DTD:
if (mPh >= PH_DTD_MISC) {
panic(FAULT);
}
mPh = PH_DTD_MISC; // misc after DTD
break;
default:
panic(FAULT);
}
} while (mPh < PH_DOCELM); // misc before DTD
// XML document starting with document's element
do {
switch (evt) {
case EV_ELM:
case EV_ELMS:
// Report the element
if (mIsNSAware == true) {
mHandCont.startElement(
mElm.value,
mElm.name,
"",
mAttrs);
} else {
mHandCont.startElement(
"",
"",
mElm.name,
mAttrs);
}
if (evt == EV_ELMS) {
evt = step();
break;
}
case EV_ELME:
// Report the end of element
if (mIsNSAware == true) {
mHandCont.endElement(mElm.value, mElm.name, "");
} else {
mHandCont.endElement("", "", mElm.name);
}
// Restore the top of the prefix stack
while (mPref.list == mElm) {
mHandCont.endPrefixMapping(mPref.name);
mPref = del(mPref);
}
// Remove the top element tag
mElm = del(mElm);
if (mElm == null) {
mPh = PH_DOCELM_MISC;
} else {
evt = step();
}
break;
case EV_TEXT:
case EV_WSPC:
case EV_CDAT:
case EV_COMM:
case EV_PI:
case EV_ENT:
evt = step();
break;
default:
panic(FAULT);
}
} while (mPh == PH_DOCELM);
// Misc after document's element
do {
if (wsskip() == EOS) {
break;
}
switch (step()) {
case EV_COMM:
case EV_PI:
break;
default:
panic(FAULT);
}
} while (mPh == PH_DOCELM_MISC);
mPh = PH_AFTER_DOC; // parsing is completed
} catch (SAXException saxe) {
throw saxe;
} catch (IOException ioe) {
throw ioe;
} catch (RuntimeException rte) {
throw rte;
} catch (Exception e) {
panic(e.toString());
} finally {
mHandCont.endDocument();
cleanup();
}
}
/**
* Reports document type.
*
* @param name The name of the entity.
* @param pubid The public identifier of the entity or <code>null</code>.
* @param sysid The system identifier of the entity or <code>null</code>.
*/
protected void docType(String name, String pubid, String sysid) throws SAXException {
mHandDtd.notationDecl(name, pubid, sysid);
}
/**
* Reports a comment.
*
* @param text The comment text starting from first charcater.
* @param length The number of characters in comment.
*/
protected void comm(char[] text, int length) {
}
/**
* Reports a processing instruction.
*
* @param target The processing instruction target name.
* @param body The processing instruction body text.
*/
protected void pi(String target, String body) throws SAXException {
mHandCont.processingInstruction(target, body);
}
/**
* Reports new namespace prefix. The Namespace prefix (
* <code>mPref.name</code>) being declared and the Namespace URI (
* <code>mPref.value</code>) the prefix is mapped to. An empty string is
* used for the default element namespace, which has no prefix.
*/
protected void newPrefix() throws SAXException {
mHandCont.startPrefixMapping(mPref.name, mPref.value);
}
/**
* Reports skipped entity name.
*
* @param name The entity name.
*/
protected void skippedEnt(String name) throws SAXException {
mHandCont.skippedEntity(name);
}
/**
* Returns an
* <code>InputSource</code> for specified entity or
* <code>null</code>.
*
* @param name The name of the entity.
* @param pubid The public identifier of the entity.
* @param sysid The system identifier of the entity.
*/
protected InputSource resolveEnt(String name, String pubid, String sysid)
throws SAXException, IOException
{
return mHandEnt.resolveEntity(pubid, sysid);
}
/**
* Reports notation declaration.
*
* @param name The notation's name.
* @param pubid The notation's public identifier, or null if none was given.
* @param sysid The notation's system identifier, or null if none was given.
*/
protected void notDecl(String name, String pubid, String sysid)
throws SAXException
{
mHandDtd.notationDecl(name, pubid, sysid);
}
/**
* Reports unparsed entity name.
*
* @param name The unparsed entity's name.
* @param pubid The entity's public identifier, or null if none was given.
* @param sysid The entity's system identifier.
* @param notation The name of the associated notation.
*/
protected void unparsedEntDecl(String name, String pubid, String sysid, String notation)
throws SAXException
{
mHandDtd.unparsedEntityDecl(name, pubid, sysid, notation);
}
/**
* Notifies the handler about fatal parsing error.
*
* @param msg The problem description message.
*/
protected void panic(String msg) throws SAXException {
SAXParseException spe = new SAXParseException(msg, this);
mHandErr.fatalError(spe);
throw spe; // [#1.2] fatal error definition
}
/**
* Reports characters and empties the parser's buffer. This method is called
* only if parser is going to return control to the main loop. This means
* that this method may use parser buffer to report white space without
* copeing characters to temporary buffer.
*/
protected void bflash() throws SAXException {
if (mBuffIdx >= 0) {
// Textual data has been read
mHandCont.characters(mBuff, 0, (mBuffIdx + 1));
mBuffIdx = -1;
}
}
/**
* Reports white space characters and empties the parser's buffer. This
* method is called only if parser is going to return control to the main
* loop. This means that this method may use parser buffer to report white
* space without copeing characters to temporary buffer.
*/
protected void bflash_ws() throws SAXException {
if (mBuffIdx >= 0) {
// BUG: With additional info from DTD and xml:space attr [#2.10]
// the following call can be supported:
// mHandCont.ignorableWhitespace(mBuff, 0, (mBuffIdx + 1));
// Textual data has been read
mHandCont.characters(mBuff, 0, (mBuffIdx + 1));
mBuffIdx = -1;
}
}
public boolean getFeature(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setFeature(String name, boolean value) {
throw new UnsupportedOperationException("Not supported yet.");
}
public Object getProperty(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setProperty(String name, Object value) {
throw new UnsupportedOperationException("Not supported yet.");
}
}

View File

@@ -0,0 +1,122 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.util.xml.impl;
import java.io.Reader;
import java.io.InputStream;
import java.io.IOException;
/**
* UTF-16 encoded stream reader.
*/
public class ReaderUTF16 extends Reader {
private InputStream is;
private char bo;
/**
* Constructor.
*
* Byte order argument can be: 'l' for little-endian or 'b' for big-endian.
*
* @param is A byte input stream.
* @param bo A byte order in the input stream.
*/
public ReaderUTF16(InputStream is, char bo) {
switch (bo) {
case 'l':
break;
case 'b':
break;
default:
throw new IllegalArgumentException("");
}
this.bo = bo;
this.is = is;
}
/**
* Reads characters into a portion of an array.
*
* @param cbuf Destination buffer.
* @param off Offset at which to start storing characters.
* @param len Maximum number of characters to read.
* @exception IOException If any IO errors occur.
*/
public int read(char[] cbuf, int off, int len) throws IOException {
int num = 0;
int val;
if (bo == 'b') {
while (num < len) {
if ((val = is.read()) < 0) {
return (num != 0) ? num : -1;
}
cbuf[off++] = (char) ((val << 8) | (is.read() & 0xff));
num++;
}
} else {
while (num < len) {
if ((val = is.read()) < 0) {
return (num != 0) ? num : -1;
}
cbuf[off++] = (char) ((is.read() << 8) | (val & 0xff));
num++;
}
}
return num;
}
/**
* Reads a single character.
*
* @return The character read, as an integer in the range 0 to 65535
* (0x0000-0xffff), or -1 if the end of the stream has been reached.
* @exception IOException If any IO errors occur.
*/
public int read() throws IOException {
int val;
if ((val = is.read()) < 0) {
return -1;
}
if (bo == 'b') {
val = (char) ((val << 8) | (is.read() & 0xff));
} else {
val = (char) ((is.read() << 8) | (val & 0xff));
}
return val;
}
/**
* Closes the stream.
*
* @exception IOException If any IO errors occur.
*/
public void close() throws IOException {
is.close();
}
}

View File

@@ -0,0 +1,138 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.util.xml.impl;
import java.io.Reader;
import java.io.InputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* UTF-8 transformed UCS-2 character stream reader.
*
* This reader converts UTF-8 transformed UCS-2 characters to Java characters.
* The UCS-2 subset of UTF-8 transformation is described in RFC-2279 #2
* "UTF-8 definition":
* 0000 0000-0000 007F 0xxxxxxx
* 0000 0080-0000 07FF 110xxxxx 10xxxxxx
* 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx
*
* This reader will return incorrect last character on broken UTF-8 stream.
*/
public class ReaderUTF8 extends Reader {
private InputStream is;
/**
* Constructor.
*
* @param is A byte input stream.
*/
public ReaderUTF8(InputStream is) {
this.is = is;
}
/**
* Reads characters into a portion of an array.
*
* @param cbuf Destination buffer.
* @param off Offset at which to start storing characters.
* @param len Maximum number of characters to read.
* @exception IOException If any IO errors occur.
* @exception UnsupportedEncodingException If UCS-4 character occur in the stream.
*/
public int read(char[] cbuf, int off, int len) throws IOException {
int num = 0;
int val;
while (num < len) {
if ((val = is.read()) < 0) {
return (num != 0) ? num : -1;
}
switch (val & 0xf0) {
case 0xc0:
case 0xd0:
cbuf[off++] = (char) (((val & 0x1f) << 6) | (is.read() & 0x3f));
break;
case 0xe0:
cbuf[off++] = (char) (((val & 0x0f) << 12)
| ((is.read() & 0x3f) << 6) | (is.read() & 0x3f));
break;
case 0xf0: // UCS-4 character
throw new UnsupportedEncodingException("UTF-32 (or UCS-4) encoding not supported.");
default:
cbuf[off++] = (char) val;
break;
}
num++;
}
return num;
}
/**
* Reads a single character.
*
* @return The character read, as an integer in the range 0 to 65535
* (0x00-0xffff), or -1 if the end of the stream has been reached.
* @exception IOException If any IO errors occur.
* @exception UnsupportedEncodingException If UCS-4 character occur in the stream.
*/
public int read() throws IOException {
int val;
if ((val = is.read()) < 0) {
return -1;
}
switch (val & 0xf0) {
case 0xc0:
case 0xd0:
val = ((val & 0x1f) << 6) | (is.read() & 0x3f);
break;
case 0xe0:
val = ((val & 0x0f) << 12)
| ((is.read() & 0x3f) << 6) | (is.read() & 0x3f);
break;
case 0xf0: // UCS-4 character
throw new UnsupportedEncodingException();
default:
break;
}
return val;
}
/**
* Closes the stream.
*
* @exception IOException If any IO errors occur.
*/
public void close() throws IOException {
is.close();
}
}

View File

@@ -0,0 +1,118 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.util.xml.impl;
import java.io.IOException;
import java.io.InputStream;
import jdk.internal.org.xml.sax.InputSource;
import jdk.internal.org.xml.sax.SAXException;
import jdk.internal.org.xml.sax.XMLReader;
import jdk.internal.org.xml.sax.helpers.DefaultHandler;
import jdk.internal.util.xml.SAXParser;
public class SAXParserImpl extends SAXParser {
private ParserSAX parser;
public SAXParserImpl() {
super();
parser = new ParserSAX();
}
/**
* Returns the {@link org.xml.sax.XMLReader} that is encapsulated by the
* implementation of this class.
*
* @return The XMLReader that is encapsulated by the
* implementation of this class.
*
* @throws SAXException If any SAX errors occur during processing.
*/
public XMLReader getXMLReader()
throws SAXException {
return parser;
}
/**
* Indicates whether or not this parser is configured to
* understand namespaces.
*
* @return true if this parser is configured to
* understand namespaces; false otherwise.
*/
public boolean isNamespaceAware() {
return parser.mIsNSAware;
}
/**
* Indicates whether or not this parser is configured to validate
* XML documents.
*
* @return true if this parser is configured to validate XML
* documents; false otherwise.
*/
public boolean isValidating() {
return false;
}
/**
* Parse the content of the given {@link java.io.InputStream}
* instance as XML using the specified
* {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param src InputStream containing the content to be parsed.
* @param handler The SAX DefaultHandler to use.
* @exception IOException If any IO errors occur.
* @exception IllegalArgumentException If the given InputStream or handler is null.
* @exception SAXException If the underlying parser throws a
* SAXException while parsing.
* @see org.xml.sax.helpers.DefaultHandler
*/
public void parse(InputStream src, DefaultHandler handler)
throws SAXException, IOException
{
parser.parse(src, handler);
}
/**
* Parse the content given {@link org.xml.sax.InputSource}
* as XML using the specified
* {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param is The InputSource containing the content to be parsed.
* @param handler The SAX DefaultHandler to use.
* @exception IOException If any IO errors occur.
* @exception IllegalArgumentException If the InputSource or handler is null.
* @exception SAXException If the underlying parser throws a
* SAXException while parsing.
* @see org.xml.sax.helpers.DefaultHandler
*/
public void parse(InputSource is, DefaultHandler handler)
throws SAXException, IOException
{
parser.parse(is, handler);
}
}

View File

@@ -0,0 +1,633 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.util.xml.impl;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import jdk.internal.util.xml.XMLStreamException;
import jdk.internal.util.xml.XMLStreamWriter;
/**
* Implementation of a reduced version of XMLStreamWriter
*
* @author Joe Wang
*/
public class XMLStreamWriterImpl implements XMLStreamWriter {
//Document state
static final int STATE_XML_DECL = 1;
static final int STATE_PROLOG = 2;
static final int STATE_DTD_DECL = 3;
static final int STATE_ELEMENT = 4;
//Element state
static final int ELEMENT_STARTTAG_OPEN = 10;
static final int ELEMENT_STARTTAG_CLOSE = 11;
static final int ELEMENT_ENDTAG_OPEN = 12;
static final int ELEMENT_ENDTAG_CLOSE = 13;
public static final char CLOSE_START_TAG = '>';
public static final char OPEN_START_TAG = '<';
public static final String OPEN_END_TAG = "</";
public static final char CLOSE_END_TAG = '>';
public static final String START_CDATA = "<![CDATA[";
public static final String END_CDATA = "]]>";
public static final String CLOSE_EMPTY_ELEMENT = "/>";
public static final String ENCODING_PREFIX = "&#x";
public static final char SPACE = ' ';
public static final char AMPERSAND = '&';
public static final char DOUBLEQUOT = '"';
public static final char SEMICOLON = ';';
//current state
private int _state = 0;
private Element _currentEle;
private XMLWriter _writer;
private String _encoding;
/**
* This flag can be used to turn escaping off for content. It does
* not apply to attribute content.
*/
boolean _escapeCharacters = true;
//pretty print by default
private boolean _doIndent = true;
//The system line separator for writing out line breaks.
private char[] _lineSep =
System.getProperty("line.separator").toCharArray();
public XMLStreamWriterImpl(OutputStream os) throws XMLStreamException {
this(os, XMLStreamWriter.DEFAULT_ENCODING);
}
public XMLStreamWriterImpl(OutputStream os, String encoding)
throws XMLStreamException
{
Charset cs = null;
if (encoding == null) {
_encoding = XMLStreamWriter.DEFAULT_ENCODING;
} else {
try {
cs = getCharset(encoding);
} catch (UnsupportedEncodingException e) {
throw new XMLStreamException(e);
}
this._encoding = encoding;
}
_writer = new XMLWriter(os, encoding, cs);
}
/**
* Write the XML Declaration. Defaults the XML version to 1.0, and the
* encoding to utf-8.
*
* @throws XMLStreamException
*/
public void writeStartDocument() throws XMLStreamException {
writeStartDocument(_encoding, XMLStreamWriter.DEFAULT_XML_VERSION);
}
/**
* Write the XML Declaration. Defaults the encoding to utf-8
*
* @param version version of the xml document
* @throws XMLStreamException
*/
public void writeStartDocument(String version) throws XMLStreamException {
writeStartDocument(_encoding, version, null);
}
/**
* Write the XML Declaration. Note that the encoding parameter does not set
* the actual encoding of the underlying output. That must be set when the
* instance of the XMLStreamWriter is created
*
* @param encoding encoding of the xml declaration
* @param version version of the xml document
* @throws XMLStreamException If given encoding does not match encoding of the
* underlying stream
*/
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
writeStartDocument(encoding, version, null);
}
/**
* Write the XML Declaration. Note that the encoding parameter does not set
* the actual encoding of the underlying output. That must be set when the
* instance of the XMLStreamWriter is created
*
* @param encoding encoding of the xml declaration
* @param version version of the xml document
* @param standalone indicate if the xml document is standalone
* @throws XMLStreamException If given encoding does not match encoding of the
* underlying stream
*/
public void writeStartDocument(String encoding, String version, String standalone)
throws XMLStreamException
{
if (_state > 0) {
throw new XMLStreamException("XML declaration must be as the first line in the XML document.");
}
_state = STATE_XML_DECL;
String enc = encoding;
if (enc == null) {
enc = _encoding;
} else {
//check if the encoding is supported
try {
getCharset(encoding);
} catch (UnsupportedEncodingException e) {
throw new XMLStreamException(e);
}
}
if (version == null) {
version = XMLStreamWriter.DEFAULT_XML_VERSION;
}
_writer.write("<?xml version=\"");
_writer.write(version);
_writer.write(DOUBLEQUOT);
if (enc != null) {
_writer.write(" encoding=\"");
_writer.write(enc);
_writer.write(DOUBLEQUOT);
}
if (standalone != null) {
_writer.write(" standalone=\"");
_writer.write(standalone);
_writer.write(DOUBLEQUOT);
}
_writer.write("?>");
writeLineSeparator();
}
/**
* Write a DTD section. This string represents the entire doctypedecl production
* from the XML 1.0 specification.
*
* @param dtd the DTD to be written
* @throws XMLStreamException
*/
public void writeDTD(String dtd) throws XMLStreamException {
if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
closeStartTag();
}
_writer.write(dtd);
writeLineSeparator();
}
/**
* Writes a start tag to the output.
* @param localName local name of the tag, may not be null
* @throws XMLStreamException
*/
public void writeStartElement(String localName) throws XMLStreamException {
if (localName == null || localName.length() == 0) {
throw new XMLStreamException("Local Name cannot be null or empty");
}
_state = STATE_ELEMENT;
if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
closeStartTag();
}
_currentEle = new Element(_currentEle, localName, false);
openStartTag();
_writer.write(localName);
}
/**
* Writes an empty element tag to the output
* @param localName local name of the tag, may not be null
* @throws XMLStreamException
*/
public void writeEmptyElement(String localName) throws XMLStreamException {
if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
closeStartTag();
}
_currentEle = new Element(_currentEle, localName, true);
openStartTag();
_writer.write(localName);
}
/**
* Writes an attribute to the output stream without a prefix.
* @param localName the local name of the attribute
* @param value the value of the attribute
* @throws IllegalStateException if the current state does not allow Attribute writing
* @throws XMLStreamException
*/
public void writeAttribute(String localName, String value) throws XMLStreamException {
if (_currentEle.getState() != ELEMENT_STARTTAG_OPEN) {
throw new XMLStreamException(
"Attribute not associated with any element");
}
_writer.write(SPACE);
_writer.write(localName);
_writer.write("=\"");
writeXMLContent(
value,
true, // true = escapeChars
true); // true = escapeDoubleQuotes
_writer.write(DOUBLEQUOT);
}
public void writeEndDocument() throws XMLStreamException {
if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
closeStartTag();
}
/**
* close unclosed elements if any
*/
while (_currentEle != null) {
if (!_currentEle.isEmpty()) {
_writer.write(OPEN_END_TAG);
_writer.write(_currentEle.getLocalName());
_writer.write(CLOSE_END_TAG);
}
_currentEle = _currentEle.getParent();
}
}
public void writeEndElement() throws XMLStreamException {
if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
closeStartTag();
}
if (_currentEle == null) {
throw new XMLStreamException("No element was found to write");
}
if (_currentEle.isEmpty()) {
return;
}
_writer.write(OPEN_END_TAG);
_writer.write(_currentEle.getLocalName());
_writer.write(CLOSE_END_TAG);
writeLineSeparator();
_currentEle = _currentEle.getParent();
}
public void writeCData(String cdata) throws XMLStreamException {
if (cdata == null) {
throw new XMLStreamException("cdata cannot be null");
}
if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
closeStartTag();
}
_writer.write(START_CDATA);
_writer.write(cdata);
_writer.write(END_CDATA);
}
public void writeCharacters(String data) throws XMLStreamException {
if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
closeStartTag();
}
writeXMLContent(data);
}
public void writeCharacters(char[] data, int start, int len)
throws XMLStreamException {
if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
closeStartTag();
}
writeXMLContent(data, start, len, _escapeCharacters);
}
/**
* Close this XMLStreamWriter by closing underlying writer.
*/
public void close() throws XMLStreamException {
if (_writer != null) {
_writer.close();
}
_writer = null;
_currentEle = null;
_state = 0;
}
/**
* Flush this XMLStreamWriter by flushing underlying writer.
*/
public void flush() throws XMLStreamException {
if (_writer != null) {
_writer.flush();
}
}
/**
* Set the flag to indicate if the writer should add line separator
* @param doIndent
*/
public void setDoIndent(boolean doIndent) {
_doIndent = doIndent;
}
/**
* Writes XML content to underlying writer. Escapes characters unless
* escaping character feature is turned off.
*/
private void writeXMLContent(char[] content, int start, int length, boolean escapeChars)
throws XMLStreamException
{
if (!escapeChars) {
_writer.write(content, start, length);
return;
}
// Index of the next char to be written
int startWritePos = start;
final int end = start + length;
for (int index = start; index < end; index++) {
char ch = content[index];
if (!_writer.canEncode(ch)) {
_writer.write(content, startWritePos, index - startWritePos);
// Escape this char as underlying encoder cannot handle it
_writer.write(ENCODING_PREFIX);
_writer.write(Integer.toHexString(ch));
_writer.write(SEMICOLON);
startWritePos = index + 1;
continue;
}
switch (ch) {
case OPEN_START_TAG:
_writer.write(content, startWritePos, index - startWritePos);
_writer.write("&lt;");
startWritePos = index + 1;
break;
case AMPERSAND:
_writer.write(content, startWritePos, index - startWritePos);
_writer.write("&amp;");
startWritePos = index + 1;
break;
case CLOSE_START_TAG:
_writer.write(content, startWritePos, index - startWritePos);
_writer.write("&gt;");
startWritePos = index + 1;
break;
}
}
// Write any pending data
_writer.write(content, startWritePos, end - startWritePos);
}
private void writeXMLContent(String content) throws XMLStreamException {
if ((content != null) && (content.length() > 0)) {
writeXMLContent(content,
_escapeCharacters, // boolean = escapeChars
false); // false = escapeDoubleQuotes
}
}
/**
* Writes XML content to underlying writer. Escapes characters unless
* escaping character feature is turned off.
*/
private void writeXMLContent(
String content,
boolean escapeChars,
boolean escapeDoubleQuotes)
throws XMLStreamException
{
if (!escapeChars) {
_writer.write(content);
return;
}
// Index of the next char to be written
int startWritePos = 0;
final int end = content.length();
for (int index = 0; index < end; index++) {
char ch = content.charAt(index);
if (!_writer.canEncode(ch)) {
_writer.write(content, startWritePos, index - startWritePos);
// Escape this char as underlying encoder cannot handle it
_writer.write(ENCODING_PREFIX);
_writer.write(Integer.toHexString(ch));
_writer.write(SEMICOLON);
startWritePos = index + 1;
continue;
}
switch (ch) {
case OPEN_START_TAG:
_writer.write(content, startWritePos, index - startWritePos);
_writer.write("&lt;");
startWritePos = index + 1;
break;
case AMPERSAND:
_writer.write(content, startWritePos, index - startWritePos);
_writer.write("&amp;");
startWritePos = index + 1;
break;
case CLOSE_START_TAG:
_writer.write(content, startWritePos, index - startWritePos);
_writer.write("&gt;");
startWritePos = index + 1;
break;
case DOUBLEQUOT:
_writer.write(content, startWritePos, index - startWritePos);
if (escapeDoubleQuotes) {
_writer.write("&quot;");
} else {
_writer.write(DOUBLEQUOT);
}
startWritePos = index + 1;
break;
}
}
// Write any pending data
_writer.write(content, startWritePos, end - startWritePos);
}
/**
* marks open of start tag and writes the same into the writer.
*/
private void openStartTag() throws XMLStreamException {
_currentEle.setState(ELEMENT_STARTTAG_OPEN);
_writer.write(OPEN_START_TAG);
}
/**
* marks close of start tag and writes the same into the writer.
*/
private void closeStartTag() throws XMLStreamException {
if (_currentEle.isEmpty()) {
_writer.write(CLOSE_EMPTY_ELEMENT);
} else {
_writer.write(CLOSE_START_TAG);
}
if (_currentEle.getParent() == null) {
writeLineSeparator();
}
_currentEle.setState(ELEMENT_STARTTAG_CLOSE);
}
/**
* Write a line separator
* @throws XMLStreamException
*/
private void writeLineSeparator() throws XMLStreamException {
if (_doIndent) {
_writer.write(_lineSep, 0, _lineSep.length);
}
}
/**
* Returns a charset object for the specified encoding
* @param encoding
* @return a charset object
* @throws UnsupportedEncodingException if the encoding is not supported
*/
private Charset getCharset(String encoding) throws UnsupportedEncodingException {
if (encoding.equalsIgnoreCase("UTF-32")) {
throw new UnsupportedEncodingException("The basic XMLWriter does "
+ "not support " + encoding);
}
Charset cs;
try {
cs = Charset.forName(encoding);
} catch (IllegalCharsetNameException | UnsupportedCharsetException ex) {
throw new UnsupportedEncodingException(encoding);
}
return cs;
}
/*
* Start of Internal classes.
*
*/
protected class Element {
/**
* the parent element
*/
protected Element _parent;
/**
* The size of the stack.
*/
protected short _Depth;
/**
* indicate if an element is an empty one
*/
boolean _isEmptyElement = false;
String _localpart;
int _state;
/**
* Default constructor.
*/
public Element() {
}
/**
* @param parent the parent of the element
* @param localpart name of the element
* @param isEmpty indicate if the element is an empty one
*/
public Element(Element parent, String localpart, boolean isEmpty) {
_parent = parent;
_localpart = localpart;
_isEmptyElement = isEmpty;
}
public Element getParent() {
return _parent;
}
public String getLocalName() {
return _localpart;
}
/**
* get the state of the element
*/
public int getState() {
return _state;
}
/**
* Set the state of the element
*
* @param state the state of the element
*/
public void setState(int state) {
_state = state;
}
public boolean isEmpty() {
return _isEmptyElement;
}
}
}

View File

@@ -0,0 +1,152 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.util.xml.impl;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import jdk.internal.util.xml.XMLStreamException;
/**
*
* @author huizwang
*/
public class XMLWriter {
private Writer _writer;
/**
* In some cases, this charset encoder is used to determine if a char is
* encodable by underlying writer. For example, an 8-bit char from the
* extended ASCII set is not encodable by 7-bit ASCII encoder. Unencodable
* chars are escaped using XML numeric entities.
*/
private CharsetEncoder _encoder = null;
public XMLWriter(OutputStream os, String encoding, Charset cs) throws XMLStreamException {
_encoder = cs.newEncoder();
try {
_writer = getWriter(os, encoding, cs);
} catch (UnsupportedEncodingException ex) {
throw new XMLStreamException(ex);
}
}
public boolean canEncode(char ch) {
if (_encoder == null) {
return false;
}
return (_encoder.canEncode(ch));
}
public void write(String s)
throws XMLStreamException {
try {
_writer.write(s.toCharArray());
// _writer.write(s.getBytes(Charset.forName(_encoding)));
} catch (IOException e) {
throw new XMLStreamException("I/O error", e);
}
}
public void write(String str, int off, int len)
throws XMLStreamException {
try {
_writer.write(str, off, len);
} catch (IOException e) {
throw new XMLStreamException("I/O error", e);
}
}
public void write(char[] cbuf, int off, int len)
throws XMLStreamException {
try {
_writer.write(cbuf, off, len);
} catch (IOException e) {
throw new XMLStreamException("I/O error", e);
}
}
void write(int b)
throws XMLStreamException {
try {
_writer.write(b);
} catch (IOException e) {
throw new XMLStreamException("I/O error", e);
}
}
void flush() throws XMLStreamException {
try {
_writer.flush();
} catch (IOException ex) {
throw new XMLStreamException(ex);
}
}
void close() throws XMLStreamException {
try {
_writer.close();
} catch (IOException ex) {
throw new XMLStreamException(ex);
}
}
private void nl() throws XMLStreamException {
String lineEnd = System.getProperty("line.separator");
try {
_writer.write(lineEnd);
} catch (IOException e) {
throw new XMLStreamException("I/O error", e);
}
}
/**
* Returns a writer for the specified encoding based on an output stream.
*
* @param output The output stream
* @param encoding The encoding
* @return A suitable writer
* @throws UnsupportedEncodingException There is no convertor to support
* this encoding
*/
private Writer getWriter(OutputStream output, String encoding, Charset cs)
throws XMLStreamException, UnsupportedEncodingException
{
if (cs != null) {
return (new OutputStreamWriter(new BufferedOutputStream(output), cs));
}
return new OutputStreamWriter(new BufferedOutputStream(output), encoding);
}
}