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,49 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
/**
* Performs character escaping and write the result
* to the output.
*
* @since 1.0.1
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public interface CharacterEscapeHandler {
/**
* @param ch The array of characters.
* @param start The starting position.
* @param length The number of characters to use.
* @param isAttVal true if this is an attribute value literal.
*/
void escape( char[] ch, int start, int length, boolean isAttVal, Writer out ) throws IOException;
}

View File

@@ -0,0 +1,377 @@
/*
* Copyright (c) 1997, 2011, 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.
*/
//@@3RD PARTY CODE@@
// DataWriter.java - XML writer for data-oriented files.
package com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* Write data- or field-oriented XML.
*
* <p>This filter pretty-prints field-oriented XML without mixed content.
* all added indentation and newlines will be passed on down
* the filter chain (if any).</p>
*
* <p>In general, all whitespace in an XML document is potentially
* significant, so a general-purpose XML writing tool like the
* {@link XMLWriter} class cannot
* add newlines or indentation.</p>
*
* <p>There is, however, a large class of XML documents where information
* is strictly fielded: each element contains either character data
* or other elements, but not both. For this special case, it is possible
* for a writing tool to provide automatic indentation and newlines
* without requiring extra work from the user. Note that this class
* will likely not yield appropriate results for document-oriented
* XML like XHTML pages, which mix character data and elements together.</p>
*
* <p>This writer will automatically place each start tag on a new line,
* optionally indented if an indent step is provided (by default, there
* is no indentation). If an element contains other elements, the end
* tag will also appear on a new line with leading indentation. Consider,
* for example, the following code:</p>
*
* <pre>
* DataWriter w = new DataWriter();
*
* w.setIndentStep(2);
* w.startDocument();
* w.startElement("Person");
* w.dataElement("name", "Jane Smith");
* w.dataElement("date-of-birth", "1965-05-23");
* w.dataElement("citizenship", "US");
* w.endElement("Person");
* w.endDocument();
* </pre>
*
* <p>This code will produce the following document:</p>
*
* <pre>
* &lt;?xml version="1.0" standalone="yes"?>
*
* &lt;Person>
* &lt;name>Jane Smith&lt;/name>
* &lt;date-of-birth>1965-05-23&lt;/date-of-birth>
* &lt;citizenship>US&lt;/citizenship>
* &lt;/Person>
* </pre>
*
* <p>This class inherits from {@link XMLWriter},
* and provides all of the same support for Namespaces.</p>
*
* @since 1.0
* @author David Megginson, david@megginson.com
* @version 0.2
* @see XMLWriter
*/
public class DataWriter extends XMLWriter
{
////////////////////////////////////////////////////////////////////
// Constructors.
////////////////////////////////////////////////////////////////////
/**
* Create a new data writer for the specified output.
*
* @param writer The character stream where the XML document
* will be written.
* @param encoding
* If non-null string is specified, it is written as a part
* of the XML declaration.
*/
public DataWriter ( Writer writer, String encoding, CharacterEscapeHandler _escapeHandler )
{
super(writer,encoding,_escapeHandler);
}
public DataWriter (Writer writer, String encoding ) {
this( writer, encoding, DumbEscapeHandler.theInstance );
}
////////////////////////////////////////////////////////////////////
// Accessors and setters.
////////////////////////////////////////////////////////////////////
/**
* Return the current indent step.
*
* <p>Return the current indent step: each start tag will be
* indented by this number of spaces times the number of
* ancestors that the element has.</p>
*
* @return The number of spaces in each indentation step,
* or 0 or less for no indentation.
* @see #setIndentStep(int)
*
* @deprecated
* Only return the length of the indent string.
*/
public int getIndentStep ()
{
return indentStep.length();
}
/**
* Set the current indent step.
*
* @param indentStep The new indent step (0 or less for no
* indentation).
* @see #getIndentStep()
*
* @deprecated
* Should use the version that takes string.
*/
public void setIndentStep (int indentStep)
{
StringBuilder buf = new StringBuilder();
for( ; indentStep>0; indentStep-- )
buf.append(' ');
setIndentStep(buf.toString());
}
public void setIndentStep(String s) {
this.indentStep = s;
}
////////////////////////////////////////////////////////////////////
// Override methods from XMLWriter.
////////////////////////////////////////////////////////////////////
/**
* Reset the writer so that it can be reused.
*
* <p>This method is especially useful if the writer failed
* with an exception the last time through.</p>
*
* @see XMLWriter#reset()
*/
public void reset ()
{
depth = 0;
state = SEEN_NOTHING;
stateStack = new Stack<Object>();
super.reset();
}
protected void writeXmlDecl(String decl) throws IOException {
super.writeXmlDecl(decl);
write('\n');
}
/**
* Write a start tag.
*
* <p>Each tag will begin on a new line, and will be
* indented by the current indent step times the number
* of ancestors that the element has.</p>
*
* <p>The newline and indentation will be passed on down
* the filter chain through regular characters events.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @param qName The element's qualified (prefixed) name.
* @param atts The element's attribute list.
* @exception org.xml.sax.SAXException If there is an error
* writing the start tag, or if a filter further
* down the chain raises an exception.
* @see XMLWriter#startElement(String, String, String, Attributes)
*/
public void startElement (String uri, String localName,
String qName, Attributes atts)
throws SAXException
{
stateStack.push(SEEN_ELEMENT);
state = SEEN_NOTHING;
if (depth > 0) {
super.characters("\n");
}
doIndent();
super.startElement(uri, localName, qName, atts);
depth++;
}
/**
* Write an end tag.
*
* <p>If the element has contained other elements, the tag
* will appear indented on a new line; otherwise, it will
* appear immediately following whatever came before.</p>
*
* <p>The newline and indentation will be passed on down
* the filter chain through regular characters events.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @param qName The element's qualified (prefixed) name.
* @exception org.xml.sax.SAXException If there is an error
* writing the end tag, or if a filter further
* down the chain raises an exception.
* @see XMLWriter#endElement(String, String, String)
*/
public void endElement (String uri, String localName, String qName)
throws SAXException
{
depth--;
if (state == SEEN_ELEMENT) {
super.characters("\n");
doIndent();
}
super.endElement(uri, localName, qName);
state = stateStack.pop();
}
public void endDocument() throws SAXException {
try {
write('\n');
} catch( IOException e ) {
throw new SAXException(e);
}
super.endDocument();
}
// /**
// * Write a empty element tag.
// *
// * <p>Each tag will appear on a new line, and will be
// * indented by the current indent step times the number
// * of ancestors that the element has.</p>
// *
// * <p>The newline and indentation will be passed on down
// * the filter chain through regular characters events.</p>
// *
// * @param uri The element's Namespace URI.
// * @param localName The element's local name.
// * @param qName The element's qualified (prefixed) name.
// * @param atts The element's attribute list.
// * @exception org.xml.sax.SAXException If there is an error
// * writing the empty tag, or if a filter further
// * down the chain raises an exception.
// * @see XMLWriter#emptyElement(String, String, String, Attributes)
// */
// public void emptyElement (String uri, String localName,
// String qName, Attributes atts)
// throws SAXException
// {
// state = SEEN_ELEMENT;
// if (depth > 0) {
// super.characters("\n");
// }
// doIndent();
// super.emptyElement(uri, localName, qName, atts);
// }
/**
* Write a sequence of characters.
*
* @param ch The characters to write.
* @param start The starting position in the array.
* @param length The number of characters to use.
* @exception org.xml.sax.SAXException If there is an error
* writing the characters, or if a filter further
* down the chain raises an exception.
* @see XMLWriter#characters(char[], int, int)
*/
public void characters (char ch[], int start, int length)
throws SAXException
{
state = SEEN_DATA;
super.characters(ch, start, length);
}
////////////////////////////////////////////////////////////////////
// Internal methods.
////////////////////////////////////////////////////////////////////
/**
* Print indentation for the current level.
*
* @exception org.xml.sax.SAXException If there is an error
* writing the indentation characters, or if a filter
* further down the chain raises an exception.
*/
private void doIndent ()
throws SAXException
{
if (depth > 0) {
char[] ch = indentStep.toCharArray();
for( int i=0; i<depth; i++ )
characters(ch, 0, ch.length);
}
}
////////////////////////////////////////////////////////////////////
// Constants.
////////////////////////////////////////////////////////////////////
private final static Object SEEN_NOTHING = new Object();
private final static Object SEEN_ELEMENT = new Object();
private final static Object SEEN_DATA = new Object();
////////////////////////////////////////////////////////////////////
// Internal state.
////////////////////////////////////////////////////////////////////
private Object state = SEEN_NOTHING;
private Stack<Object> stateStack = new Stack<Object>();
private String indentStep = "";
private int depth = 0;
}
// end of DataWriter.java

View File

@@ -0,0 +1,79 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
/**
* Escape everything above the US-ASCII code range.
* A fallback position.
*
* Works with any JDK, any encoding.
*
* @since 1.0.1
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class DumbEscapeHandler implements CharacterEscapeHandler {
private DumbEscapeHandler() {} // no instanciation please
public static final CharacterEscapeHandler theInstance = new DumbEscapeHandler();
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
int limit = start+length;
for (int i = start; i < limit; i++) {
switch (ch[i]) {
case '&':
out.write("&amp;");
break;
case '<':
out.write("&lt;");
break;
case '>':
out.write("&gt;");
break;
case '\"':
if (isAttVal) {
out.write("&quot;");
} else {
out.write('\"');
}
break;
default:
if (ch[i] > '\u007f') {
out.write("&#");
out.write(Integer.toString(ch[i]));
out.write(';');
} else {
out.write(ch[i]);
}
}
}
}
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* Formats error messages.
*
* @since JAXB1.0
*/
public class Messages
{
public static String format( String property ) {
return format( property, null );
}
public static String format( String property, Object arg1 ) {
return format( property, new Object[]{arg1} );
}
public static String format( String property, Object arg1, Object arg2 ) {
return format( property, new Object[]{arg1,arg2} );
}
public static String format( String property, Object arg1, Object arg2, Object arg3 ) {
return format( property, new Object[]{arg1,arg2,arg3} );
}
// add more if necessary.
/** Loads a string resource and formats it with specified arguments. */
static String format( String property, Object[] args ) {
String text = ResourceBundle.getBundle(Messages.class.getName()).getString(property);
return MessageFormat.format(text,args);
}
//
//
// Message resources
//
//
public static final String NOT_MARSHALLABLE = // 0 args
"MarshallerImpl.NotMarshallable";
public static final String UNSUPPORTED_RESULT = // 0 args
"MarshallerImpl.UnsupportedResult";
public static final String UNSUPPORTED_ENCODING = // 1 arg
"MarshallerImpl.UnsupportedEncoding";
public static final String NULL_WRITER = // 0 args
"MarshallerImpl.NullWriterParam";
public static final String ASSERT_FAILED = // 0 args
"SAXMarshaller.AssertFailed";
/**
* @deprecated use ERR_MISSING_OBJECT2
*/
public static final String ERR_MISSING_OBJECT = // 0 args
"SAXMarshaller.MissingObject";
/**
* @deprecated
* use {@link com.sun.xml.internal.bind.v2.runtime.XMLSerializer#reportMissingObjectError(String)}
* Usage not found. TODO Remove
*/
// public static final String ERR_MISSING_OBJECT2 = // 1 arg
// "SAXMarshaller.MissingObject2";
/**
* @deprecated only used from 1.0
*/
public static final String ERR_DANGLING_IDREF = // 1 arg
"SAXMarshaller.DanglingIDREF";
/**
* @deprecated only used from 1.0
*/
public static final String ERR_NOT_IDENTIFIABLE = // 0 args
"SAXMarshaller.NotIdentifiable";
public static final String DOM_IMPL_DOESNT_SUPPORT_CREATELEMENTNS = // 2 args
"SAX2DOMEx.DomImplDoesntSupportCreateElementNs";
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
/**
* Performs no character escaping. Usable only when the output encoding
* is UTF, but this handler gives the maximum performance.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class MinimumEscapeHandler implements CharacterEscapeHandler {
private MinimumEscapeHandler() {} // no instanciation please
public static final CharacterEscapeHandler theInstance = new MinimumEscapeHandler();
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
// avoid calling the Writerwrite method too much by assuming
// that the escaping occurs rarely.
// profiling revealed that this is faster than the naive code.
int limit = start+length;
for (int i = start; i < limit; i++) {
char c = ch[i];
if(c == '&' || c == '<' || c == '>' || c == '\r' || (c == '\"' && isAttVal) ) {
if(i!=start)
out.write(ch,start,i-start);
start = i+1;
switch (ch[i]) {
case '&':
out.write("&amp;");
break;
case '<':
out.write("&lt;");
break;
case '>':
out.write("&gt;");
break;
case '\"':
out.write("&quot;");
break;
}
}
}
if( start!=limit )
out.write(ch,start,limit-start);
}
}

View File

@@ -0,0 +1,256 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.io.OutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
import org.w3c.dom.Node;
// be careful about changing this class. this class is supposed to be
// extended by users and therefore we are not allowed to break
// those user code.
//
// this means:
// - don't add any abstract method
// - don't change any existing method signature
// - don't remove any existing method.
/**
* Implemented by the user application to determine URI -> prefix
* mapping.
*
* This is considered as an interface, though it's implemented
* as an abstract class to make it easy to add new methods in
* a future.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public abstract class NamespacePrefixMapper {
private static final String[] EMPTY_STRING = new String[0];
/**
* Returns a preferred prefix for the given namespace URI.
*
* This method is intended to be overrided by a derived class.
*
* <p>
* As noted in the return value portion of the javadoc, there
* are several cases where the preference cannot be honored.
* Specifically, as of JAXB RI 2.0 and onward:
*
* <ol>
* <li>
* If the prefix returned is already in use as one of the in-scope
* namespace bindings. This is partly necessary for correctness
* (so that we don't unexpectedly change the meaning of QNames
* bound to {@link String}), partly to simplify the marshaller.
* <li>
* If the prefix returned is "" yet the current {@link JAXBContext}
* includes classes that use the empty namespace URI. This allows
* the JAXB RI to reserve the "" prefix for the empty namespace URI,
* which is the only possible prefix for the URI.
* This restriction is also to simplify the marshaller.
* </ol>
*
* @param namespaceUri
* The namespace URI for which the prefix needs to be found.
* Never be null. "" is used to denote the default namespace.
* @param suggestion
* When the content tree has a suggestion for the prefix
* to the given namespaceUri, that suggestion is passed as a
* parameter. Typicall this value comes from the QName.getPrefix
* to show the preference of the content tree. This parameter
* may be null, and this parameter may represent an already
* occupied prefix.
* @param requirePrefix
* If this method is expected to return non-empty prefix.
* When this flag is true, it means that the given namespace URI
* cannot be set as the default namespace.
*
* @return
* null if there's no prefered prefix for the namespace URI.
* In this case, the system will generate a prefix for you.
*
* Otherwise the system will try to use the returned prefix,
* but generally there's no guarantee if the prefix will be
* actually used or not.
*
* return "" to map this namespace URI to the default namespace.
* Again, there's no guarantee that this preference will be
* honored.
*
* If this method returns "" when requirePrefix=true, the return
* value will be ignored and the system will generate one.
*
* @since JAXB 1.0.1
*/
public abstract String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix);
/**
* Returns a list of namespace URIs that should be declared
* at the root element.
*
* <p>
* By default, the JAXB RI 1.0.x produces namespace declarations only when
* they are necessary, only at where they are used. Because of this
* lack of look-ahead, sometimes the marshaller produces a lot of
* namespace declarations that look redundant to human eyes. For example,
* <pre><xmp>
* <?xml version="1.0"?>
* <root>
* <ns1:child xmlns:ns1="urn:foo"> ... </ns1:child>
* <ns2:child xmlns:ns2="urn:foo"> ... </ns2:child>
* <ns3:child xmlns:ns3="urn:foo"> ... </ns3:child>
* ...
* </root>
* </xmp></pre>
*
* <p>
* The JAXB RI 2.x mostly doesn't exhibit this behavior any more,
* as it declares all statically known namespace URIs (those URIs
* that are used as element/attribute names in JAXB annotations),
* but it may still declare additional namespaces in the middle of
* a document, for example when (i) a QName as an attribute/element value
* requires a new namespace URI, or (ii) DOM nodes as a portion of an object
* tree requires a new namespace URI.
*
* <p>
* If you know in advance that you are going to use a certain set of
* namespace URIs, you can override this method and have the marshaller
* declare those namespace URIs at the root element.
*
* <p>
* For example, by returning <code>new String[]{"urn:foo"}</code>,
* the marshaller will produce:
* <pre><xmp>
* <?xml version="1.0"?>
* <root xmlns:ns1="urn:foo">
* <ns1:child> ... </ns1:child>
* <ns1:child> ... </ns1:child>
* <ns1:child> ... </ns1:child>
* ...
* </root>
* </xmp></pre>
* <p>
* To control prefixes assigned to those namespace URIs, use the
* {@link #getPreferredPrefix(String, String, boolean)} method.
*
* @return
* A list of namespace URIs as an array of {@link String}s.
* This method can return a length-zero array but not null.
* None of the array component can be null. To represent
* the empty namespace, use the empty string <code>""</code>.
*
* @since
* JAXB RI 1.0.2
*/
public String[] getPreDeclaredNamespaceUris() {
return EMPTY_STRING;
}
/**
* Similar to {@link #getPreDeclaredNamespaceUris()} but allows the
* (prefix,nsUri) pairs to be returned.
*
* <p>
* With {@link #getPreDeclaredNamespaceUris()}, applications who wish to control
* the prefixes as well as the namespaces needed to implement both
* {@link #getPreDeclaredNamespaceUris()} and {@link #getPreferredPrefix(String, String, boolean)}.
*
* <p>
* This version eliminates the needs by returning an array of pairs.
*
* @return
* always return a non-null (but possibly empty) array. The array stores
* data like (prefix1,nsUri1,prefix2,nsUri2,...) Use an empty string to represent
* the empty namespace URI and the default prefix. Null is not allowed as a value
* in the array.
*
* @since
* JAXB RI 2.0 beta
*/
public String[] getPreDeclaredNamespaceUris2() {
return EMPTY_STRING;
}
/**
* Returns a list of (prefix,namespace URI) pairs that represents
* namespace bindings available on ancestor elements (that need not be repeated
* by the JAXB RI.)
*
* <p>
* Sometimes JAXB is used to marshal an XML document, which will be
* used as a subtree of a bigger document. When this happens, it's nice
* for a JAXB marshaller to be able to use in-scope namespace bindings
* of the larger document and avoid declaring redundant namespace URIs.
*
* <p>
* This is automatically done when you are marshalling to {@link XMLStreamWriter},
* {@link XMLEventWriter}, {@link DOMResult}, or {@link Node}, because
* those output format allows us to inspect what's currently available
* as in-scope namespace binding. However, with other output format,
* such as {@link OutputStream}, the JAXB RI cannot do this automatically.
* That's when this method comes into play.
*
* <p>
* Namespace bindings returned by this method will be used by the JAXB RI,
* but will not be re-declared. They are assumed to be available when you insert
* this subtree into a bigger document.
*
* <p>
* It is <b>NOT</b> OK to return the same binding, or give
* the receiver a conflicting binding information.
* It's a responsibility of the caller to make sure that this doesn't happen
* even if the ancestor elements look like:
* <pre><xmp>
* <foo:abc xmlns:foo="abc">
* <foo:abc xmlns:foo="def">
* <foo:abc xmlns:foo="abc">
* ... JAXB marshalling into here.
* </foo:abc>
* </foo:abc>
* </foo:abc>
* </xmp></pre>
*
* @return
* always return a non-null (but possibly empty) array. The array stores
* data like (prefix1,nsUri1,prefix2,nsUri2,...) Use an empty string to represent
* the empty namespace URI and the default prefix. Null is not allowed as a value
* in the array.
*
* @since JAXB RI 2.0 beta
*/
public String[] getContextualNamespaceDecls() {
return EMPTY_STRING;
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
/**
* Uses JDK1.4 NIO functionality to escape characters smartly.
*
* @since 1.0.1
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class NioEscapeHandler implements CharacterEscapeHandler {
private final CharsetEncoder encoder;
// exposing those variations upset javac 1.3.1, since it needs to
// know about those classes to determine which overloaded version
// of the method it wants to use. So comment it out for the compatibility.
// public NioEscapeHandler(CharsetEncoder _encoder) {
// this.encoder = _encoder;
// if(encoder==null)
// throw new NullPointerException();
// }
//
// public NioEscapeHandler(Charset charset) {
// this(charset.newEncoder());
// }
public NioEscapeHandler(String charsetName) {
// this(Charset.forName(charsetName));
this.encoder = Charset.forName(charsetName).newEncoder();
}
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
int limit = start+length;
for (int i = start; i < limit; i++) {
switch (ch[i]) {
case '&':
out.write("&amp;");
break;
case '<':
out.write("&lt;");
break;
case '>':
out.write("&gt;");
break;
case '\"':
if (isAttVal) {
out.write("&quot;");
} else {
out.write('\"');
}
break;
default:
if( encoder.canEncode(ch[i]) ) {
out.write(ch[i]);
} else {
out.write("&#");
out.write(Integer.toString(ch[i]));
out.write(';');
}
}
}
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright (c) 2017, 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 com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
/**
* Performs no character escaping.
*
* @author
* Roman Grigoriadi (roman.grigoriadi@oracle.com)
*/
public class NoEscapeHandler implements CharacterEscapeHandler {
public static final NoEscapeHandler theInstance = new NoEscapeHandler();
@Override
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
out.write(ch, start, length);
}
}

View File

@@ -0,0 +1,234 @@
/*
* Copyright (c) 1997, 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 com.sun.xml.internal.bind.marshaller;
import java.util.Stack;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import com.sun.xml.internal.bind.util.Which;
import com.sun.istack.internal.FinalArrayList;
import com.sun.xml.internal.bind.v2.util.XmlFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
/**
* Builds a DOM tree from SAX2 events.
*
* @author Vivek Pandey
* @since 1.0
*/
public class SAX2DOMEx implements ContentHandler {
private Node node = null;
private boolean isConsolidate;
protected final Stack<Node> nodeStack = new Stack<Node>();
private final FinalArrayList<String> unprocessedNamespaces = new FinalArrayList<String>();
/**
* Document object that owns the specified node.
*/
protected final Document document;
/**
* @param node
* Nodes will be created and added under this object.
*/
public SAX2DOMEx(Node node) {
this(node, false);
}
/**
* @param node
* Nodes will be created and added under this object.
*/
public SAX2DOMEx(Node node, boolean isConsolidate) {
this.node = node;
this.isConsolidate = isConsolidate;
nodeStack.push(this.node);
if (node instanceof Document) {
this.document = (Document) node;
} else {
this.document = node.getOwnerDocument();
}
}
/**
* Creates a fresh empty DOM document and adds nodes under this document.
*/
public SAX2DOMEx(DocumentBuilderFactory f) throws ParserConfigurationException {
f.setValidating(false);
document = f.newDocumentBuilder().newDocument();
node = document;
nodeStack.push(document);
}
/**
* Creates a fresh empty DOM document and adds nodes under this document.
* @deprecated
*/
public SAX2DOMEx() throws ParserConfigurationException {
DocumentBuilderFactory factory = XmlFactory.createDocumentBuilderFactory(false);
factory.setValidating(false);
document = factory.newDocumentBuilder().newDocument();
node = document;
nodeStack.push(document);
}
public final Element getCurrentElement() {
return (Element) nodeStack.peek();
}
public Node getDOM() {
return node;
}
public void startDocument() {
}
public void endDocument() {
}
protected void namespace(Element element, String prefix, String uri) {
String qname;
if ("".equals(prefix) || prefix == null) {
qname = "xmlns";
} else {
qname = "xmlns:" + prefix;
}
// older version of Xerces (I confirmed that the bug is gone with Xerces 2.4.0)
// have a problem of re-setting the same namespace attribute twice.
// work around this bug removing it first.
if (element.hasAttributeNS("http://www.w3.org/2000/xmlns/", qname)) {
// further workaround for an old Crimson bug where the removeAttribtueNS
// method throws NPE when the element doesn't have any attribute.
// to be on the safe side, check the existence of attributes before
// attempting to remove it.
// for details about this bug, see org.apache.crimson.tree.ElementNode2
// line 540 or the following message:
// https://jaxb.dev.java.net/servlets/ReadMsg?list=users&msgNo=2767
element.removeAttributeNS("http://www.w3.org/2000/xmlns/", qname);
}
// workaround until here
element.setAttributeNS("http://www.w3.org/2000/xmlns/", qname, uri);
}
public void startElement(String namespace, String localName, String qName, Attributes attrs) {
Node parent = nodeStack.peek();
// some broken DOM implementation (we confirmed it with SAXON)
// return null from this method.
Element element = document.createElementNS(namespace, qName);
if (element == null) {
// if so, report an user-friendly error message,
// rather than dying mysteriously with NPE.
throw new AssertionError(
Messages.format(Messages.DOM_IMPL_DOESNT_SUPPORT_CREATELEMENTNS,
document.getClass().getName(),
Which.which(document.getClass())));
}
// process namespace bindings
for (int i = 0; i < unprocessedNamespaces.size(); i += 2) {
String prefix = unprocessedNamespaces.get(i);
String uri = unprocessedNamespaces.get(i + 1);
namespace(element, prefix, uri);
}
unprocessedNamespaces.clear();
if (attrs != null) {
int length = attrs.getLength();
for (int i = 0; i < length; i++) {
String namespaceuri = attrs.getURI(i);
String value = attrs.getValue(i);
String qname = attrs.getQName(i);
element.setAttributeNS(namespaceuri, qname, value);
}
}
// append this new node onto current stack node
parent.appendChild(element);
// push this node onto stack
nodeStack.push(element);
}
public void endElement(String namespace, String localName, String qName) {
nodeStack.pop();
}
public void characters(char[] ch, int start, int length) {
characters(new String(ch, start, length));
}
protected Text characters(String s) {
Node parent = nodeStack.peek();
Node lastChild = parent.getLastChild();
Text text;
if (isConsolidate && lastChild != null && lastChild.getNodeType() == Node.TEXT_NODE) {
text = (Text) lastChild;
text.appendData(s);
} else {
text = document.createTextNode(s);
parent.appendChild(text);
}
return text;
}
public void ignorableWhitespace(char[] ch, int start, int length) {
}
public void processingInstruction(String target, String data) throws org.xml.sax.SAXException {
Node parent = nodeStack.peek();
Node n = document.createProcessingInstruction(target, data);
parent.appendChild(n);
}
public void setDocumentLocator(Locator locator) {
}
public void skippedEntity(String name) {
}
public void startPrefixMapping(String prefix, String uri) {
unprocessedNamespaces.add(prefix);
unprocessedNamespaces.add(uri);
}
public void endPrefixMapping(String prefix) {
}
}

View File

@@ -0,0 +1,976 @@
/*
* Copyright (c) 1997, 2011, 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.
*/
// @@3RD PARTY CODE@@
// XMLWriter.java - serialize an XML document.
// Written by David Megginson, david@megginson.com
// NO WARRANTY! This class is in the public domain.
// Id: XMLWriter.java,v 1.5 2000/09/17 01:08:16 david Exp
package com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.XMLFilterImpl;
/**
* Filter to write an XML document from a SAX event stream.
*
* <p>This class can be used by itself or as part of a SAX event
* stream: it takes as input a series of SAX2 ContentHandler
* events and uses the information in those events to write
* an XML document. Since this class is a filter, it can also
* pass the events on down a filter chain for further processing
* (you can use the XMLWriter to take a snapshot of the current
* state at any point in a filter chain), and it can be
* used directly as a ContentHandler for a SAX2 XMLReader.</p>
*
* <p>The client creates a document by invoking the methods for
* standard SAX2 events, always beginning with the
* {@link #startDocument startDocument} method and ending with
* the {@link #endDocument endDocument} method. There are convenience
* methods provided so that clients to not have to create empty
* attribute lists or provide empty strings as parameters; for
* example, the method invocation</p>
*
* <pre>
* w.startElement("foo");
* </pre>
*
* <p>is equivalent to the regular SAX2 ContentHandler method</p>
*
* <pre>
* w.startElement("", "foo", "", new AttributesImpl());
* </pre>
*
* <p>Except that it is more efficient because it does not allocate
* a new empty attribute list each time. The following code will send
* a simple XML document to standard output:</p>
*
* <pre>
* XMLWriter w = new XMLWriter();
*
* w.startDocument();
* w.startElement("greeting");
* w.characters("Hello, world!");
* w.endElement("greeting");
* w.endDocument();
* </pre>
*
* <p>The resulting document will look like this:</p>
*
* <pre>
* &lt;?xml version="1.0" standalone="yes"?>
*
* &lt;greeting>Hello, world!&lt;/greeting>
* </pre>
*
* <p>In fact, there is an even simpler convenience method,
* <var>dataElement</var>, designed for writing elements that
* contain only character data, so the code to generate the
* document could be shortened to</p>
*
* <pre>
* XMLWriter w = new XMLWriter();
*
* w.startDocument();
* w.dataElement("greeting", "Hello, world!");
* w.endDocument();
* </pre>
*
* <h2>Whitespace</h2>
*
* <p>According to the XML Recommendation, <em>all</em> whitespace
* in an XML document is potentially significant to an application,
* so this class never adds newlines or indentation. If you
* insert three elements in a row, as in</p>
*
* <pre>
* w.dataElement("item", "1");
* w.dataElement("item", "2");
* w.dataElement("item", "3");
* </pre>
*
* <p>you will end up with</p>
*
* <pre>
* &lt;item>1&lt;/item>&lt;item>3&lt;/item>&lt;item>3&lt;/item>
* </pre>
*
* <p>You need to invoke one of the <var>characters</var> methods
* explicitly to add newlines or indentation. Alternatively, you
* can use {@link DataWriter}, which
* is derived from this class -- it is optimized for writing
* purely data-oriented (or field-oriented) XML, and does automatic
* linebreaks and indentation (but does not support mixed content
* properly).</p>
*
*
* <h2>Namespace Support</h2>
*
* <p>The writer contains extensive support for XML Namespaces, so that
* a client application does not have to keep track of prefixes and
* supply <var>xmlns</var> attributes. By default, the XML writer will
* generate Namespace declarations in the form _NS1, _NS2, etc., wherever
* they are needed, as in the following example:</p>
*
* <pre>
* w.startDocument();
* w.emptyElement("http://www.foo.com/ns/", "foo");
* w.endDocument();
* </pre>
*
* <p>The resulting document will look like this:</p>
*
* <pre>
* &lt;?xml version="1.0" standalone="yes"?>
*
* &lt;_NS1:foo xmlns:_NS1="http://www.foo.com/ns/"/>
* </pre>
*
* <p>In many cases, document authors will prefer to choose their
* own prefixes rather than using the (ugly) default names. The
* XML writer allows two methods for selecting prefixes:</p>
*
* <ol>
* <li>the qualified name</li>
* </ol>
*
* <p>Whenever the XML writer finds a new Namespace URI, it checks
* to see if a qualified (prefixed) name is also available; if so
* it attempts to use the name's prefix (as long as the prefix is
* not already in use for another Namespace URI).</p>
*
* <p>The resulting document will look like this:</p>
*
* <pre>
* &lt;?xml version="1.0" standalone="yes"?>
*
* &lt;foo:foo xmlns:foo="http://www.foo.com/ns/"/>
* </pre>
*
* <p>The default Namespace simply uses an empty string as the prefix:</p>
*
* <pre>
* w.setPrefix("http://www.foo.com/ns/", "");
* w.startDocument();
* w.emptyElement("http://www.foo.com/ns/", "foo");
* w.endDocument();
* </pre>
*
* <p>The resulting document will look like this:</p>
*
* <pre>
* &lt;?xml version="1.0" standalone="yes"?>
*
* &lt;foo xmlns="http://www.foo.com/ns/"/>
* </pre>
*
* <p>By default, the XML writer will not declare a Namespace until
* it is actually used. Sometimes, this approach will create
* a large number of Namespace declarations, as in the following
* example:</p>
*
* <pre>
* &lt;xml version="1.0" standalone="yes"?>
*
* &lt;rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
* &lt;rdf:Description about="http://www.foo.com/ids/books/12345">
* &lt;dc:title xmlns:dc="http://www.purl.org/dc/">A Dark Night&lt;/dc:title>
* &lt;dc:creator xmlns:dc="http://www.purl.org/dc/">Jane Smith&lt;/dc:title>
* &lt;dc:date xmlns:dc="http://www.purl.org/dc/">2000-09-09&lt;/dc:title>
* &lt;/rdf:Description>
* &lt;/rdf:RDF>
* </pre>
*
* <p>The "rdf" prefix is declared only once, because the RDF Namespace
* is used by the root element and can be inherited by all of its
* descendants; the "dc" prefix, on the other hand, is declared three
* times, because no higher element uses the Namespace. To solve this
* problem, you can instruct the XML writer to predeclare Namespaces
* on the root element even if they are not used there:</p>
*
* <pre>
* w.forceNSDecl("http://www.purl.org/dc/");
* </pre>
*
* <p>Now, the "dc" prefix will be declared on the root element even
* though it's not needed there, and can be inherited by its
* descendants:</p>
*
* <pre>
* &lt;xml version="1.0" standalone="yes"?>
*
* &lt;rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
* xmlns:dc="http://www.purl.org/dc/">
* &lt;rdf:Description about="http://www.foo.com/ids/books/12345">
* &lt;dc:title>A Dark Night&lt;/dc:title>
* &lt;dc:creator>Jane Smith&lt;/dc:title>
* &lt;dc:date>2000-09-09&lt;/dc:title>
* &lt;/rdf:Description>
* &lt;/rdf:RDF>
* </pre>
*
* <p>This approach is also useful for declaring Namespace prefixes
* that be used by qualified names appearing in attribute values or
* character data.</p>
*
* @author David Megginson, david@megginson.com
* @version 0.2
* @since JAXB1.0
* @see org.xml.sax.XMLFilter
* @see org.xml.sax.ContentHandler
*/
public class XMLWriter extends XMLFilterImpl
{
////////////////////////////////////////////////////////////////////
// Constructors.
////////////////////////////////////////////////////////////////////
/**
* Create a new XML writer.
*
* <p>Write to the writer provided.</p>
*
* @param writer
* The output destination, or null to use standard output.
* @param encoding
* If non-null string is specified, it is written as a part
* of the XML declaration.
*/
public XMLWriter (Writer writer, String encoding, CharacterEscapeHandler _escapeHandler )
{
init(writer,encoding);
this.escapeHandler = _escapeHandler;
}
public XMLWriter (Writer writer, String encoding ) {
this( writer, encoding, DumbEscapeHandler.theInstance );
}
/**
* Internal initialization method.
*
* <p>All of the public constructors invoke this method.
*
* @param writer The output destination, or null to use
* standard output.
*/
private void init (Writer writer,String encoding)
{
setOutput(writer,encoding);
}
////////////////////////////////////////////////////////////////////
// Public methods.
////////////////////////////////////////////////////////////////////
/**
* Reset the writer.
*
* <p>This method is especially useful if the writer throws an
* exception before it is finished, and you want to reuse the
* writer for a new document. It is usually a good idea to
* invoke {@link #flush flush} before resetting the writer,
* to make sure that no output is lost.</p>
*
* <p>This method is invoked automatically by the
* {@link #startDocument startDocument} method before writing
* a new document.</p>
*
* <p><strong>Note:</strong> this method will <em>not</em>
* clear the prefix or URI information in the writer or
* the selected output writer.</p>
*
* @see #flush()
*/
public void reset ()
{
elementLevel = 0;
startTagIsClosed = true;
}
/**
* Flush the output.
*
* <p>This method flushes the output stream. It is especially useful
* when you need to make certain that the entire document has
* been written to output but do not want to close the output
* stream.</p>
*
* <p>This method is invoked automatically by the
* {@link #endDocument endDocument} method after writing a
* document.</p>
*
* @see #reset()
*/
public void flush ()
throws IOException
{
output.flush();
}
/**
* Set a new output destination for the document.
*
* @param writer The output destination, or null to use
* standard output.
* @see #flush()
*/
public void setOutput (Writer writer,String _encoding)
{
if (writer == null) {
output = new OutputStreamWriter(System.out);
} else {
output = writer;
}
encoding = _encoding;
}
/**
* Set whether the writer should print out the XML declaration
* (&lt;?xml version='1.0' ... ?>).
* <p>
* This option is set to true by default.
*/
public void setXmlDecl( boolean _writeXmlDecl ) {
this.writeXmlDecl = _writeXmlDecl;
}
/**
* Sets the header string.
*
* This string will be written right after the xml declaration
* without any escaping. Useful for generating a boiler-plate
* DOCTYPE decl, PIs, and comments.
*
* @param _header
* passing null will work as if the empty string is passed.
*/
public void setHeader( String _header ) {
this.header = _header;
}
private final HashMap<String,String> locallyDeclaredPrefix = new HashMap<String,String>();
public void startPrefixMapping( String prefix, String uri ) throws SAXException {
locallyDeclaredPrefix.put(prefix,uri);
}
////////////////////////////////////////////////////////////////////
// Methods from org.xml.sax.ContentHandler.
////////////////////////////////////////////////////////////////////
/**
* Write the XML declaration at the beginning of the document.
*
* Pass the event on down the filter chain for further processing.
*
* @exception org.xml.sax.SAXException If there is an error
* writing the XML declaration, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#startDocument()
*/
public void startDocument ()
throws SAXException
{
try {
reset();
if(writeXmlDecl) {
String e="";
if(encoding!=null)
e = " encoding=\""+encoding+'\"';
writeXmlDecl("<?xml version=\"1.0\""+e +" standalone=\"yes\"?>");
}
if(header!=null)
write(header);
super.startDocument();
} catch( IOException e ) {
throw new SAXException(e);
}
}
protected void writeXmlDecl(String decl) throws IOException {
write(decl);
}
/**
* Write a newline at the end of the document.
*
* Pass the event on down the filter chain for further processing.
*
* @exception org.xml.sax.SAXException If there is an error
* writing the newline, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#endDocument()
*/
public void endDocument ()
throws SAXException
{
try {
super.endDocument();
flush();
} catch( IOException e ) {
throw new SAXException(e);
}
}
/**
* Write a start tag.
*
* Pass the event on down the filter chain for further processing.
*
* @param uri The Namespace URI, or the empty string if none
* is available.
* @param localName The element's local (unprefixed) name (required).
* @param qName The element's qualified (prefixed) name, or the
* empty string is none is available. This method will
* use the qName as a template for generating a prefix
* if necessary, but it is not guaranteed to use the
* same qName.
* @param atts The element's attribute list (must not be null).
* @exception org.xml.sax.SAXException If there is an error
* writing the start tag, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement (String uri, String localName,
String qName, Attributes atts)
throws SAXException
{
try {
if (!startTagIsClosed) {
write(">");
}
elementLevel++;
// nsSupport.pushContext();
write('<');
write(qName);
writeAttributes(atts);
// declare namespaces specified by the startPrefixMapping methods
if(!locallyDeclaredPrefix.isEmpty()) {
for (Map.Entry<String,String> e : locallyDeclaredPrefix.entrySet()) {
String p = e.getKey();
String u = e.getValue();
if (u == null) {
u = "";
}
write(' ');
if ("".equals(p)) {
write("xmlns=\"");
} else {
write("xmlns:");
write(p);
write("=\"");
}
char ch[] = u.toCharArray();
writeEsc(ch, 0, ch.length, true);
write('\"');
}
locallyDeclaredPrefix.clear(); // clear the contents
}
// if (elementLevel == 1) {
// forceNSDecls();
// }
// writeNSDecls();
super.startElement(uri, localName, qName, atts);
startTagIsClosed = false;
} catch( IOException e ) {
throw new SAXException(e);
}
}
/**
* Write an end tag.
*
* Pass the event on down the filter chain for further processing.
*
* @param uri The Namespace URI, or the empty string if none
* is available.
* @param localName The element's local (unprefixed) name (required).
* @param qName The element's qualified (prefixed) name, or the
* empty string is none is available. This method will
* use the qName as a template for generating a prefix
* if necessary, but it is not guaranteed to use the
* same qName.
* @exception org.xml.sax.SAXException If there is an error
* writing the end tag, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
public void endElement (String uri, String localName, String qName)
throws SAXException
{
try {
if (startTagIsClosed) {
write("</");
write(qName);
write('>');
} else {
write("/>");
startTagIsClosed = true;
}
super.endElement(uri, localName, qName);
// nsSupport.popContext();
elementLevel--;
} catch( IOException e ) {
throw new SAXException(e);
}
}
/**
* Write character data.
*
* Pass the event on down the filter chain for further processing.
*
* @param ch The array of characters to write.
* @param start The starting position in the array.
* @param len The number of characters to write.
* @exception org.xml.sax.SAXException If there is an error
* writing the characters, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
public void characters (char ch[], int start, int len)
throws SAXException
{
try {
if (!startTagIsClosed) {
write('>');
startTagIsClosed = true;
}
writeEsc(ch, start, len, false);
super.characters(ch, start, len);
} catch( IOException e ) {
throw new SAXException(e);
}
}
/**
* Write ignorable whitespace.
*
* Pass the event on down the filter chain for further processing.
*
* @param ch The array of characters to write.
* @param start The starting position in the array.
* @param length The number of characters to write.
* @exception org.xml.sax.SAXException If there is an error
* writing the whitespace, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int)
*/
public void ignorableWhitespace (char ch[], int start, int length)
throws SAXException
{
try {
writeEsc(ch, start, length, false);
super.ignorableWhitespace(ch, start, length);
} catch( IOException e ) {
throw new SAXException(e);
}
}
/**
* Write a processing instruction.
*
* Pass the event on down the filter chain for further processing.
*
* @param target The PI target.
* @param data The PI data.
* @exception org.xml.sax.SAXException If there is an error
* writing the PI, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String)
*/
public void processingInstruction (String target, String data)
throws SAXException
{
try {
if (!startTagIsClosed) {
write('>');
startTagIsClosed = true;
}
write("<?");
write(target);
write(' ');
write(data);
write("?>");
if (elementLevel < 1) {
write('\n');
}
super.processingInstruction(target, data);
} catch( IOException e ) {
throw new SAXException(e);
}
}
////////////////////////////////////////////////////////////////////
// Convenience methods.
////////////////////////////////////////////////////////////////////
/**
* Start a new element without a qname or attributes.
*
* <p>This method will provide a default empty attribute
* list and an empty string for the qualified name.
* It invokes {@link
* #startElement(String, String, String, Attributes)}
* directly.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If there is an error
* writing the start tag, or if a handler further down
* the filter chain raises an exception.
* @see #startElement(String, String, String, Attributes)
*/
public void startElement (String uri, String localName)
throws SAXException
{
startElement(uri, localName, "", EMPTY_ATTS);
}
/**
* Start a new element without a qname, attributes or a Namespace URI.
*
* <p>This method will provide an empty string for the
* Namespace URI, and empty string for the qualified name,
* and a default empty attribute list. It invokes
* #startElement(String, String, String, Attributes)}
* directly.</p>
*
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If there is an error
* writing the start tag, or if a handler further down
* the filter chain raises an exception.
* @see #startElement(String, String, String, Attributes)
*/
public void startElement (String localName)
throws SAXException
{
startElement("", localName, "", EMPTY_ATTS);
}
/**
* End an element without a qname.
*
* <p>This method will supply an empty string for the qName.
* It invokes {@link #endElement(String, String, String)}
* directly.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If there is an error
* writing the end tag, or if a handler further down
* the filter chain raises an exception.
* @see #endElement(String, String, String)
*/
public void endElement (String uri, String localName)
throws SAXException
{
endElement(uri, localName, "");
}
/**
* End an element without a Namespace URI or qname.
*
* <p>This method will supply an empty string for the qName
* and an empty string for the Namespace URI.
* It invokes {@link #endElement(String, String, String)}
* directly.</p>
*
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If there is an error
* writing the end tag, or if a handler further down
* the filter chain raises an exception.
* @see #endElement(String, String, String)
*/
public void endElement (String localName)
throws SAXException
{
endElement("", localName, "");
}
/**
* Write an element with character data content.
*
* <p>This is a convenience method to write a complete element
* with character data content, including the start tag
* and end tag.</p>
*
* <p>This method invokes
* {@link #startElement(String, String, String, Attributes)},
* followed by
* {@link #characters(String)}, followed by
* {@link #endElement(String, String, String)}.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @param qName The element's default qualified name.
* @param atts The element's attributes.
* @param content The character data content.
* @exception org.xml.sax.SAXException If there is an error
* writing the empty tag, or if a handler further down
* the filter chain raises an exception.
* @see #startElement(String, String, String, Attributes)
* @see #characters(String)
* @see #endElement(String, String, String)
*/
public void dataElement (String uri, String localName,
String qName, Attributes atts,
String content)
throws SAXException
{
startElement(uri, localName, qName, atts);
characters(content);
endElement(uri, localName, qName);
}
/**
* Write an element with character data content but no attributes.
*
* <p>This is a convenience method to write a complete element
* with character data content, including the start tag
* and end tag. This method provides an empty string
* for the qname and an empty attribute list.</p>
*
* <p>This method invokes
* {@link #startElement(String, String, String, Attributes)},
* followed by
* {@link #characters(String)}, followed by
* {@link #endElement(String, String, String)}.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @param content The character data content.
* @exception org.xml.sax.SAXException If there is an error
* writing the empty tag, or if a handler further down
* the filter chain raises an exception.
* @see #startElement(String, String, String, Attributes)
* @see #characters(String)
* @see #endElement(String, String, String)
*/
public void dataElement (String uri, String localName, String content)
throws SAXException
{
dataElement(uri, localName, "", EMPTY_ATTS, content);
}
/**
* Write an element with character data content but no attributes or Namespace URI.
*
* <p>This is a convenience method to write a complete element
* with character data content, including the start tag
* and end tag. The method provides an empty string for the
* Namespace URI, and empty string for the qualified name,
* and an empty attribute list.</p>
*
* <p>This method invokes
* {@link #startElement(String, String, String, Attributes)},
* followed by
* {@link #characters(String)}, followed by
* {@link #endElement(String, String, String)}.</p>
*
* @param localName The element's local name.
* @param content The character data content.
* @exception org.xml.sax.SAXException If there is an error
* writing the empty tag, or if a handler further down
* the filter chain raises an exception.
* @see #startElement(String, String, String, Attributes)
* @see #characters(String)
* @see #endElement(String, String, String)
*/
public void dataElement (String localName, String content)
throws SAXException
{
dataElement("", localName, "", EMPTY_ATTS, content);
}
/**
* Write a string of character data, with XML escaping.
*
* <p>This is a convenience method that takes an XML
* String, converts it to a character array, then invokes
* {@link #characters(char[], int, int)}.</p>
*
* @param data The character data.
* @exception org.xml.sax.SAXException If there is an error
* writing the string, or if a handler further down
* the filter chain raises an exception.
* @see #characters(char[], int, int)
*/
public void characters (String data) throws SAXException {
try {
if (!startTagIsClosed) {
write('>');
startTagIsClosed = true;
}
char ch[] = data.toCharArray();
characters(ch, 0, ch.length);
} catch( IOException e ) {
throw new SAXException(e);
}
}
////////////////////////////////////////////////////////////////////
// Internal methods.
////////////////////////////////////////////////////////////////////
/**
* Write a raw character.
*
* @param c The character to write.
*/
protected final void write (char c) throws IOException {
output.write(c);
}
/**
* Write a raw string.
*/
protected final void write(String s) throws IOException {
output.write(s);
}
/**
* Write out an attribute list, escaping values.
*
* The names will have prefixes added to them.
*
* @param atts The attribute list to write.
*/
private void writeAttributes (Attributes atts) throws IOException {
int len = atts.getLength();
for (int i = 0; i < len; i++) {
char ch[] = atts.getValue(i).toCharArray();
write(' ');
write(atts.getQName(i));
write("=\"");
writeEsc(ch, 0, ch.length, true);
write('"');
}
}
/**
* Write an array of data characters with escaping.
*
* @param ch The array of characters.
* @param start The starting position.
* @param length The number of characters to use.
* @param isAttVal true if this is an attribute value literal.
*/
private void writeEsc (char ch[], int start,
int length, boolean isAttVal)
throws IOException
{
escapeHandler.escape(ch, start, length, isAttVal, output);
}
////////////////////////////////////////////////////////////////////
// Constants.
////////////////////////////////////////////////////////////////////
private final Attributes EMPTY_ATTS = new AttributesImpl();
////////////////////////////////////////////////////////////////////
// Internal state.
////////////////////////////////////////////////////////////////////
private int elementLevel = 0;
private Writer output;
private String encoding;
private boolean writeXmlDecl = true;
/**
* This string will be written right after the xml declaration
* without any escaping. Useful for generating a boiler-plate DOCTYPE decl
* , PIs, and comments.
*/
private String header=null;
private final CharacterEscapeHandler escapeHandler;
private boolean startTagIsClosed = true;
}
// end of XMLWriter.java