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,149 @@
/*
* Copyright (c) 2006, 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.stream.writers;
import java.io.Writer;
import java.io.OutputStream;
import java.io.IOException;
import com.sun.org.apache.xerces.internal.util.XMLChar;
/**
* <p>This class is used to write a stream of chars as a stream of
* bytes using the UTF8 encoding. It assumes that the underlying
* output stream is buffered or does not need additional buffering.</p>
*
* <p>It is more efficient than using a <code>java.io.OutputStreamWriter</code>
* because it does not need to be wrapped in a
* <code>java.io.BufferedWriter</code>. Creating multiple instances
* of <code>java.io.BufferedWriter</code> has been shown to be very
* expensive in JAX-WS.</p>
*
* @author Santiago.PericasGeertsen@sun.com
*/
public final class UTF8OutputStreamWriter extends Writer {
/**
* Undelying output stream. This class assumes that this
* output stream does not need buffering.
*/
OutputStream out;
/**
* Java represents chars that are not in the Basic Multilingual
* Plane (BMP) in UTF-16. This int stores the first code unit
* for a code point encoded in two UTF-16 code units.
*/
int lastUTF16CodePoint = 0;
public UTF8OutputStreamWriter(OutputStream out) {
this.out = out;
}
public String getEncoding() {
return "UTF-8";
}
public void write(int c) throws IOException {
// Check in we are encoding at high and low surrogates
if (lastUTF16CodePoint != 0) {
final int uc =
(((lastUTF16CodePoint & 0x3ff) << 10) | (c & 0x3ff)) + 0x10000;
if (uc < 0 || uc >= 0x200000) {
throw new IOException("Atttempting to write invalid Unicode code point '" + uc + "'");
}
out.write(0xF0 | (uc >> 18));
out.write(0x80 | ((uc >> 12) & 0x3F));
out.write(0x80 | ((uc >> 6) & 0x3F));
out.write(0x80 | (uc & 0x3F));
lastUTF16CodePoint = 0;
return;
}
// Otherwise, encode char as defined in UTF-8
if (c < 0x80) {
// 1 byte, 7 bits
out.write((int) c);
}
else if (c < 0x800) {
// 2 bytes, 11 bits
out.write(0xC0 | (c >> 6)); // first 5
out.write(0x80 | (c & 0x3F)); // second 6
}
else if (c <= '\uFFFF') {
if (!XMLChar.isHighSurrogate(c) && !XMLChar.isLowSurrogate(c)) {
// 3 bytes, 16 bits
out.write(0xE0 | (c >> 12)); // first 4
out.write(0x80 | ((c >> 6) & 0x3F)); // second 6
out.write(0x80 | (c & 0x3F)); // third 6
}
else {
lastUTF16CodePoint = c;
}
}
}
public void write(char cbuf[]) throws IOException {
for (int i = 0; i < cbuf.length; i++) {
write(cbuf[i]);
}
}
public void write(char cbuf[], int off, int len) throws IOException {
for (int i = 0; i < len; i++) {
write(cbuf[off + i]);
}
}
public void write(String str) throws IOException {
final int len = str.length();
for (int i = 0; i < len; i++) {
write(str.charAt(i));
}
}
public void write(String str, int off, int len) throws IOException {
for (int i = 0; i < len; i++) {
write(str.charAt(off + i));
}
}
public void flush() throws IOException {
out.flush();
}
public void close() throws IOException {
if (lastUTF16CodePoint != 0) {
throw new IllegalStateException("Attempting to close a UTF8OutputStreamWriter"
+ " while awaiting for a UTF-16 code unit");
}
out.close();
}
}

View File

@@ -0,0 +1,254 @@
/*
* Copyright (c) 2005, 2013, 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.stream.writers;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import com.sun.org.apache.xerces.internal.util.XMLChar;
import com.sun.org.apache.xerces.internal.utils.SecuritySupport;
/**
* Implements common xml writer functions.
*
* @author Neeraj Bajaj,K.Venugopal Sun Microsystems.
*/
public class WriterUtility {
public static final String START_COMMENT = "<!--";
public static final String END_COMMENT = "-->";
public static final String DEFAULT_ENCODING = " encoding=\"utf-8\"";
public static final String DEFAULT_XMLDECL ="<?xml version=\"1.0\" ?>";
public static final String DEFAULT_XML_VERSION ="1.0";
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 SPACE = " ";
public static final String UTF_8 = "utf-8";
static final boolean DEBUG_XML_CONTENT = false;
/**XXX: This feature is only used when writing element content values.
* default value is 'true' however, if the feature is set to false
* characters wont be escaped.
* This feature has no effect when writing Attribute values, character would still be escaped.
* I can't think of any reason why this would be useful when writing attribute values.
* However, this can be reconsidered if there is any usecase.
*/
boolean fEscapeCharacters = true ;
/** Writer object*/
Writer fWriter = null;
//CharsetEncoder
CharsetEncoder fEncoder ;
public WriterUtility(){
fEncoder = getDefaultEncoder();
}
/** Creates a new instance of WriterUtility */
public WriterUtility(Writer writer) {
fWriter = writer;
if(writer instanceof OutputStreamWriter){
String charset = ((OutputStreamWriter)writer).getEncoding();
if(charset != null){
fEncoder = Charset.forName(charset).newEncoder();
}
}else if(writer instanceof FileWriter){
String charset = ((FileWriter)writer).getEncoding();
if(charset != null){
fEncoder = Charset.forName(charset).newEncoder();
}
}
else{
//attempt to retreive default fEncoderoder
fEncoder = getDefaultEncoder();
}
}
/**
* sets the writer object
* @param writer file to write into
*/
public void setWriter(Writer writer){
fWriter = writer;
}
public void setEscapeCharacters(boolean escape){
fEscapeCharacters = escape ;
}
public boolean getEscapeCharacters(){
return fEscapeCharacters;
}
/**
* writes xml content (characters and element content
* @param content
*/
public void writeXMLContent(char[] content, int start, int length) throws IOException{
writeXMLContent(content, start, length, getEscapeCharacters());
}
/**
* writes xml content (characters and element content
* @param content
*/
private void writeXMLContent(char[] content, int start, int length, boolean escapeCharacter) throws IOException{
if(DEBUG_XML_CONTENT){
System.out.println("content to write is " + new String(content, start, length));
}
int index;
char ch;
int sc;
final int end = start + length ;
//define startWritePos to track the position from where the character array data needs to be written
//initialize this variable to start pos. indicating that no data has been written
int startWritePos = start;
for ( index = start ; index < end ; index++ ) {
ch = content[ index ];
if(fEncoder != null && !fEncoder.canEncode(ch)){
//- write the data to the point we get this character
fWriter.write(content, startWritePos, index - startWritePos );
//escape this character
fWriter.write( "&#x" );
fWriter.write(Integer.toHexString(ch));
fWriter.write( ';' );
//increase the startWritePos by 1 indicating that next write should start from
//one position ahead
startWritePos = index + 1;
}
if(DEBUG_XML_CONTENT){
System.out.println("startWritePos = " + startWritePos);
System.out.println("index = " + index);
System.out.println("start = " + start);
System.out.println("end = " + end);
}
switch(ch){
case '<' :{
if(escapeCharacter){
//this character needs to be escaped, write the data from the last write pos
fWriter.write(content, startWritePos, index - startWritePos);
fWriter.write("&lt;");
if(DEBUG_XML_CONTENT){
System.out.print(new String(content, startWritePos, index - startWritePos));
System.out.println("&lt;");
}
//increase the startWritePos by 1 indicating that next write should start from
//one position ahead
startWritePos = index + 1;
}
break;
}
case '&' :{
if(escapeCharacter){
//this character needs to be escaped, write the data from the last write pos
fWriter.write(content, startWritePos, index - startWritePos);
fWriter.write("&amp;");
if(DEBUG_XML_CONTENT){
System.out.print(new String(content,startWritePos, index - startWritePos));
System.out.println("&amp;");
}
//increase the startWritePos by 1 indicating that next write should start from
//one position ahead
startWritePos = index + 1;
}
break;
}
case '>': {
if(escapeCharacter){
//this character needs to be escaped, write the data from the last write pos
fWriter.write(content, startWritePos, index - startWritePos);
fWriter.write("&gt;");
if(DEBUG_XML_CONTENT){
System.out.print(new String(content,startWritePos, index - startWritePos));
System.out.println("&gt;");
}
//increase the startWritePos by 1 indicating that next write should start from
//one position ahead
startWritePos = index + 1;
}
break;
}
}
}
if(DEBUG_XML_CONTENT){
System.out.println("out of the loop, writing " + new String(content, startWritePos, end - startWritePos));
}
//write any pending data
fWriter.write(content, startWritePos, end - startWritePos);
}
/**
* writes xml content (characters and element content
* @param content
*/
public void writeXMLContent(String content) throws IOException{
if(content == null || content.length() == 0) return ;
writeXMLContent(content.toCharArray(), 0, content.length());
}
/**
* Write Attribute value to the underlying stream.
*
* @param value
*/
public void writeXMLAttributeValue(String value)throws IOException{
writeXMLContent(value.toCharArray(), 0, value.length(), true);
}
private CharsetEncoder getDefaultEncoder(){
try{
String encoding = SecuritySupport.getSystemProperty("file.encoding");
if(encoding != null){
return Charset.forName(encoding).newEncoder();
}
}
catch(Exception ex){
//for any exception thrown , catch and continue
}
return null;
}
}

View File

@@ -0,0 +1,742 @@
/*
* Copyright (c) 2005, 2006, 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.stream.writers;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.Node;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.helpers.NamespaceSupport;
/**
* This class provides support to build a DOM tree using XMLStreamWriter API's.
* @author K.Venugopal@sun.com
*/
/*
* TODO : -Venu
* Internal NamespaceManagement
* setPrefix
* support for isRepairNamespace property.
* Some Unsupported Methods.
* Change StringBuffer to StringBuilder, when JDK 1.5 will be minimum requirement for SJSXP.
*/
public class XMLDOMWriterImpl implements XMLStreamWriter {
private Document ownerDoc = null;
private Node currentNode = null;
private Node node = null;
private NamespaceSupport namespaceContext = null;
private Method mXmlVersion = null;
private boolean [] needContextPop = null;
private StringBuffer stringBuffer = null;
private int resizeValue = 20;
private int depth = 0;
/**
* Creates a new instance of XMLDOMwriterImpl
* @param result DOMResult object @javax.xml.transform.dom.DOMResult
*/
public XMLDOMWriterImpl(DOMResult result) {
node = result.getNode();
if( node.getNodeType() == Node.DOCUMENT_NODE){
ownerDoc = (Document)node;
currentNode = ownerDoc;
}else{
ownerDoc = node.getOwnerDocument();
currentNode = node;
}
getDLThreeMethods();
stringBuffer = new StringBuffer();
needContextPop = new boolean[resizeValue];
namespaceContext = new NamespaceSupport();
}
private void getDLThreeMethods(){
try{
mXmlVersion = ownerDoc.getClass().getMethod("setXmlVersion",new Class[] {String.class});
}catch(NoSuchMethodException mex){
//log these errors at fine level.
mXmlVersion = null;
}catch(SecurityException se){
//log these errors at fine level.
mXmlVersion = null;
}
}
/**
* This method has no effect when called.
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void close() throws XMLStreamException {
//no-op
}
/**
* This method has no effect when called.
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void flush() throws XMLStreamException {
//no-op
}
/**
* {@inheritDoc}
* @return {@inheritDoc}
*/
public javax.xml.namespace.NamespaceContext getNamespaceContext() {
return null;
}
/**
* {@inheritDoc}
* @param namespaceURI {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
* @return {@inheritDoc}
*/
public String getPrefix(String namespaceURI) throws XMLStreamException {
String prefix = null;
if(this.namespaceContext != null){
prefix = namespaceContext.getPrefix(namespaceURI);
}
return prefix;
}
/**
* Is not supported in this implementation.
* @param str {@inheritDoc}
* @throws java.lang.IllegalArgumentException {@inheritDoc}
* @return {@inheritDoc}
*/
public Object getProperty(String str) throws IllegalArgumentException {
throw new UnsupportedOperationException();
}
/**
* Is not supported in this version of the implementation.
* @param uri {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void setDefaultNamespace(String uri) throws XMLStreamException {
namespaceContext.declarePrefix(XMLConstants.DEFAULT_NS_PREFIX, uri);
if(!needContextPop[depth]){
needContextPop[depth] = true;
}
}
/**
* {@inheritDoc}
* @param namespaceContext {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void setNamespaceContext(javax.xml.namespace.NamespaceContext namespaceContext) throws XMLStreamException {
throw new UnsupportedOperationException();
}
/**
* Is not supported in this version of the implementation.
* @param prefix {@inheritDoc}
* @param uri {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void setPrefix(String prefix, String uri) throws XMLStreamException {
if(prefix == null){
throw new XMLStreamException("Prefix cannot be null");
}
namespaceContext.declarePrefix(prefix, uri);
if(!needContextPop[depth]){
needContextPop[depth] = true;
}
}
/**
* Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node.
* @param localName {@inheritDoc}
* @param value {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeAttribute(String localName, String value) throws XMLStreamException {
if(currentNode.getNodeType() == Node.ELEMENT_NODE){
Attr attr = ownerDoc.createAttribute(localName);
attr.setValue(value);
((Element)currentNode).setAttributeNode(attr);
}else{
//Convert node type to String
throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() +
"and does not allow attributes to be set ");
}
}
/**
* Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node.
* @param namespaceURI {@inheritDoc}
* @param localName {@inheritDoc}
* @param value {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException {
if(currentNode.getNodeType() == Node.ELEMENT_NODE){
String prefix = null;
if(namespaceURI == null ){
throw new XMLStreamException("NamespaceURI cannot be null");
}
if(localName == null){
throw new XMLStreamException("Local name cannot be null");
}
if(namespaceContext != null){
prefix = namespaceContext.getPrefix(namespaceURI);
}
if(prefix == null){
throw new XMLStreamException("Namespace URI "+namespaceURI +
"is not bound to any prefix" );
}
String qualifiedName = null;
if(prefix.equals("")){
qualifiedName = localName;
}else{
qualifiedName = getQName(prefix,localName);
}
Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName);
attr.setValue(value);
((Element)currentNode).setAttributeNode(attr);
}else{
//Convert node type to String
throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() +
"and does not allow attributes to be set ");
}
}
/**
* Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node.
* @param prefix {@inheritDoc}
* @param namespaceURI {@inheritDoc}
* @param localName {@inheritDoc}
* @param value {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeAttribute(String prefix,String namespaceURI,String localName,String value)throws XMLStreamException {
if(currentNode.getNodeType() == Node.ELEMENT_NODE){
if(namespaceURI == null ){
throw new XMLStreamException("NamespaceURI cannot be null");
}
if(localName == null){
throw new XMLStreamException("Local name cannot be null");
}
if(prefix == null){
throw new XMLStreamException("prefix cannot be null");
}
String qualifiedName = null;
if(prefix.equals("")){
qualifiedName = localName;
}else{
qualifiedName = getQName(prefix,localName);
}
Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName);
attr.setValue(value);
((Element)currentNode).setAttributeNodeNS(attr);
}else{
//Convert node type to String
throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() +
"and does not allow attributes to be set ");
}
}
/**
* Creates a CDATA object @see org.w3c.dom.CDATASection.
* @param data {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeCData(String data) throws XMLStreamException {
if(data == null){
throw new XMLStreamException("CDATA cannot be null");
}
CDATASection cdata = ownerDoc.createCDATASection(data);
getNode().appendChild(cdata);
}
/**
* Creates a character object @see org.w3c.dom.Text and appends it to the current
* element in the DOM tree.
* @param charData {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeCharacters(String charData) throws XMLStreamException {
Text text = ownerDoc.createTextNode(charData);
currentNode.appendChild(text);
}
/**
* Creates a character object @see org.w3c.dom.Text and appends it to the current
* element in the DOM tree.
* @param values {@inheritDoc}
* @param param {@inheritDoc}
* @param param2 {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeCharacters(char[] values, int param, int param2) throws XMLStreamException {
Text text = ownerDoc.createTextNode(new String(values,param,param2));
currentNode.appendChild(text);
}
/**
* Creates a Comment object @see org.w3c.dom.Comment and appends it to the current
* element in the DOM tree.
* @param str {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeComment(String str) throws XMLStreamException {
Comment comment = ownerDoc.createComment(str);
getNode().appendChild(comment);
}
/**
* This method is not supported in this implementation.
* @param str {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeDTD(String str) throws XMLStreamException {
throw new UnsupportedOperationException();
}
/**
* Creates a DOM attribute and adds it to the current element in the DOM tree.
* @param namespaceURI {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException {
if(currentNode.getNodeType() == Node.ELEMENT_NODE){
String qname = XMLConstants.XMLNS_ATTRIBUTE;
((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI);
}else{
//Convert node type to String
throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() +
"and does not allow attributes to be set ");
}
}
/**
* creates a DOM Element and appends it to the current element in the tree.
* @param localName {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeEmptyElement(String localName) throws XMLStreamException {
if(ownerDoc != null){
Element element = ownerDoc.createElement(localName);
if(currentNode!=null){
currentNode.appendChild(element);
}else{
ownerDoc.appendChild(element);
}
}
}
/**
* creates a DOM Element and appends it to the current element in the tree.
* @param namespaceURI {@inheritDoc}
* @param localName {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
if(ownerDoc != null){
String qualifiedName = null;
String prefix = null;
if(namespaceURI == null ){
throw new XMLStreamException("NamespaceURI cannot be null");
}
if(localName == null){
throw new XMLStreamException("Local name cannot be null");
}
if(namespaceContext != null){
prefix = namespaceContext.getPrefix(namespaceURI);
}
if(prefix == null){
throw new XMLStreamException("Namespace URI "+namespaceURI +
"is not bound to any prefix" );
}
if("".equals(prefix)){
qualifiedName = localName;
}else{
qualifiedName = getQName(prefix,localName);
}
Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName);
if(currentNode!=null){
currentNode.appendChild(element);
}else{
ownerDoc.appendChild(element);
}
//currentNode = element;
}
}
/**
* creates a DOM Element and appends it to the current element in the tree.
* @param prefix {@inheritDoc}
* @param localName {@inheritDoc}
* @param namespaceURI {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
if(ownerDoc != null){
if(namespaceURI == null ){
throw new XMLStreamException("NamespaceURI cannot be null");
}
if(localName == null){
throw new XMLStreamException("Local name cannot be null");
}
if(prefix == null){
throw new XMLStreamException("Prefix cannot be null");
}
String qualifiedName = null;
if("".equals(prefix)){
qualifiedName = localName;
}else{
qualifiedName = getQName(prefix,localName);
}
Element el = ownerDoc.createElementNS(namespaceURI,qualifiedName);
if(currentNode!=null){
currentNode.appendChild(el);
}else{
ownerDoc.appendChild(el);
}
}
}
/**
* Will reset current Node pointer maintained by the implementation.
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeEndDocument() throws XMLStreamException {
//What do you want me to do eh! :)
currentNode = null;
for(int i=0; i< depth;i++){
if(needContextPop[depth]){
needContextPop[depth] = false;
namespaceContext.popContext();
}
depth--;
}
depth =0;
}
/**
* Internal current Node pointer will point to the parent of the current Node.
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeEndElement() throws XMLStreamException {
Node node= currentNode.getParentNode();
if(currentNode.getNodeType() == Node.DOCUMENT_NODE){
currentNode = null;
}else{
currentNode = node;
}
if(needContextPop[depth]){
needContextPop[depth] = false;
namespaceContext.popContext();
}
depth--;
}
/**
* Is not supported in this implementation.
* @param name {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeEntityRef(String name) throws XMLStreamException {
EntityReference er = ownerDoc.createEntityReference(name);
currentNode.appendChild(er);
}
/**
* creates a namespace attribute and will associate it with the current element in
* the DOM tree.
* @param prefix {@inheritDoc}
* @param namespaceURI {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {
if (prefix == null) {
throw new XMLStreamException("prefix cannot be null");
}
if (namespaceURI == null) {
throw new XMLStreamException("NamespaceURI cannot be null");
}
String qname = null;
if (prefix.equals("")) {
qname = XMLConstants.XMLNS_ATTRIBUTE;
} else {
qname = getQName(XMLConstants.XMLNS_ATTRIBUTE,prefix);
}
((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI);
}
/**
* is not supported in this release.
* @param target {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeProcessingInstruction(String target) throws XMLStreamException {
if(target == null){
throw new XMLStreamException("Target cannot be null");
}
ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, "");
currentNode.appendChild(pi);
}
/**
* is not supported in this release.
* @param target {@inheritDoc}
* @param data {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeProcessingInstruction(String target, String data) throws XMLStreamException {
if(target == null){
throw new XMLStreamException("Target cannot be null");
}
ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, data);
currentNode.appendChild(pi);
}
/**
* will set version on the Document object when the DOM Node passed to this implementation
* supports DOM Level3 API's.
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeStartDocument() throws XMLStreamException {
try{
if(mXmlVersion != null){
mXmlVersion.invoke(ownerDoc, new Object[] {"1.0"});
}
}catch(IllegalAccessException iae){
throw new XMLStreamException(iae);
}catch(InvocationTargetException ite){
throw new XMLStreamException(ite);
}
}
/**
* will set version on the Document object when the DOM Node passed to this implementation
* supports DOM Level3 API's.
* @param version {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeStartDocument(String version) throws XMLStreamException {
try{
if(mXmlVersion != null){
mXmlVersion.invoke(ownerDoc, new Object[] {version});
}
}catch(IllegalAccessException iae){
throw new XMLStreamException(iae);
}catch(InvocationTargetException ite){
throw new XMLStreamException(ite);
}
}
/**
* will set version on the Document object when the DOM Node passed to this implementation
* supports DOM Level3 API's.
* @param encoding {@inheritDoc}
* @param version {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
try{
if(mXmlVersion != null){
mXmlVersion.invoke(ownerDoc, new Object[] {version});
}
}catch(IllegalAccessException iae){
throw new XMLStreamException(iae);
}catch(InvocationTargetException ite){
throw new XMLStreamException(ite);
}
//TODO: What to do with encoding.-Venu
}
/**
* creates a DOM Element and appends it to the current element in the tree.
* @param localName {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeStartElement(String localName) throws XMLStreamException {
if(ownerDoc != null){
Element element = ownerDoc.createElement(localName);
if(currentNode!=null){
currentNode.appendChild(element);
}else{
ownerDoc.appendChild(element);
}
currentNode = element;
}
if(needContextPop[depth]){
namespaceContext.pushContext();
}
incDepth();
}
/**
* creates a DOM Element and appends it to the current element in the tree.
* @param namespaceURI {@inheritDoc}
* @param localName {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
if(ownerDoc != null){
String qualifiedName = null;
String prefix = null;
if(namespaceURI == null ){
throw new XMLStreamException("NamespaceURI cannot be null");
}
if(localName == null){
throw new XMLStreamException("Local name cannot be null");
}
if(namespaceContext != null){
prefix = namespaceContext.getPrefix(namespaceURI);
}
if(prefix == null){
throw new XMLStreamException("Namespace URI "+namespaceURI +
"is not bound to any prefix" );
}
if("".equals(prefix)){
qualifiedName = localName;
}else{
qualifiedName = getQName(prefix,localName);
}
Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName);
if(currentNode!=null){
currentNode.appendChild(element);
}else{
ownerDoc.appendChild(element);
}
currentNode = element;
}
if(needContextPop[depth]){
namespaceContext.pushContext();
}
incDepth();
}
/**
* creates a DOM Element and appends it to the current element in the tree.
* @param prefix {@inheritDoc}
* @param localName {@inheritDoc}
* @param namespaceURI {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
if(ownerDoc != null){
String qname = null;
if(namespaceURI == null ){
throw new XMLStreamException("NamespaceURI cannot be null");
}
if(localName == null){
throw new XMLStreamException("Local name cannot be null");
}
if(prefix == null){
throw new XMLStreamException("Prefix cannot be null");
}
if(prefix.equals("")){
qname = localName;
}else{
qname = getQName(prefix,localName);
}
Element el = ownerDoc.createElementNS(namespaceURI,qname);
if(currentNode!=null){
currentNode.appendChild(el);
}else{
ownerDoc.appendChild(el);
}
currentNode = el;
if(needContextPop[depth]){
namespaceContext.pushContext();
}
incDepth();
}
}
private String getQName(String prefix , String localName){
stringBuffer.setLength(0);
stringBuffer.append(prefix);
stringBuffer.append(":");
stringBuffer.append(localName);
return stringBuffer.toString();
}
private Node getNode(){
if(currentNode == null){
return ownerDoc;
} else{
return currentNode;
}
}
private void incDepth() {
depth++;
if (depth == needContextPop.length) {
boolean[] array = new boolean[depth + resizeValue];
System.arraycopy(needContextPop, 0, array, 0, depth);
needContextPop = array;
}
}
}

View File

@@ -0,0 +1,261 @@
/*
* Copyright (c) 2005, 2006, 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.stream.writers;
import java.util.Iterator;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.Comment;
import javax.xml.stream.events.DTD;
import javax.xml.stream.events.EntityReference;
import javax.xml.stream.events.Namespace;
import javax.xml.stream.events.ProcessingInstruction;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.XMLStreamWriter;
/**
*
* @author Neeraj Bajaj, Sun Microsystems.
*
*/
public class XMLEventWriterImpl implements XMLEventWriter{
//delegate everything to XMLStreamWriter..
private XMLStreamWriter fStreamWriter ;
private static final boolean DEBUG = false;
/**
*
* @param streamWriter
*/
public XMLEventWriterImpl(XMLStreamWriter streamWriter){
fStreamWriter = streamWriter;
}
/**
*
* @param xMLEventReader
* @throws XMLStreamException
*/
public void add(javax.xml.stream.XMLEventReader xMLEventReader) throws javax.xml.stream.XMLStreamException {
if(xMLEventReader == null) throw new XMLStreamException("Event reader shouldn't be null");
while(xMLEventReader.hasNext()){
add(xMLEventReader.nextEvent());
}
}
/**
*
* @param xMLEvent
* @throws XMLStreamException
*/
public void add(javax.xml.stream.events.XMLEvent xMLEvent) throws javax.xml.stream.XMLStreamException {
int type = xMLEvent.getEventType();
switch(type){
case XMLEvent.DTD:{
DTD dtd = (DTD)xMLEvent ;
if (DEBUG)System.out.println("Adding DTD = " + dtd.toString());
fStreamWriter.writeDTD(dtd.getDocumentTypeDeclaration());
break;
}
case XMLEvent.START_DOCUMENT :{
StartDocument startDocument = (StartDocument)xMLEvent ;
if (DEBUG)System.out.println("Adding StartDocument = " + startDocument.toString());
try {
fStreamWriter.writeStartDocument(startDocument.getCharacterEncodingScheme(), startDocument.getVersion());
}catch(XMLStreamException e) {
fStreamWriter.writeStartDocument(startDocument.getVersion());
}
break;
}
case XMLEvent.START_ELEMENT :{
StartElement startElement = xMLEvent.asStartElement() ;
if (DEBUG)System.out.println("Adding startelement = " + startElement.toString());
QName qname = startElement.getName();
fStreamWriter.writeStartElement(qname.getPrefix(), qname.getLocalPart(), qname.getNamespaceURI());
//getNamespaces() Returns an Iterator of namespaces declared on this element. This Iterator does not contain
//previously declared namespaces unless they appear on the current START_ELEMENT. Therefore
//this list may contain redeclared namespaces and duplicate namespace declarations. Use the
//getNamespaceContext() method to get the current context of namespace declarations.
//so we should be using getNamespaces() to write namespace declarations for this START_ELEMENT
Iterator iterator = startElement.getNamespaces();
while(iterator.hasNext()){
Namespace namespace = (Namespace)iterator.next();
fStreamWriter.writeNamespace(namespace.getPrefix(), namespace.getNamespaceURI());
}
//REVISIT: What about writing attributes ?
Iterator attributes = startElement.getAttributes();
while(attributes.hasNext()){
Attribute attribute = (Attribute)attributes.next();
QName aqname = attribute.getName();
fStreamWriter.writeAttribute(aqname.getPrefix(), aqname.getNamespaceURI(), aqname.getLocalPart(),attribute.getValue());
}
break;
}
case XMLEvent.NAMESPACE:{
Namespace namespace = (Namespace)xMLEvent;
if (DEBUG)System.out.println("Adding namespace = " + namespace.toString());
fStreamWriter.writeNamespace(namespace.getPrefix(), namespace.getNamespaceURI());
break ;
}
case XMLEvent.COMMENT: {
Comment comment = (Comment)xMLEvent ;
if (DEBUG)System.out.println("Adding comment = " + comment.toString());
fStreamWriter.writeComment(comment.getText());
break;
}
case XMLEvent.PROCESSING_INSTRUCTION:{
ProcessingInstruction processingInstruction = (ProcessingInstruction)xMLEvent ;
if (DEBUG)System.out.println("Adding processing instruction = " + processingInstruction.toString());
fStreamWriter.writeProcessingInstruction(processingInstruction.getTarget(), processingInstruction.getData());
break;
}
case XMLEvent.CHARACTERS:{
Characters characters = xMLEvent.asCharacters();
if (DEBUG)System.out.println("Adding characters = " + characters.toString());
//check if the CHARACTERS are CDATA
if(characters.isCData()){
fStreamWriter.writeCData(characters.getData());
}
else{
fStreamWriter.writeCharacters(characters.getData());
}
break;
}
case XMLEvent.ENTITY_REFERENCE:{
EntityReference entityReference = (EntityReference)xMLEvent ;
if (DEBUG)System.out.println("Adding Entity Reference = "+ entityReference.toString());
fStreamWriter.writeEntityRef(entityReference.getName());
break;
}
case XMLEvent.ATTRIBUTE:{
Attribute attribute = (Attribute)xMLEvent;
if (DEBUG)System.out.println("Adding Attribute = " + attribute.toString());
QName qname = attribute.getName();
fStreamWriter.writeAttribute(qname.getPrefix(), qname.getNamespaceURI(), qname.getLocalPart(),attribute.getValue());
break;
}
case XMLEvent.CDATA:{
//there is no separate CDATA datatype but CDATA event can be reported
//by using vendor specific CDATA property.
Characters characters = (Characters)xMLEvent;
if (DEBUG)System.out.println("Adding characters = " + characters.toString());
if(characters.isCData()){
fStreamWriter.writeCData(characters.getData());
}
break;
}
//xxx: Why there isn't any event called Notation.
//case XMLEvent.NOTATION_DECLARATION:{
//}
case XMLEvent.END_ELEMENT:{
//we dont need to typecast it.. just call writeEndElement() and fStreamWriter will take care of it.
//EndElement endElement = (EndElement)xMLEvent;
fStreamWriter.writeEndElement();
break;
}
case XMLEvent.END_DOCUMENT:{
//we dont need to typecast just call writeEndDocument() and fStreamWriter will take care rest.
//EndDocument endDocument = (EndDocument)xMLEvent;
fStreamWriter.writeEndDocument();
break;
}
//throw new XMLStreamException("Unknown Event type = " + type);
};
}
/**
*
* @throws XMLStreamException
*/
public void close() throws javax.xml.stream.XMLStreamException {
fStreamWriter.close();
}
/**
*
* @throws XMLStreamException will inturn call flush on the stream to which data is being
* written.
*/
public void flush() throws javax.xml.stream.XMLStreamException {
fStreamWriter.flush();
}
/**
*
* @return
*/
public javax.xml.namespace.NamespaceContext getNamespaceContext() {
return fStreamWriter.getNamespaceContext();
}
/**
*
* @param namespaceURI Namespace URI
* @throws XMLStreamException
* @return prefix associated with the URI.
*/
public String getPrefix(String namespaceURI) throws javax.xml.stream.XMLStreamException {
return fStreamWriter.getPrefix(namespaceURI);
}
/**
*
* @param uri Namespace URI
* @throws XMLStreamException
*/
public void setDefaultNamespace(String uri) throws javax.xml.stream.XMLStreamException {
fStreamWriter.setDefaultNamespace(uri);
}
/**
*
* @param namespaceContext Namespace Context
* @throws XMLStreamException
*/
public void setNamespaceContext(javax.xml.namespace.NamespaceContext namespaceContext) throws javax.xml.stream.XMLStreamException {
fStreamWriter.setNamespaceContext(namespaceContext);
}
/**
*
* @param prefix namespace prefix associated with the uri.
* @param uri Namespace URI
* @throws XMLStreamException
*/
public void setPrefix(String prefix, String uri) throws javax.xml.stream.XMLStreamException {
fStreamWriter.setPrefix(prefix, uri);
}
}//XMLEventWriterImpl

View File

@@ -0,0 +1,45 @@
/*
* Copyright (c) 2006, 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.stream.writers;
import java.io.OutputStream;
import java.io.Writer;
/**
* XMLOutputSource.
*
* Encapuslates the information about the source where
* XML output needs to be written.
*
* @author Neeraj Bajaj
*/
public class XMLOutputSource {
/** Creates a new instance of XMLOutputSource */
public XMLOutputSource() {
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,260 @@
/*
* Copyright (c) 2006, 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.stream.writers;
import java.io.IOException;
import java.io.Writer;
import com.sun.org.apache.xerces.internal.util.XMLStringBuffer;
/**
* XMLWriter
*
* <code>XMLWriter</code> is not thread safe.
*
* For efficiency this writer buffers the input. Use <code>flush()</code> function
* to explicitly write the data to underlying stream.
*
* This writer is designed in such a way that it atleast buffers the input to the
* <code>size</code> specified. Unless <code>flush</code> is called, it guarantees that
* data in chunks of size equal to or more than <code>size</code> specified will be written.
*
*
* <code>XMLWriter</code> instance can be reused. <code>setWriter()</code> internally clears the
* buffer and stores the reference to newly supplied <code>Writer</code> instance.
*
* @author Neeraj Bajaj Sun Microsystems, inc.
*/
public class XMLWriter extends Writer {
private Writer writer ;
private int size ;
//keep the size of internal buffer more than 'size' required to avoid resizing
private XMLStringBuffer buffer = new XMLStringBuffer(6 * (1 << 11) ); // 6 KB
private static final int THRESHHOLD_LENGTH = 1 << 12 ; // 4 KB
private static final boolean DEBUG = false;
/** Creates the instance of <code>XMLWriter</code>
*/
public XMLWriter(Writer writer){
this(writer, THRESHHOLD_LENGTH);
}
/**
* Creates the instnace of <code>XMLWriter</code>.
*
* atleast buffers the input to the
* <code>size</code> specified.
*/
public XMLWriter(Writer writer, int size){
this.writer = writer ;
this.size = size;
}
/**
* Write a single character. The character to be written is contained in
* the 16 low-order bits of the given integer value; the 16 high-order bits
* are ignored.
*
* <p> Subclasses that intend to support efficient single-character output
* should override this method.
*
* @param c int specifying a character to be written.
* @exception IOException If an I/O error occurs
*/
public void write(int c) throws IOException {
ensureOpen();
buffer.append((char)c);
conditionalWrite();
}
/**
* Write an array of characters.
*
* @param cbuf Array of characters to be written
*
* @exception IOException If an I/O error occurs
*/
public void write(char cbuf[]) throws IOException {
write(cbuf, 0, cbuf.length);
}
/**
* Write a portion of an array of characters.
*
* @param cbuf Array of characters
* @param off Offset from which to start writing characters
* @param len Number of characters to write
*
* @exception IOException If an I/O error occurs
*/
public void write(char cbuf[], int off, int len) throws IOException{
ensureOpen();
//optimization: if data size to be written is more than the 'size' specified,
//do not buffer the data but write the data straight to the underlying stream
if(len > size){
//first write the data that may be present in the buffer
writeBufferedData();
//write directly to stream
writer.write(cbuf, off, len);
}else{
buffer.append(cbuf, off, len);
conditionalWrite();
}
}
/**
* Write a portion of a string.
*
* @param str A String
* @param off Offset from which to start writing characters
* @param len Number of characters to write
*
* @exception IOException If an I/O error occurs
*/
public void write(String str, int off, int len) throws IOException {
write(str.toCharArray(), off, len);
}
/**
* Write a string.
*
* @param str String to be written
*
* @exception IOException If an I/O error occurs
*/
public void write(String str) throws IOException {
//optimization: if data size to be written is more than the 'size' specified,
//do not buffer the data but write the data straight to the underlying stream - nb.
if(str.length() > size){
//first write the data that may be present in the buffer
writeBufferedData();
//write directly to stream
writer.write(str);
}else{
buffer.append(str);
conditionalWrite();
}
}
/**
* Close the stream, flushing it first. Once a stream has been closed,
* further write() or flush() invocations will cause an IOException to be
* thrown. Closing a previously-closed stream, however, has no effect.
*
* @exception IOException If an I/O error occurs
*/
public void close() throws IOException {
if(writer == null) return;
//flush it first
flush();
writer.close();
writer = null ;
}
/**
* Flush the stream. If the stream has saved any characters from the
* various write() methods in a buffer, write them immediately to their
* intended destination. Then, if that destination is another character or
* byte stream, flush it. Thus one flush() invocation will flush all the
* buffers in a chain of Writers and OutputStreams.
*
* @exception IOException If an I/O error occurs
*/
public void flush() throws IOException {
ensureOpen();
//write current data present in the buffer
writeBufferedData();
writer.flush();
}
/** Reset this Writer.
*
* see @setWriter()
*/
public void reset(){
this.writer = null;
buffer.clear();
this.size = THRESHHOLD_LENGTH;
}
/**
* Set the given <code>Writer</code>.
*
* @param Writer Writer.
*/
public void setWriter(Writer writer){
this.writer = writer;
buffer.clear();
this.size = THRESHHOLD_LENGTH;
}
/** Set the given <code>Writer</code>
*
* @param Writer Writer.
* @param int Writer will buffer the character data size, after that data is written to stream.
*/
public void setWriter(Writer writer, int size){
this.writer = writer;
this.size = size;
}
/**
* Returns underlying <code>Writer</code>
*/
protected Writer getWriter() {
return writer;
}
/** write the buffer data, if the buffer size has increased the size specified
*/
private void conditionalWrite() throws IOException {
if(buffer.length > size){
if(DEBUG){
System.out.println("internal buffer length " + buffer.length + " increased size limit : " + size);
System.out.println("Data: ('" + new String(buffer.ch, buffer.offset, buffer.length) + "')");
}
writeBufferedData();
}
}
/** Write the data present in the buffer to the writer.
* buffer is cleared after write operation.
*/
private void writeBufferedData() throws IOException {
writer.write(buffer.ch, buffer.offset, buffer.length);
buffer.clear();
}
/** Check to make sure that the stream has not been closed */
private void ensureOpen() throws IOException {
if (writer == null)throw new IOException("Stream closed");
}
}