You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tomee.apache.org by jl...@apache.org on 2020/12/08 14:12:13 UTC

[tomee] branch master updated (c38f60e -> dff0f6b)

This is an automated email from the ASF dual-hosted git repository.

jlmonteiro pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git.


    from c38f60e  TOMEE-2933 Upgrade of EclipseLink
     new 2059cec  TOMEE-2938 Xalan is required for JSTL xml:transform As the 2.7.2 is not maintained. Patch it ourselves
     new 02feaaa  TOMEE-2938 Default copy of Xalan code before patching
     new c01cff2  TOMEE-2938 Fix encoding in Xalan and Serializer
     new dff0f6b  TOMEE-2938 Properly configure patch plugin

The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 arquillian/arquillian-tomee-webapp-remote/pom.xml  |    4 -
 tomee/tomee-webapp/pom.xml                         |   39 +
 .../org/apache/xml/serializer/ToHTMLStream.java    | 2354 +++++++++++++
 .../java/org/apache/xml/serializer/ToStream.java   | 3618 ++++++++++++++++++++
 4 files changed, 6011 insertions(+), 4 deletions(-)
 create mode 100644 tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java
 create mode 100644 tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java


[tomee] 01/04: TOMEE-2938 Xalan is required for JSTL xml:transform As the 2.7.2 is not maintained. Patch it ourselves

Posted by jl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jlmonteiro pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 2059ceca0ded285ec7b4fa1bbd8280a47f28e630
Author: Jean-Louis Monteiro <jl...@tomitribe.com>
AuthorDate: Tue Dec 8 14:42:37 2020 +0100

    TOMEE-2938 Xalan is required for JSTL xml:transform
    As the 2.7.2 is not maintained. Patch it ourselves
---
 tomee/tomee-webapp/pom.xml                         |   39 +
 .../org/apache/xml/serializer/ToHTMLStream.java    | 2350 +++++++++++++
 .../java/org/apache/xml/serializer/ToStream.java   | 3616 ++++++++++++++++++++
 3 files changed, 6005 insertions(+)

diff --git a/tomee/tomee-webapp/pom.xml b/tomee/tomee-webapp/pom.xml
index cc0e27a..122d84c 100644
--- a/tomee/tomee-webapp/pom.xml
+++ b/tomee/tomee-webapp/pom.xml
@@ -117,6 +117,45 @@
           </sourceFolders>
         </configuration>
       </plugin>
+
+      <!--
+        This is to patch Xalan https://issues.apache.org/jira/browse/TOMEE-2938
+      -->
+      <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>build-helper-maven-plugin</artifactId>
+        <version>3.2.0</version>
+        <executions>
+          <execution>
+            <id>add-source</id>
+            <phase>generate-sources</phase>
+            <goals>
+              <goal>add-source</goal>
+            </goals>
+            <configuration>
+              <sources>
+                <source>src/patch/java</source>
+              </sources>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.tomee.patch</groupId>
+        <artifactId>tomee-patch-plugin</artifactId>
+        <version>0.1</version>
+        <configuration>
+          <select>apache-tomee.*\.zip</select>
+        </configuration>
+        <executions>
+          <execution>
+            <goals>
+              <goal>run</goal>
+            </goals>
+            <phase>package</phase>
+          </execution>
+        </executions>
+      </plugin>
     </plugins>
   </build>
   <dependencies>
diff --git a/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java
new file mode 100644
index 0000000..637117d
--- /dev/null
+++ b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java
@@ -0,0 +1,2350 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the  "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*
+ * $Id: ToHTMLStream.java 1225444 2011-12-29 05:52:39Z mrglavas $
+ */
+package org.apache.xml.serializer;
+
+import java.io.IOException;
+import java.util.Properties;
+
+import javax.xml.transform.Result;
+
+import org.apache.xml.serializer.utils.MsgKey;
+import org.apache.xml.serializer.utils.Utils;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ * This serializer takes a series of SAX or
+ * SAX-like events and writes its output
+ * to the given stream.
+ * 
+ * This class is not a public API, it is public
+ * because it is used from another package.
+ * 
+ * @xsl.usage internal
+ */
+public class ToHTMLStream extends ToStream 
+{
+
+    /** This flag is set while receiving events from the DTD */
+    protected boolean m_inDTD = false;
+
+    /** True if the current element is a block element.  (seems like 
+     *  this needs to be a stack. -sb). */
+    private boolean m_inBlockElem = false;
+
+    /**
+     * Map that tells which XML characters should have special treatment, and it
+     *  provides character to entity name lookup.
+     */
+    private final CharInfo m_htmlcharInfo =
+//        new CharInfo(CharInfo.HTML_ENTITIES_RESOURCE);
+        CharInfo.getCharInfo(CharInfo.HTML_ENTITIES_RESOURCE, Method.HTML);
+
+    /** A digital search trie for fast, case insensitive lookup of ElemDesc objects. */
+    static final Trie m_elementFlags = new Trie();
+
+    static {
+        initTagReference(m_elementFlags);
+    }
+    static void initTagReference(Trie m_elementFlags) {
+
+        // HTML 4.0 loose DTD
+        m_elementFlags.put("BASEFONT", new ElemDesc(0 | ElemDesc.EMPTY));
+        m_elementFlags.put(
+            "FRAME",
+            new ElemDesc(0 | ElemDesc.EMPTY | ElemDesc.BLOCK));
+        m_elementFlags.put("FRAMESET", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put("NOFRAMES", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "ISINDEX",
+            new ElemDesc(0 | ElemDesc.EMPTY | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "APPLET",
+            new ElemDesc(0 | ElemDesc.WHITESPACESENSITIVE));
+        m_elementFlags.put("CENTER", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put("DIR", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put("MENU", new ElemDesc(0 | ElemDesc.BLOCK));
+
+        // HTML 4.0 strict DTD
+        m_elementFlags.put("TT", new ElemDesc(0 | ElemDesc.FONTSTYLE));
+        m_elementFlags.put("I", new ElemDesc(0 | ElemDesc.FONTSTYLE));
+        m_elementFlags.put("B", new ElemDesc(0 | ElemDesc.FONTSTYLE));
+        m_elementFlags.put("BIG", new ElemDesc(0 | ElemDesc.FONTSTYLE));
+        m_elementFlags.put("SMALL", new ElemDesc(0 | ElemDesc.FONTSTYLE));
+        m_elementFlags.put("EM", new ElemDesc(0 | ElemDesc.PHRASE));
+        m_elementFlags.put("STRONG", new ElemDesc(0 | ElemDesc.PHRASE));
+        m_elementFlags.put("DFN", new ElemDesc(0 | ElemDesc.PHRASE));
+        m_elementFlags.put("CODE", new ElemDesc(0 | ElemDesc.PHRASE));
+        m_elementFlags.put("SAMP", new ElemDesc(0 | ElemDesc.PHRASE));
+        m_elementFlags.put("KBD", new ElemDesc(0 | ElemDesc.PHRASE));
+        m_elementFlags.put("VAR", new ElemDesc(0 | ElemDesc.PHRASE));
+        m_elementFlags.put("CITE", new ElemDesc(0 | ElemDesc.PHRASE));
+        m_elementFlags.put("ABBR", new ElemDesc(0 | ElemDesc.PHRASE));
+        m_elementFlags.put("ACRONYM", new ElemDesc(0 | ElemDesc.PHRASE));
+        m_elementFlags.put(
+            "SUP",
+            new ElemDesc(0 | ElemDesc.SPECIAL | ElemDesc.ASPECIAL));
+        m_elementFlags.put(
+            "SUB",
+            new ElemDesc(0 | ElemDesc.SPECIAL | ElemDesc.ASPECIAL));
+        m_elementFlags.put(
+            "SPAN",
+            new ElemDesc(0 | ElemDesc.SPECIAL | ElemDesc.ASPECIAL));
+        m_elementFlags.put(
+            "BDO",
+            new ElemDesc(0 | ElemDesc.SPECIAL | ElemDesc.ASPECIAL));
+        m_elementFlags.put(
+            "BR",
+            new ElemDesc(
+                0
+                    | ElemDesc.SPECIAL
+                    | ElemDesc.ASPECIAL
+                    | ElemDesc.EMPTY
+                    | ElemDesc.BLOCK));
+        m_elementFlags.put("BODY", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "ADDRESS",
+            new ElemDesc(
+                0
+                    | ElemDesc.BLOCK
+                    | ElemDesc.BLOCKFORM
+                    | ElemDesc.BLOCKFORMFIELDSET));
+        m_elementFlags.put(
+            "DIV",
+            new ElemDesc(
+                0
+                    | ElemDesc.BLOCK
+                    | ElemDesc.BLOCKFORM
+                    | ElemDesc.BLOCKFORMFIELDSET));
+        m_elementFlags.put("A", new ElemDesc(0 | ElemDesc.SPECIAL));
+        m_elementFlags.put(
+            "MAP",
+            new ElemDesc(
+                0 | ElemDesc.SPECIAL | ElemDesc.ASPECIAL | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "AREA",
+            new ElemDesc(0 | ElemDesc.EMPTY | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "LINK",
+            new ElemDesc(
+                0 | ElemDesc.HEADMISC | ElemDesc.EMPTY | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "IMG",
+            new ElemDesc(
+                0
+                    | ElemDesc.SPECIAL
+                    | ElemDesc.ASPECIAL
+                    | ElemDesc.EMPTY
+                    | ElemDesc.WHITESPACESENSITIVE));
+        m_elementFlags.put(
+            "OBJECT",
+            new ElemDesc(
+                0
+                    | ElemDesc.SPECIAL
+                    | ElemDesc.ASPECIAL
+                    | ElemDesc.HEADMISC
+                    | ElemDesc.WHITESPACESENSITIVE));
+        m_elementFlags.put("PARAM", new ElemDesc(0 | ElemDesc.EMPTY));
+        m_elementFlags.put(
+            "HR",
+            new ElemDesc(
+                0
+                    | ElemDesc.BLOCK
+                    | ElemDesc.BLOCKFORM
+                    | ElemDesc.BLOCKFORMFIELDSET
+                    | ElemDesc.EMPTY));
+        m_elementFlags.put(
+            "P",
+            new ElemDesc(
+                0
+                    | ElemDesc.BLOCK
+                    | ElemDesc.BLOCKFORM
+                    | ElemDesc.BLOCKFORMFIELDSET));
+        m_elementFlags.put(
+            "H1",
+            new ElemDesc(0 | ElemDesc.HEAD | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "H2",
+            new ElemDesc(0 | ElemDesc.HEAD | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "H3",
+            new ElemDesc(0 | ElemDesc.HEAD | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "H4",
+            new ElemDesc(0 | ElemDesc.HEAD | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "H5",
+            new ElemDesc(0 | ElemDesc.HEAD | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "H6",
+            new ElemDesc(0 | ElemDesc.HEAD | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "PRE",
+            new ElemDesc(0 | ElemDesc.PREFORMATTED | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "Q",
+            new ElemDesc(0 | ElemDesc.SPECIAL | ElemDesc.ASPECIAL));
+        m_elementFlags.put(
+            "BLOCKQUOTE",
+            new ElemDesc(
+                0
+                    | ElemDesc.BLOCK
+                    | ElemDesc.BLOCKFORM
+                    | ElemDesc.BLOCKFORMFIELDSET));
+        m_elementFlags.put("INS", new ElemDesc(0));
+        m_elementFlags.put("DEL", new ElemDesc(0));
+        m_elementFlags.put(
+            "DL",
+            new ElemDesc(
+                0
+                    | ElemDesc.BLOCK
+                    | ElemDesc.BLOCKFORM
+                    | ElemDesc.BLOCKFORMFIELDSET));
+        m_elementFlags.put("DT", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put("DD", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "OL",
+            new ElemDesc(0 | ElemDesc.LIST | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "UL",
+            new ElemDesc(0 | ElemDesc.LIST | ElemDesc.BLOCK));
+        m_elementFlags.put("LI", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put("FORM", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put("LABEL", new ElemDesc(0 | ElemDesc.FORMCTRL));
+        m_elementFlags.put(
+            "INPUT",
+            new ElemDesc(
+                0 | ElemDesc.FORMCTRL | ElemDesc.INLINELABEL | ElemDesc.EMPTY));
+        m_elementFlags.put(
+            "SELECT",
+            new ElemDesc(0 | ElemDesc.FORMCTRL | ElemDesc.INLINELABEL));
+        m_elementFlags.put("OPTGROUP", new ElemDesc(0));
+        m_elementFlags.put("OPTION", new ElemDesc(0));
+        m_elementFlags.put(
+            "TEXTAREA",
+            new ElemDesc(0 | ElemDesc.FORMCTRL | ElemDesc.INLINELABEL));
+        m_elementFlags.put(
+            "FIELDSET",
+            new ElemDesc(0 | ElemDesc.BLOCK | ElemDesc.BLOCKFORM));
+        m_elementFlags.put("LEGEND", new ElemDesc(0));
+        m_elementFlags.put(
+            "BUTTON",
+            new ElemDesc(0 | ElemDesc.FORMCTRL | ElemDesc.INLINELABEL));
+        m_elementFlags.put(
+            "TABLE",
+            new ElemDesc(
+                0
+                    | ElemDesc.BLOCK
+                    | ElemDesc.BLOCKFORM
+                    | ElemDesc.BLOCKFORMFIELDSET));
+        m_elementFlags.put("CAPTION", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put("THEAD", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put("TFOOT", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put("TBODY", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put("COLGROUP", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "COL",
+            new ElemDesc(0 | ElemDesc.EMPTY | ElemDesc.BLOCK));
+        m_elementFlags.put("TR", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put("TH", new ElemDesc(0));
+        m_elementFlags.put("TD", new ElemDesc(0));
+        m_elementFlags.put(
+            "HEAD",
+            new ElemDesc(0 | ElemDesc.BLOCK | ElemDesc.HEADELEM));
+        m_elementFlags.put("TITLE", new ElemDesc(0 | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "BASE",
+            new ElemDesc(0 | ElemDesc.EMPTY | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "META",
+            new ElemDesc(
+                0 | ElemDesc.HEADMISC | ElemDesc.EMPTY | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "STYLE",
+            new ElemDesc(
+                0 | ElemDesc.HEADMISC | ElemDesc.RAW | ElemDesc.BLOCK));
+        m_elementFlags.put(
+            "SCRIPT",
+            new ElemDesc(
+                0
+                    | ElemDesc.SPECIAL
+                    | ElemDesc.ASPECIAL
+                    | ElemDesc.HEADMISC
+                    | ElemDesc.RAW));
+        m_elementFlags.put(
+            "NOSCRIPT",
+            new ElemDesc(
+                0
+                    | ElemDesc.BLOCK
+                    | ElemDesc.BLOCKFORM
+                    | ElemDesc.BLOCKFORMFIELDSET));
+        m_elementFlags.put("HTML", new ElemDesc(0 | ElemDesc.BLOCK | ElemDesc.HTMLELEM));
+
+        // From "John Ky" <hand@syd.speednet.com.au
+        // Transitional Document Type Definition ()
+        // file:///C:/Documents%20and%20Settings/sboag.BOAG600E/My%20Documents/html/sgml/loosedtd.html#basefont
+        m_elementFlags.put("FONT", new ElemDesc(0 | ElemDesc.FONTSTYLE));
+
+        // file:///C:/Documents%20and%20Settings/sboag.BOAG600E/My%20Documents/html/present/graphics.html#edef-STRIKE
+        m_elementFlags.put("S", new ElemDesc(0 | ElemDesc.FONTSTYLE));
+        m_elementFlags.put("STRIKE", new ElemDesc(0 | ElemDesc.FONTSTYLE));
+
+        // file:///C:/Documents%20and%20Settings/sboag.BOAG600E/My%20Documents/html/present/graphics.html#edef-U
+        m_elementFlags.put("U", new ElemDesc(0 | ElemDesc.FONTSTYLE));
+
+        // From "John Ky" <hand@syd.speednet.com.au
+        m_elementFlags.put("NOBR", new ElemDesc(0 | ElemDesc.FONTSTYLE));
+
+        // HTML 4.0, section 16.5
+        m_elementFlags.put(
+            "IFRAME",
+            new ElemDesc(
+                0
+                    | ElemDesc.BLOCK
+                    | ElemDesc.BLOCKFORM
+                    | ElemDesc.BLOCKFORMFIELDSET));
+                    
+        // Netscape 4 extension
+        m_elementFlags.put(
+            "LAYER",
+            new ElemDesc(
+                0
+                    | ElemDesc.BLOCK
+                    | ElemDesc.BLOCKFORM
+                    | ElemDesc.BLOCKFORMFIELDSET));
+        // Netscape 4 extension                    
+        m_elementFlags.put(
+            "ILAYER",
+            new ElemDesc(
+                0
+                    | ElemDesc.BLOCK
+                    | ElemDesc.BLOCKFORM
+                    | ElemDesc.BLOCKFORMFIELDSET));
+
+        // NOW FOR ATTRIBUTE INFORMATION . . .
+        ElemDesc elemDesc;
+
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("a");
+        elemDesc.setAttr("HREF", ElemDesc.ATTRURL);
+        elemDesc.setAttr("NAME", ElemDesc.ATTRURL);
+        
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("area");
+
+        elemDesc.setAttr("HREF", ElemDesc.ATTRURL);
+        elemDesc.setAttr("NOHREF", ElemDesc.ATTREMPTY);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("base");
+
+        elemDesc.setAttr("HREF", ElemDesc.ATTRURL);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("button");
+        elemDesc.setAttr("DISABLED", ElemDesc.ATTREMPTY);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("blockquote");
+
+        elemDesc.setAttr("CITE", ElemDesc.ATTRURL);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("del");
+        elemDesc.setAttr("CITE", ElemDesc.ATTRURL);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("dir");
+        elemDesc.setAttr("COMPACT", ElemDesc.ATTREMPTY);
+           
+        // ----------------------------------------------
+        
+        elemDesc = (ElemDesc) m_elementFlags.get("div");
+        elemDesc.setAttr("SRC", ElemDesc.ATTRURL); // Netscape 4 extension
+        elemDesc.setAttr("NOWRAP", ElemDesc.ATTREMPTY); // Internet-Explorer extension
+   
+        // ----------------------------------------------        
+        elemDesc = (ElemDesc) m_elementFlags.get("dl");
+        elemDesc.setAttr("COMPACT", ElemDesc.ATTREMPTY);
+           
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("form");
+        elemDesc.setAttr("ACTION", ElemDesc.ATTRURL);
+
+        // ----------------------------------------------
+        // Attribution to: "Voytenko, Dimitry" <DV...@SECTORBASE.COM>
+        elemDesc = (ElemDesc) m_elementFlags.get("frame");
+        elemDesc.setAttr("SRC", ElemDesc.ATTRURL);
+        elemDesc.setAttr("LONGDESC", ElemDesc.ATTRURL);
+        elemDesc.setAttr("NORESIZE",ElemDesc.ATTREMPTY);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("head");
+        elemDesc.setAttr("PROFILE", ElemDesc.ATTRURL);
+
+        // ----------------------------------------------        
+        elemDesc = (ElemDesc) m_elementFlags.get("hr");
+        elemDesc.setAttr("NOSHADE", ElemDesc.ATTREMPTY);
+        
+        // ----------------------------------------------
+        // HTML 4.0, section 16.5
+        elemDesc = (ElemDesc) m_elementFlags.get("iframe");
+        elemDesc.setAttr("SRC", ElemDesc.ATTRURL);
+        elemDesc.setAttr("LONGDESC", ElemDesc.ATTRURL);
+
+        // ----------------------------------------------
+        // Netscape 4 extension
+        elemDesc = (ElemDesc) m_elementFlags.get("ilayer");
+        elemDesc.setAttr("SRC", ElemDesc.ATTRURL);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("img");
+        elemDesc.setAttr("SRC", ElemDesc.ATTRURL);
+        elemDesc.setAttr("LONGDESC", ElemDesc.ATTRURL);
+        elemDesc.setAttr("USEMAP", ElemDesc.ATTRURL);
+        elemDesc.setAttr("ISMAP", ElemDesc.ATTREMPTY);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("input");
+
+        elemDesc.setAttr("SRC", ElemDesc.ATTRURL);
+        elemDesc.setAttr("USEMAP", ElemDesc.ATTRURL);
+        elemDesc.setAttr("CHECKED", ElemDesc.ATTREMPTY);
+        elemDesc.setAttr("DISABLED", ElemDesc.ATTREMPTY);
+        elemDesc.setAttr("ISMAP", ElemDesc.ATTREMPTY);
+        elemDesc.setAttr("READONLY", ElemDesc.ATTREMPTY);
+        
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("ins");
+        elemDesc.setAttr("CITE", ElemDesc.ATTRURL);
+
+        // ----------------------------------------------
+        // Netscape 4 extension
+        elemDesc = (ElemDesc) m_elementFlags.get("layer");
+        elemDesc.setAttr("SRC", ElemDesc.ATTRURL);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("link");
+        elemDesc.setAttr("HREF", ElemDesc.ATTRURL);
+       
+        // ----------------------------------------------       
+        elemDesc = (ElemDesc) m_elementFlags.get("menu");
+        elemDesc.setAttr("COMPACT", ElemDesc.ATTREMPTY);
+        
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("object");
+
+        elemDesc.setAttr("CLASSID", ElemDesc.ATTRURL);
+        elemDesc.setAttr("CODEBASE", ElemDesc.ATTRURL);
+        elemDesc.setAttr("DATA", ElemDesc.ATTRURL);
+        elemDesc.setAttr("ARCHIVE", ElemDesc.ATTRURL);
+        elemDesc.setAttr("USEMAP", ElemDesc.ATTRURL);
+        elemDesc.setAttr("DECLARE", ElemDesc.ATTREMPTY);
+        
+        // ----------------------------------------------        
+        elemDesc = (ElemDesc) m_elementFlags.get("ol");
+        elemDesc.setAttr("COMPACT", ElemDesc.ATTREMPTY);
+        
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("optgroup");
+        elemDesc.setAttr("DISABLED", ElemDesc.ATTREMPTY);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("option");
+        elemDesc.setAttr("SELECTED", ElemDesc.ATTREMPTY);
+        elemDesc.setAttr("DISABLED", ElemDesc.ATTREMPTY);
+        
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("q");
+        elemDesc.setAttr("CITE", ElemDesc.ATTRURL);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("script");
+        elemDesc.setAttr("SRC", ElemDesc.ATTRURL);
+        elemDesc.setAttr("FOR", ElemDesc.ATTRURL);
+        elemDesc.setAttr("DEFER", ElemDesc.ATTREMPTY);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("select");
+        elemDesc.setAttr("DISABLED", ElemDesc.ATTREMPTY);
+        elemDesc.setAttr("MULTIPLE", ElemDesc.ATTREMPTY);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("table");
+        elemDesc.setAttr("NOWRAP", ElemDesc.ATTREMPTY); // Internet-Explorer extension
+        
+        // ----------------------------------------------        
+        elemDesc = (ElemDesc) m_elementFlags.get("td");
+        elemDesc.setAttr("NOWRAP", ElemDesc.ATTREMPTY);
+
+        // ----------------------------------------------
+        elemDesc = (ElemDesc) m_elementFlags.get("textarea");
+        elemDesc.setAttr("DISABLED", ElemDesc.ATTREMPTY);
+        elemDesc.setAttr("READONLY", ElemDesc.ATTREMPTY);
+       
+        // ----------------------------------------------                
+        elemDesc = (ElemDesc) m_elementFlags.get("th");
+        elemDesc.setAttr("NOWRAP", ElemDesc.ATTREMPTY);
+        
+        // ----------------------------------------------
+        // The nowrap attribute of a tr element is both
+        // a Netscape and Internet-Explorer extension                
+        elemDesc = (ElemDesc) m_elementFlags.get("tr");
+        elemDesc.setAttr("NOWRAP", ElemDesc.ATTREMPTY);
+        
+        // ----------------------------------------------        
+        elemDesc = (ElemDesc) m_elementFlags.get("ul");
+        elemDesc.setAttr("COMPACT", ElemDesc.ATTREMPTY);
+    }
+
+    /**
+     * Dummy element for elements not found.
+     */
+    static private final ElemDesc m_dummy = new ElemDesc(0 | ElemDesc.BLOCK);
+
+    /** True if URLs should be specially escaped with the %xx form. */
+    private boolean m_specialEscapeURLs = true;
+
+    /** True if the META tag should be omitted. */
+    private boolean m_omitMetaTag = false;
+
+    /**
+     * Tells if the formatter should use special URL escaping.
+     *
+     * @param bool True if URLs should be specially escaped with the %xx form.
+     */
+    public void setSpecialEscapeURLs(boolean bool)
+    {
+        m_specialEscapeURLs = bool;
+    }
+
+    /**
+     * Tells if the formatter should omit the META tag.
+     *
+     * @param bool True if the META tag should be omitted.
+     */
+    public void setOmitMetaTag(boolean bool)
+    {
+        m_omitMetaTag = bool;
+    }
+
+    /**
+     * Specifies an output format for this serializer. It the
+     * serializer has already been associated with an output format,
+     * it will switch to the new format. This method should not be
+     * called while the serializer is in the process of serializing
+     * a document.
+     * 
+     * This method can be called multiple times before starting
+     * the serialization of a particular result-tree. In principle
+     * all serialization parameters can be changed, with the exception
+     * of method="html" (it must be method="html" otherwise we
+     * shouldn't even have a ToHTMLStream object here!) 
+     *
+     * @param format The output format or serialzation parameters
+     * to use.
+     */
+    public void setOutputFormat(Properties format)
+    {
+        /*
+         * If "format" does not contain the property
+         * S_USE_URL_ESCAPING, then don't set this value at all,
+         * just leave as-is rather than explicitly setting it.
+         */
+        String value; 
+        value = format.getProperty(OutputPropertiesFactory.S_USE_URL_ESCAPING);
+        if (value != null) {
+            m_specialEscapeURLs =
+                OutputPropertyUtils.getBooleanProperty(
+                    OutputPropertiesFactory.S_USE_URL_ESCAPING,
+                    format);
+        }
+
+        /*
+         * If "format" does not contain the property
+         * S_OMIT_META_TAG, then don't set this value at all,
+         * just leave as-is rather than explicitly setting it.
+         */
+        value = format.getProperty(OutputPropertiesFactory.S_OMIT_META_TAG);
+        if (value != null) {
+           m_omitMetaTag =
+                OutputPropertyUtils.getBooleanProperty(
+                    OutputPropertiesFactory.S_OMIT_META_TAG,
+                    format);
+        }
+
+        super.setOutputFormat(format);
+    }
+
+    /**
+     * Tells if the formatter should use special URL escaping.
+     *
+     * @return True if URLs should be specially escaped with the %xx form.
+     */
+    private final boolean getSpecialEscapeURLs()
+    {
+        return m_specialEscapeURLs;
+    }
+
+    /**
+     * Tells if the formatter should omit the META tag.
+     *
+     * @return True if the META tag should be omitted.
+     */
+    private final boolean getOmitMetaTag()
+    {
+        return m_omitMetaTag;
+    }
+
+    /**
+     * Get a description of the given element.
+     *
+     * @param name non-null name of element, case insensitive.
+     *
+     * @return non-null reference to ElemDesc, which may be m_dummy if no 
+     *         element description matches the given name.
+     */
+    public static final ElemDesc getElemDesc(String name)
+    {
+        /* this method used to return m_dummy  when name was null
+         * but now it doesn't check and and requires non-null name.
+         */
+        Object obj = m_elementFlags.get(name);
+        if (null != obj)
+            return (ElemDesc)obj;
+        return m_dummy;
+    }
+    
+    
+    /**
+     * A Trie that is just a copy of the "static" one.
+     * We need this one to be able to use the faster, but not thread-safe
+     * method Trie.get2(name)
+     */
+    private Trie m_htmlInfo = new Trie(m_elementFlags);
+    /**
+     * Calls to this method could be replaced with calls to
+     * getElemDesc(name), but this one should be faster.
+     */
+    private ElemDesc getElemDesc2(String name)
+    {
+        Object obj = m_htmlInfo.get2(name);
+        if (null != obj)
+            return (ElemDesc)obj;
+        return m_dummy;
+    }
+
+    /**
+     * Default constructor.
+     */
+    public ToHTMLStream()
+    {
+
+        super();
+        // we are just constructing this thing, no output properties
+        // have been used, so we will set the right default for
+        // indenting anyways
+        m_doIndent = true; 
+        m_charInfo = m_htmlcharInfo;
+        // initialize namespaces
+        m_prefixMap = new NamespaceMappings();
+
+    }
+
+    /** The name of the current element. */
+//    private String m_currentElementName = null;
+
+    /**
+     * Receive notification of the beginning of a document.
+     *
+     * @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    protected void startDocumentInternal() throws org.xml.sax.SAXException
+    {
+        super.startDocumentInternal();
+
+        m_needToCallStartDocument = false; 
+        m_needToOutputDocTypeDecl = true;
+        m_startNewLine = false;
+        setOmitXMLDeclaration(true);
+    }
+
+    /**
+     * This method should only get called once.
+     * If a DOCTYPE declaration needs to get written out, it will
+     * be written out. If it doesn't need to be written out, then
+     * the call to this method has no effect.
+     */
+    private void outputDocTypeDecl(String name) throws SAXException {
+        if (true == m_needToOutputDocTypeDecl)
+        {
+            String doctypeSystem = getDoctypeSystem();
+            String doctypePublic = getDoctypePublic();
+            if ((null != doctypeSystem) || (null != doctypePublic))
+            {
+                final java.io.Writer writer = m_writer;
+                try
+                {
+                writer.write("<!DOCTYPE ");
+                writer.write(name);
+
+                if (null != doctypePublic)
+                {
+                    writer.write(" PUBLIC \"");
+                    writer.write(doctypePublic);
+                    writer.write('"');
+                }
+
+                if (null != doctypeSystem)
+                {
+                    if (null == doctypePublic)
+                        writer.write(" SYSTEM \"");
+                    else
+                        writer.write(" \"");
+
+                    writer.write(doctypeSystem);
+                    writer.write('"');
+                }
+
+                writer.write('>');
+                outputLineSep();
+                }
+                catch(IOException e)
+                {
+                    throw new SAXException(e);
+                }
+            }
+        }
+
+        m_needToOutputDocTypeDecl = false;
+    }
+
+    /**
+     * Receive notification of the end of a document. 
+     *
+     * @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public final void endDocument() throws org.xml.sax.SAXException
+    {
+        
+        flushPending();
+        if (m_doIndent && !m_isprevtext)
+        {
+            try
+            {
+            outputLineSep();
+            }
+            catch(IOException e)
+            {
+                throw new SAXException(e);
+            }
+        }
+
+        flushWriter();
+        if (m_tracer != null)
+            super.fireEndDoc();
+    }
+
+    /**
+     *  Receive notification of the beginning of an element.
+     *
+     *
+     *  @param namespaceURI
+     *  @param localName
+     *  @param name The element type name.
+     *  @param atts The attributes attached to the element, if any.
+     *  @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *             wrapping another exception.
+     *  @see #endElement
+     *  @see org.xml.sax.AttributeList
+     */
+    public void startElement(
+        String namespaceURI,
+        String localName,
+        String name,
+        Attributes atts)
+        throws org.xml.sax.SAXException
+    {
+
+        ElemContext elemContext = m_elemContext;
+
+        // clean up any pending things first
+        if (elemContext.m_startTagOpen)
+        {
+            closeStartTag();
+            elemContext.m_startTagOpen = false;
+        }
+        else if (m_cdataTagOpen)
+        {
+            closeCDATA();
+            m_cdataTagOpen = false;
+        }
+        else if (m_needToCallStartDocument)
+        {
+            startDocumentInternal();
+            m_needToCallStartDocument = false;
+        }
+        
+        if (m_needToOutputDocTypeDecl) {            
+            String n = name;
+            if (n == null || n.length() == 0) {
+                // If the lexical QName is not given
+                // use the localName in the DOCTYPE
+                n = localName;
+            }
+            outputDocTypeDecl(n);
+        }
+
+
+        // if this element has a namespace then treat it like XML
+        if (null != namespaceURI && namespaceURI.length() > 0)
+        {
+            super.startElement(namespaceURI, localName, name, atts);
+
+            return;
+        }
+        
+        try
+        {
+            // getElemDesc2(name) is faster than getElemDesc(name)
+            ElemDesc elemDesc = getElemDesc2(name);
+            int elemFlags = elemDesc.getFlags();
+
+            // deal with indentation issues first
+            if (m_doIndent)
+            {
+
+                boolean isBlockElement = (elemFlags & ElemDesc.BLOCK) != 0;
+                if (m_ispreserve)
+                    m_ispreserve = false;
+                else if (
+                    (null != elemContext.m_elementName)
+                    && (!m_inBlockElem
+                        || isBlockElement) /* && !isWhiteSpaceSensitive */
+                    )
+                {
+                    m_startNewLine = true;
+
+                    indent();
+
+                }
+                m_inBlockElem = !isBlockElement;
+            }
+
+            // save any attributes for later processing
+            if (atts != null)
+                addAttributes(atts);            
+
+            m_isprevtext = false;
+            final java.io.Writer writer = m_writer;
+            writer.write('<');
+            writer.write(name);
+
+
+
+            if (m_tracer != null)
+                firePseudoAttributes();
+            
+            if ((elemFlags & ElemDesc.EMPTY) != 0)  
+            {
+                // an optimization for elements which are expected
+                // to be empty.
+                m_elemContext = elemContext.push();
+                /* XSLTC sometimes calls namespaceAfterStartElement()
+                 * so we need to remember the name
+                 */
+                m_elemContext.m_elementName = name;
+                m_elemContext.m_elementDesc = elemDesc;
+                return;                
+            } 
+            else
+            {
+                elemContext = elemContext.push(namespaceURI,localName,name);
+                m_elemContext = elemContext;
+                elemContext.m_elementDesc = elemDesc;
+                elemContext.m_isRaw = (elemFlags & ElemDesc.RAW) != 0;
+            }
+            
+
+            if ((elemFlags & ElemDesc.HEADELEM) != 0)
+            {
+                // This is the <HEAD> element, do some special processing
+                closeStartTag();
+                elemContext.m_startTagOpen = false;
+                if (!m_omitMetaTag)
+                {
+                    if (m_doIndent)
+                        indent();
+                    writer.write(
+                        "<META http-equiv=\"Content-Type\" content=\"text/html; charset=");
+                    String encoding = getEncoding();
+                    String encode = Encodings.getMimeEncoding(encoding);
+                    writer.write(encode);
+                    writer.write("\">");
+                }
+            }
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+    }
+
+    /**
+     *  Receive notification of the end of an element.
+     *
+     *
+     *  @param namespaceURI
+     *  @param localName
+     *  @param name The element type name
+     *  @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *             wrapping another exception.
+     */
+    public final void endElement(
+        final String namespaceURI,
+        final String localName,
+        final String name)
+        throws org.xml.sax.SAXException
+    {
+        // deal with any pending issues
+        if (m_cdataTagOpen)
+            closeCDATA();
+
+        // if the element has a namespace, treat it like XML, not HTML
+        if (null != namespaceURI && namespaceURI.length() > 0)
+        {
+            super.endElement(namespaceURI, localName, name);
+
+            return;
+        }
+
+        try
+        {
+
+            ElemContext elemContext = m_elemContext;
+            final ElemDesc elemDesc = elemContext.m_elementDesc;
+            final int elemFlags = elemDesc.getFlags();
+            final boolean elemEmpty = (elemFlags & ElemDesc.EMPTY) != 0;
+
+            // deal with any indentation issues
+            if (m_doIndent)
+            {
+                final boolean isBlockElement = (elemFlags&ElemDesc.BLOCK) != 0;
+                boolean shouldIndent = false;
+
+                if (m_ispreserve)
+                {
+                    m_ispreserve = false;
+                }
+                else if (m_doIndent && (!m_inBlockElem || isBlockElement))
+                {
+                    m_startNewLine = true;
+                    shouldIndent = true;
+                }
+                if (!elemContext.m_startTagOpen && shouldIndent)
+                    indent(elemContext.m_currentElemDepth - 1);
+                m_inBlockElem = !isBlockElement;
+            }
+
+            final java.io.Writer writer = m_writer;
+            if (!elemContext.m_startTagOpen)
+            {
+                writer.write("</");
+                writer.write(name);
+                writer.write('>');
+            }
+            else
+            {
+                // the start-tag open when this method was called,
+                // so we need to process it now.
+                
+                if (m_tracer != null)
+                    super.fireStartElem(name);
+
+                // the starting tag was still open when we received this endElement() call
+                // so we need to process any gathered attributes NOW, before they go away.
+                int nAttrs = m_attributes.getLength();
+                if (nAttrs > 0)
+                {
+                    processAttributes(m_writer, nAttrs);
+                    // clear attributes object for re-use with next element
+                    m_attributes.clear();
+                }
+                if (!elemEmpty)
+                {
+                    // As per Dave/Paul recommendation 12/06/2000
+                    // if (shouldIndent)
+                    // writer.write('>');
+                    //  indent(m_currentIndent);
+
+                    writer.write("></");
+                    writer.write(name);
+                    writer.write('>');
+                }
+                else
+                {
+                    writer.write('>');
+                }
+            }
+            
+            // clean up because the element has ended
+            if ((elemFlags & ElemDesc.WHITESPACESENSITIVE) != 0)
+                m_ispreserve = true;
+            m_isprevtext = false;
+
+            // fire off the end element event
+            if (m_tracer != null)
+                super.fireEndElem(name);            
+                           
+            // OPTIMIZE-EMPTY                
+            if (elemEmpty)
+            {
+                // a quick exit if the HTML element had no children.
+                // This block of code can be removed if the corresponding block of code
+                // in startElement() also labeled with "OPTIMIZE-EMPTY" is also removed
+                m_elemContext = elemContext.m_prev;
+                return;
+            }
+
+            // some more clean because the element has ended. 
+            if (!elemContext.m_startTagOpen)
+            {
+                if (m_doIndent && !m_preserves.isEmpty())
+                    m_preserves.pop();
+            }
+            m_elemContext = elemContext.m_prev;
+//            m_isRawStack.pop();
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+    }
+
+    /**
+     * Process an attribute.
+     * @param   writer The writer to write the processed output to.
+     * @param   name   The name of the attribute.
+     * @param   value   The value of the attribute.
+     * @param   elemDesc The description of the HTML element 
+     *           that has this attribute.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    protected void processAttribute(
+        java.io.Writer writer,
+        String name,
+        String value,
+        ElemDesc elemDesc)
+        throws IOException
+    {
+        writer.write(' ');
+
+        if (   ((value.length() == 0) || value.equalsIgnoreCase(name))
+            && elemDesc != null 
+            && elemDesc.isAttrFlagSet(name, ElemDesc.ATTREMPTY))
+        {
+            writer.write(name);
+        }
+        else
+        {
+            // %REVIEW% %OPT%
+            // Two calls to single-char write may NOT
+            // be more efficient than one to string-write...
+            writer.write(name);
+            writer.write("=\"");
+            if (   elemDesc != null
+                && elemDesc.isAttrFlagSet(name, ElemDesc.ATTRURL))
+                writeAttrURI(writer, value, m_specialEscapeURLs);
+            else
+                writeAttrString(writer, value, this.getEncoding());
+            writer.write('"');
+
+        }
+    }
+
+    /**
+     * Tell if a character is an ASCII digit.
+     */
+    private boolean isASCIIDigit(char c)
+    {
+        return (c >= '0' && c <= '9');
+    }
+
+    /**
+     * Make an integer into an HH hex value.
+     * Does no checking on the size of the input, since this 
+     * is only meant to be used locally by writeAttrURI.
+     * 
+     * @param i must be a value less than 255.
+     * 
+     * @return should be a two character string.
+     */
+    private static String makeHHString(int i)
+    {
+        String s = Integer.toHexString(i).toUpperCase();
+        if (s.length() == 1)
+        {
+            s = "0" + s;
+        }
+        return s;
+    }
+
+    /**
+    * Dmitri Ilyin: Makes sure if the String is HH encoded sign.
+    * @param str must be 2 characters long
+    *
+    * @return true or false
+    */
+    private boolean isHHSign(String str)
+    {
+        boolean sign = true;
+        try
+        {
+            char r = (char) Integer.parseInt(str, 16);
+        }
+        catch (NumberFormatException e)
+        {
+            sign = false;
+        }
+        return sign;
+    }
+
+    /**
+     * Write the specified <var>string</var> after substituting non ASCII characters,
+     * with <CODE>%HH</CODE>, where HH is the hex of the byte value.
+     *
+     * @param   string      String to convert to XML format.
+     * @param doURLEscaping True if we should try to encode as 
+     *                      per http://www.ietf.org/rfc/rfc2396.txt.
+     *
+     * @throws org.xml.sax.SAXException if a bad surrogate pair is detected.
+     */
+    public void writeAttrURI(
+        final java.io.Writer writer, String string, boolean doURLEscaping)
+        throws IOException
+    {
+        // http://www.ietf.org/rfc/rfc2396.txt says:
+        // A URI is always in an "escaped" form, since escaping or unescaping a
+        // completed URI might change its semantics.  Normally, the only time
+        // escape encodings can safely be made is when the URI is being created
+        // from its component parts; each component may have its own set of
+        // characters that are reserved, so only the mechanism responsible for
+        // generating or interpreting that component can determine whether or
+        // not escaping a character will change its semantics. Likewise, a URI
+        // must be separated into its components before the escaped characters
+        // within those components can be safely decoded.
+        //
+        // ...So we do our best to do limited escaping of the URL, without 
+        // causing damage.  If the URL is already properly escaped, in theory, this 
+        // function should not change the string value.
+
+        final int end = string.length();
+        if (end > m_attrBuff.length)
+        {
+           m_attrBuff = new char[end*2 + 1];               
+        }
+        string.getChars(0,end, m_attrBuff, 0); 
+        final char[] chars = m_attrBuff;
+
+        int cleanStart = 0;
+        int cleanLength = 0;
+        
+        
+        char ch = 0;
+        for (int i = 0; i < end; i++)
+        {
+            ch = chars[i];
+
+            if ((ch < 32) || (ch > 126))
+            {
+                if (cleanLength > 0)
+                {
+                    writer.write(chars, cleanStart, cleanLength);
+                    cleanLength = 0;
+                }
+                if (doURLEscaping)
+                {
+                    // Encode UTF16 to UTF8.
+                    // Reference is Unicode, A Primer, by Tony Graham.
+                    // Page 92.
+
+                    // Note that Kay doesn't escape 0x20...
+                    //  if(ch == 0x20) // Not sure about this... -sb
+                    //  {
+                    //    writer.write(ch);
+                    //  }
+                    //  else 
+                    if (ch <= 0x7F)
+                    {
+                        writer.write('%');
+                        writer.write(makeHHString(ch));
+                    }
+                    else if (ch <= 0x7FF)
+                    {
+                        // Clear low 6 bits before rotate, put high 4 bits in low byte, 
+                        // and set two high bits.
+                        int high = (ch >> 6) | 0xC0;
+                        int low = (ch & 0x3F) | 0x80;
+                        // First 6 bits, + high bit
+                        writer.write('%');
+                        writer.write(makeHHString(high));
+                        writer.write('%');
+                        writer.write(makeHHString(low));
+                    }
+                    else if (Encodings.isHighUTF16Surrogate(ch)) // high surrogate
+                    {
+                        // I'm sure this can be done in 3 instructions, but I choose 
+                        // to try and do it exactly like it is done in the book, at least 
+                        // until we are sure this is totally clean.  I don't think performance 
+                        // is a big issue with this particular function, though I could be 
+                        // wrong.  Also, the stuff below clearly does more masking than 
+                        // it needs to do.
+
+                        // Clear high 6 bits.
+                        int highSurrogate = ((int) ch) & 0x03FF;
+
+                        // Middle 4 bits (wwww) + 1
+                        // "Note that the value of wwww from the high surrogate bit pattern
+                        // is incremented to make the uuuuu bit pattern in the scalar value 
+                        // so the surrogate pair don't address the BMP."
+                        int wwww = ((highSurrogate & 0x03C0) >> 6);
+                        int uuuuu = wwww + 1;
+
+                        // next 4 bits
+                        int zzzz = (highSurrogate & 0x003C) >> 2;
+
+                        // low 2 bits
+                        int yyyyyy = ((highSurrogate & 0x0003) << 4) & 0x30;
+
+                        // Get low surrogate character.
+                        ch = chars[++i];
+
+                        // Clear high 6 bits.
+                        int lowSurrogate = ((int) ch) & 0x03FF;
+
+                        // put the middle 4 bits into the bottom of yyyyyy (byte 3)
+                        yyyyyy = yyyyyy | ((lowSurrogate & 0x03C0) >> 6);
+
+                        // bottom 6 bits.
+                        int xxxxxx = (lowSurrogate & 0x003F);
+
+                        int byte1 = 0xF0 | (uuuuu >> 2); // top 3 bits of uuuuu
+                        int byte2 =
+                            0x80 | (((uuuuu & 0x03) << 4) & 0x30) | zzzz;
+                        int byte3 = 0x80 | yyyyyy;
+                        int byte4 = 0x80 | xxxxxx;
+
+                        writer.write('%');
+                        writer.write(makeHHString(byte1));
+                        writer.write('%');
+                        writer.write(makeHHString(byte2));
+                        writer.write('%');
+                        writer.write(makeHHString(byte3));
+                        writer.write('%');
+                        writer.write(makeHHString(byte4));
+                    }
+                    else
+                    {
+                        int high = (ch >> 12) | 0xE0; // top 4 bits
+                        int middle = ((ch & 0x0FC0) >> 6) | 0x80;
+                        // middle 6 bits
+                        int low = (ch & 0x3F) | 0x80;
+                        // First 6 bits, + high bit
+                        writer.write('%');
+                        writer.write(makeHHString(high));
+                        writer.write('%');
+                        writer.write(makeHHString(middle));
+                        writer.write('%');
+                        writer.write(makeHHString(low));
+                    }
+
+                }
+                else if (escapingNotNeeded(ch))
+                {
+                    writer.write(ch);
+                }
+                else
+                {
+                    writer.write("&#");
+                    writer.write(Integer.toString(ch));
+                    writer.write(';');
+                }
+                // In this character range we have first written out any previously accumulated 
+                // "clean" characters, then processed the current more complicated character,
+                // which may have incremented "i".
+                // We now we reset the next possible clean character.
+                cleanStart = i + 1;
+            }
+            // Since http://www.ietf.org/rfc/rfc2396.txt refers to the URI grammar as
+            // not allowing quotes in the URI proper syntax, nor in the fragment 
+            // identifier, we believe that it's OK to double escape quotes.
+            else if (ch == '"')
+            {
+                // If the character is a '%' number number, try to avoid double-escaping.
+                // There is a question if this is legal behavior.
+
+                // Dmitri Ilyin: to check if '%' number number is invalid. It must be checked if %xx is a sign, that would be encoded
+                // The encoded signes are in Hex form. So %xx my be in form %3C that is "<" sign. I will try to change here a little.
+
+                //        if( ((i+2) < len) && isASCIIDigit(stringArray[i+1]) && isASCIIDigit(stringArray[i+2]) )
+
+                // We are no longer escaping '%'
+
+                if (cleanLength > 0)
+                {
+                    writer.write(chars, cleanStart, cleanLength);
+                    cleanLength = 0;
+                }   
+                
+                
+                // Mike Kay encodes this as &#34;, so he may know something I don't?
+                if (doURLEscaping)
+                    writer.write("%22");
+                else
+                    writer.write("&quot;"); // we have to escape this, I guess.
+
+                // We have written out any clean characters, then the escaped '%' and now we
+                // We now we reset the next possible clean character.
+                cleanStart = i + 1;    
+            }
+            else if (ch == '&')
+            {
+                // HTML 4.01 reads, "Authors should use "&amp;" (ASCII decimal 38) 
+                // instead of "&" to avoid confusion with the beginning of a character 
+                // reference (entity reference open delimiter). 
+                if (cleanLength > 0)
+                {
+                    writer.write(chars, cleanStart, cleanLength);
+                    cleanLength = 0;
+                } 
+                writer.write("&amp;");
+                cleanStart = i + 1; 
+            }
+            else
+            {
+                // no processing for this character, just count how
+                // many characters in a row that we have that need no processing
+                cleanLength++;
+            }
+        }
+        
+        // are there any clean characters at the end of the array
+        // that we haven't processed yet?
+        if (cleanLength > 1)
+        {
+            // if the whole string can be written out as-is do so
+            // otherwise write out the clean chars at the end of the
+            // array
+            if (cleanStart == 0)
+                writer.write(string);
+            else
+                writer.write(chars, cleanStart, cleanLength);
+        }
+        else if (cleanLength == 1)
+        {
+            // a little optimization for 1 clean character
+            // (we could have let the previous if(...) handle them all)
+            writer.write(ch);
+        }
+    }
+
+    /**
+     * Writes the specified <var>string</var> after substituting <VAR>specials</VAR>,
+     * and UTF-16 surrogates for character references <CODE>&amp;#xnn</CODE>.
+     *
+     * @param   string      String to convert to XML format.
+     * @param   encoding    CURRENTLY NOT IMPLEMENTED.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public void writeAttrString(
+        final java.io.Writer writer, String string, String encoding)
+        throws IOException
+    {
+        final int end = string.length();
+        if (end > m_attrBuff.length)
+        {
+            m_attrBuff = new char[end * 2 + 1];
+        }
+        string.getChars(0, end, m_attrBuff, 0);
+        final char[] chars = m_attrBuff;
+
+        
+
+        int cleanStart = 0;
+        int cleanLength = 0;
+
+        char ch = 0;
+        for (int i = 0; i < end; i++)
+        {
+            ch = chars[i];
+
+            // System.out.println("SPECIALSSIZE: "+SPECIALSSIZE);
+            // System.out.println("ch: "+(int)ch);
+            // System.out.println("m_maxCharacter: "+(int)m_maxCharacter);
+            // System.out.println("m_attrCharsMap[ch]: "+(int)m_attrCharsMap[ch]);
+            if (escapingNotNeeded(ch) && (!m_charInfo.shouldMapAttrChar(ch)))
+            {
+                cleanLength++;
+            }
+            else if ('<' == ch || '>' == ch)
+            {
+                cleanLength++; // no escaping in this case, as specified in 15.2
+            }
+            else if (
+                ('&' == ch) && ((i + 1) < end) && ('{' == chars[i + 1]))
+            {
+                cleanLength++; // no escaping in this case, as specified in 15.2
+            }
+            else
+            {
+                if (cleanLength > 0)
+                {
+                    writer.write(chars,cleanStart,cleanLength);
+                    cleanLength = 0;
+                }
+                int pos = accumDefaultEntity(writer, ch, i, chars, end, false, true);
+
+                if (i != pos)
+                {
+                    i = pos - 1;
+                }
+                else
+                {
+                    if (Encodings.isHighUTF16Surrogate(ch))
+                    {
+ 
+                            writeUTF16Surrogate(ch, chars, i, end);
+                            i++; // two input characters processed
+                                 // this increments by one and the for()
+                                 // loop itself increments by another one.
+                    }
+
+                    // The next is kind of a hack to keep from escaping in the case 
+                    // of Shift_JIS and the like.
+
+                    /*
+                    else if ((ch < m_maxCharacter) && (m_maxCharacter == 0xFFFF)
+                    && (ch != 160))
+                    {
+                    writer.write(ch);  // no escaping in this case
+                    }
+                    else
+                    */
+                    String outputStringForChar = m_charInfo.getOutputStringForChar(ch);
+                    if (null != outputStringForChar)
+                    {
+                        writer.write(outputStringForChar);
+                    }
+                    else if (escapingNotNeeded(ch))
+                    {
+                        writer.write(ch); // no escaping in this case
+                    }
+                    else
+                    {
+                        writer.write("&#");
+                        writer.write(Integer.toString(ch));
+                        writer.write(';');
+                    }
+                }
+                cleanStart = i + 1;
+            }
+        } // end of for()
+        
+        // are there any clean characters at the end of the array
+        // that we haven't processed yet?
+        if (cleanLength > 1)
+        {
+            // if the whole string can be written out as-is do so
+            // otherwise write out the clean chars at the end of the
+            // array
+            if (cleanStart == 0)
+                writer.write(string);
+            else
+                writer.write(chars, cleanStart, cleanLength);
+        }
+        else if (cleanLength == 1)
+        {
+            // a little optimization for 1 clean character
+            // (we could have let the previous if(...) handle them all)
+            writer.write(ch);
+        }
+    }
+
+
+
+    /**
+     * Receive notification of character data.
+     *
+     * <p>The Parser will call this method to report each chunk of
+     * character data.  SAX parsers may return all contiguous character
+     * data in a single chunk, or they may split it into several
+     * chunks; however, all of the characters in any single event
+     * must come from the same external entity, so that the Locator
+     * provides useful information.</p>
+     *
+     * <p>The application must not attempt to read from the array
+     * outside of the specified range.</p>
+     *
+     * <p>Note that some parsers will report whitespace using the
+     * ignorableWhitespace() method rather than this one (validating
+     * parsers must do so).</p>
+     *
+     * @param chars The characters from the XML document.
+     * @param start The start position in the array.
+     * @param length The number of characters to read from the array.
+     * @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see #ignorableWhitespace
+     * @see org.xml.sax.Locator
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public final void characters(char chars[], int start, int length)
+        throws org.xml.sax.SAXException
+    {
+
+        if (m_elemContext.m_isRaw)
+        { 
+            try
+            {
+                // Clean up some pending issues.
+                if (m_elemContext.m_startTagOpen)
+                {
+                    closeStartTag();
+                    m_elemContext.m_startTagOpen = false;
+                }
+                
+                m_ispreserve = true;
+                
+                writeNormalizedChars(chars, start, length, false, m_lineSepUse);
+                
+                // time to generate characters event
+                if (m_tracer != null)
+                    super.fireCharEvent(chars, start, length);
+                
+                return;
+            }
+            catch (IOException ioe)
+            {
+                throw new org.xml.sax.SAXException(
+                    Utils.messages.createMessage(MsgKey.ER_OIERROR,null),ioe);
+            }
+        }
+        else
+        {
+            super.characters(chars, start, length);
+        }
+    }
+
+    /**
+     *  Receive notification of cdata.
+     *
+     *  <p>The Parser will call this method to report each chunk of
+     *  character data.  SAX parsers may return all contiguous character
+     *  data in a single chunk, or they may split it into several
+     *  chunks; however, all of the characters in any single event
+     *  must come from the same external entity, so that the Locator
+     *  provides useful information.</p>
+     *
+     *  <p>The application must not attempt to read from the array
+     *  outside of the specified range.</p>
+     *
+     *  <p>Note that some parsers will report whitespace using the
+     *  ignorableWhitespace() method rather than this one (validating
+     *  parsers must do so).</p>
+     *
+     *  @param ch The characters from the XML document.
+     *  @param start The start position in the array.
+     *  @param length The number of characters to read from the array.
+     *  @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *             wrapping another exception.
+     *  @see #ignorableWhitespace
+     *  @see org.xml.sax.Locator
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public final void cdata(char ch[], int start, int length)
+        throws org.xml.sax.SAXException
+    {
+
+        if ((null != m_elemContext.m_elementName)
+            && (m_elemContext.m_elementName.equalsIgnoreCase("SCRIPT")
+                || m_elemContext.m_elementName.equalsIgnoreCase("STYLE")))
+        {
+            try
+            {
+                if (m_elemContext.m_startTagOpen)
+                {
+                    closeStartTag();
+                    m_elemContext.m_startTagOpen = false;
+                }
+
+                m_ispreserve = true;
+
+                if (shouldIndent())
+                    indent();
+
+                // writer.write(ch, start, length);
+                writeNormalizedChars(ch, start, length, true, m_lineSepUse);
+            }
+            catch (IOException ioe)
+            {
+                throw new org.xml.sax.SAXException(
+                    Utils.messages.createMessage(
+                        MsgKey.ER_OIERROR,
+                        null),
+                    ioe);
+                //"IO error", ioe);
+            }
+        }
+        else
+        {
+            super.cdata(ch, start, length);
+        }
+    }
+
+    /**
+     *  Receive notification of a processing instruction.
+     *
+     *  @param target The processing instruction target.
+     *  @param data The processing instruction data, or null if
+     *         none was supplied.
+     *  @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *             wrapping another exception.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public void processingInstruction(String target, String data)
+        throws org.xml.sax.SAXException
+    {
+
+        // Process any pending starDocument and startElement first.
+        flushPending(); 
+        
+        // Use a fairly nasty hack to tell if the next node is supposed to be 
+        // unescaped text.
+        if (target.equals(Result.PI_DISABLE_OUTPUT_ESCAPING))
+        {
+            startNonEscaping();
+        }
+        else if (target.equals(Result.PI_ENABLE_OUTPUT_ESCAPING))
+        {
+            endNonEscaping();
+        }
+        else
+        {
+            try
+            {
+                // clean up any pending things first
+                if (m_elemContext.m_startTagOpen)
+                {
+                    closeStartTag();
+                    m_elemContext.m_startTagOpen = false;
+                }
+                else if (m_cdataTagOpen)
+                {
+                    closeCDATA();
+                }
+                else if (m_needToCallStartDocument)
+                {
+                    startDocumentInternal();
+                }
+            
+
+            /*
+             * Perhaps processing instructions can be written out in HTML before
+             * the DOCTYPE, in which case this could be emitted with the
+             * startElement call, that knows the name of the document element
+             * doing it right.
+             */
+            if (true == m_needToOutputDocTypeDecl)
+                outputDocTypeDecl("html"); // best guess for the upcoming element
+
+ 
+            if (shouldIndent())
+                indent();
+
+            final java.io.Writer writer = m_writer;
+            //writer.write("<?" + target);
+            writer.write("<?");
+            writer.write(target);
+
+            if (data.length() > 0 && !Character.isSpaceChar(data.charAt(0)))
+                writer.write(' '); 
+
+            //writer.write(data + ">"); // different from XML
+            writer.write(data); // different from XML
+            writer.write('>'); // different from XML
+
+            // Always output a newline char if not inside of an 
+            // element. The whitespace is not significant in that
+            // case.
+            if (m_elemContext.m_currentElemDepth <= 0)
+                outputLineSep();
+
+            m_startNewLine = true;
+            }
+            catch(IOException e)
+            {
+                throw new SAXException(e);
+            }
+        }
+               
+        // now generate the PI event
+        if (m_tracer != null)
+            super.fireEscapingEvent(target, data);
+     }
+
+    /**
+     * Receive notivication of a entityReference.
+     *
+     * @param name non-null reference to entity name string.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public final void entityReference(String name)
+        throws org.xml.sax.SAXException
+    {
+        try
+        {
+
+        final java.io.Writer writer = m_writer;
+        writer.write('&');
+        writer.write(name);
+        writer.write(';');
+        
+        } catch(IOException e)
+        {
+            throw new SAXException(e);
+        }
+    }
+    /**
+     * @see ExtendedContentHandler#endElement(String)
+     */
+    public final void endElement(String elemName) throws SAXException
+    {
+        endElement(null, null, elemName);
+    }
+
+    /**
+     * Process the attributes, which means to write out the currently
+     * collected attributes to the writer. The attributes are not
+     * cleared by this method
+     * 
+     * @param writer the writer to write processed attributes to.
+     * @param nAttrs the number of attributes in m_attributes 
+     * to be processed
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public void processAttributes(java.io.Writer writer, int nAttrs)
+        throws IOException,SAXException
+    {
+            /* 
+             * process the collected attributes
+             */
+            for (int i = 0; i < nAttrs; i++)
+            {
+                processAttribute(
+                    writer,
+                    m_attributes.getQName(i),
+                    m_attributes.getValue(i),
+                    m_elemContext.m_elementDesc);
+            }
+    }
+
+    /**
+     * For the enclosing elements starting tag write out out any attributes
+     * followed by ">". At this point we also mark if this element is
+     * a cdata-section-element.
+     *
+     *@throws org.xml.sax.SAXException
+     */
+    protected void closeStartTag() throws SAXException
+    {
+            try
+            {
+
+            // finish processing attributes, time to fire off the start element event
+            if (m_tracer != null)
+                super.fireStartElem(m_elemContext.m_elementName);  
+            
+            int nAttrs = m_attributes.getLength();   
+            if (nAttrs>0)
+            {
+                processAttributes(m_writer, nAttrs);
+                // clear attributes object for re-use with next element
+                m_attributes.clear();
+            }
+
+            m_writer.write('>');
+
+            /* At this point we have the prefix mappings now, so
+             * lets determine if the current element is specified in the cdata-
+             * section-elements list.
+             */
+            if (m_CdataElems != null) // if there are any cdata sections
+                m_elemContext.m_isCdataSection = isCdataSection();
+            if (m_doIndent)
+            {
+                m_isprevtext = false;
+                m_preserves.push(m_ispreserve);
+            }
+            
+            }
+            catch(IOException e)
+            {
+                throw new SAXException(e);
+            }
+    }
+    
+
+   
+        /**
+         * This method is used when a prefix/uri namespace mapping
+         * is indicated after the element was started with a
+         * startElement() and before and endElement().
+         * startPrefixMapping(prefix,uri) would be used before the
+         * startElement() call.
+         * @param uri the URI of the namespace
+         * @param prefix the prefix associated with the given URI.
+         *
+         * @see ExtendedContentHandler#namespaceAfterStartElement(String, String)
+         */
+        public void namespaceAfterStartElement(String prefix, String uri)
+            throws SAXException
+        {
+            // hack for XSLTC with finding URI for default namespace
+            if (m_elemContext.m_elementURI == null)
+            {
+                String prefix1 = getPrefixPart(m_elemContext.m_elementName);
+                if (prefix1 == null && EMPTYSTRING.equals(prefix))
+                {
+                    // the elements URI is not known yet, and it
+                    // doesn't have a prefix, and we are currently
+                    // setting the uri for prefix "", so we have
+                    // the uri for the element... lets remember it
+                    m_elemContext.m_elementURI = uri;
+                }
+            }            
+            startPrefixMapping(prefix,uri,false);
+        }
+
+    public void startDTD(String name, String publicId, String systemId)
+        throws SAXException
+    {
+        m_inDTD = true;
+        super.startDTD(name, publicId, systemId);
+    }
+
+    /**
+     * Report the end of DTD declarations.
+     * @throws org.xml.sax.SAXException The application may raise an exception.
+     * @see #startDTD
+     */
+    public void endDTD() throws org.xml.sax.SAXException
+    {
+        m_inDTD = false;
+        /* for ToHTMLStream the DOCTYPE is entirely output in the
+         * startDocumentInternal() method, so don't do anything here
+         */
+    }
+    /**
+     * This method does nothing.
+     */
+    public void attributeDecl(
+        String eName,
+        String aName,
+        String type,
+        String valueDefault,
+        String value)
+        throws SAXException
+    {
+        // The internal DTD subset is not serialized by the ToHTMLStream serializer
+    }
+
+    /**
+     * This method does nothing.
+     */
+    public void elementDecl(String name, String model) throws SAXException
+    {
+        // The internal DTD subset is not serialized by the ToHTMLStream serializer
+    }
+    /**
+     * This method does nothing.
+     */
+    public void internalEntityDecl(String name, String value)
+        throws SAXException
+    {
+        // The internal DTD subset is not serialized by the ToHTMLStream serializer
+    }
+    /**
+     * This method does nothing.
+     */
+    public void externalEntityDecl(
+        String name,
+        String publicId,
+        String systemId)
+        throws SAXException
+    {
+        // The internal DTD subset is not serialized by the ToHTMLStream serializer
+    }
+
+    /**
+     * This method is used to add an attribute to the currently open element. 
+     * The caller has guaranted that this attribute is unique, which means that it
+     * not been seen before and will not be seen again.
+     * 
+     * @param name the qualified name of the attribute
+     * @param value the value of the attribute which can contain only
+     * ASCII printable characters characters in the range 32 to 127 inclusive.
+     * @param flags the bit values of this integer give optimization information.
+     */
+    public void addUniqueAttribute(String name, String value, int flags)
+        throws SAXException
+    {
+        try
+        {
+            final java.io.Writer writer = m_writer;
+            if ((flags & NO_BAD_CHARS) > 0 && m_htmlcharInfo.onlyQuotAmpLtGt)
+            {
+                // "flags" has indicated that the characters
+                // '>'  '<'   '&'  and '"' are not in the value and
+                // m_htmlcharInfo has recorded that there are no other
+                // entities in the range 0 to 127 so we write out the
+                // value directly
+                writer.write(' ');
+                writer.write(name);
+                writer.write("=\"");
+                writer.write(value);
+                writer.write('"');
+            }
+            else if (
+                (flags & HTML_ATTREMPTY) > 0
+                    && (value.length() == 0 || value.equalsIgnoreCase(name)))
+            {
+                writer.write(' ');
+                writer.write(name);
+            }
+            else
+            {
+                writer.write(' ');
+                writer.write(name);
+                writer.write("=\"");
+                if ((flags & HTML_ATTRURL) > 0)
+                {
+                    writeAttrURI(writer, value, m_specialEscapeURLs);
+                }
+                else
+                {
+                    writeAttrString(writer, value, this.getEncoding());
+                }
+                writer.write('"');
+            }
+        } catch (IOException e) {
+            throw new SAXException(e);
+        }
+    }
+
+    public void comment(char ch[], int start, int length)
+            throws SAXException
+    {
+        // The internal DTD subset is not serialized by the ToHTMLStream serializer
+        if (m_inDTD)
+            return;
+        
+        // Clean up some pending issues, just in case
+        // this call is coming right after a startElement()
+        // or we are in the middle of writing out CDATA
+        // or if a startDocument() call was not received
+        if (m_elemContext.m_startTagOpen)
+        {
+            closeStartTag();
+            m_elemContext.m_startTagOpen = false;
+        }
+        else if (m_cdataTagOpen)
+        {
+            closeCDATA();
+        }
+        else if (m_needToCallStartDocument)
+        {
+            startDocumentInternal();
+        }
+
+        /*
+         * Perhaps comments can be written out in HTML before the DOCTYPE.
+         * In this case we might delete this call to writeOutDOCTYPE, and
+         * it would be handled within the startElement() call.
+         */
+        if (m_needToOutputDocTypeDecl)
+            outputDocTypeDecl("html"); // best guess for the upcoming element
+
+        super.comment(ch, start, length);
+    }
+    
+    public boolean reset()
+    {
+        boolean ret = super.reset();
+        if (!ret)
+            return false;
+        resetToHTMLStream();
+        return true;        
+    }
+    
+    private void resetToHTMLStream()
+    {
+        // m_htmlcharInfo remains unchanged
+        // m_htmlInfo = null;  // Don't reset
+        m_inBlockElem = false;
+        m_inDTD = false;
+        m_omitMetaTag = false;
+        m_specialEscapeURLs = true;     
+    }
+    
+    static class Trie
+    {
+        /**
+         * A digital search trie for 7-bit ASCII text
+         * The API is a subset of java.util.Hashtable
+         * The key must be a 7-bit ASCII string
+         * The value may be any Java Object
+         * One can get an object stored in a trie from its key, 
+         * but the search is either case sensitive or case 
+         * insensitive to the characters in the key, and this
+         * choice of sensitivity or insensitivity is made when
+         * the Trie is created, before any objects are put in it.
+         * 
+         * This class is a copy of the one in org.apache.xml.utils. 
+         * It exists to cut the serializers dependancy on that package.
+         *  
+         * @xsl.usage internal
+         */
+
+        /** Size of the m_nextChar array.  */
+        public static final int ALPHA_SIZE = 128;
+
+        /** The root node of the tree.    */
+        final Node m_Root;
+
+        /** helper buffer to convert Strings to char arrays */
+        private char[] m_charBuffer = new char[0];
+
+        /** true if the search for an object is lower case only with the key */
+        private final boolean m_lowerCaseOnly;
+
+        /**
+         * Construct the trie that has a case insensitive search.
+         */
+        public Trie()
+        {
+            m_Root = new Node();
+            m_lowerCaseOnly = false;
+        }
+
+        /**
+         * Construct the trie given the desired case sensitivity with the key.
+         * @param lowerCaseOnly true if the search keys are to be loser case only,
+         * not case insensitive.
+         */
+        public Trie(boolean lowerCaseOnly)
+        {
+            m_Root = new Node();
+            m_lowerCaseOnly = lowerCaseOnly;
+        }
+
+        /**
+         * Put an object into the trie for lookup.
+         *
+         * @param key must be a 7-bit ASCII string
+         * @param value any java object.
+         *
+         * @return The old object that matched key, or null.
+         */
+        public Object put(String key, Object value)
+        {
+
+            final int len = key.length();
+            if (len > m_charBuffer.length)
+            {
+                // make the biggest buffer ever needed in get(String)
+                m_charBuffer = new char[len];
+            }
+
+            Node node = m_Root;
+
+            for (int i = 0; i < len; i++)
+            {
+                Node nextNode =
+                    node.m_nextChar[Character.toLowerCase(key.charAt(i))];
+
+                if (nextNode != null)
+                {
+                    node = nextNode;
+                }
+                else
+                {
+                    for (; i < len; i++)
+                    {
+                        Node newNode = new Node();
+                        if (m_lowerCaseOnly)
+                        {
+                            // put this value into the tree only with a lower case key 
+                            node.m_nextChar[Character.toLowerCase(
+                                key.charAt(i))] =
+                                newNode;
+                        }
+                        else
+                        {
+                            // put this value into the tree with a case insensitive key
+                            node.m_nextChar[Character.toUpperCase(
+                                key.charAt(i))] =
+                                newNode;
+                            node.m_nextChar[Character.toLowerCase(
+                                key.charAt(i))] =
+                                newNode;
+                        }
+                        node = newNode;
+                    }
+                    break;
+                }
+            }
+
+            Object ret = node.m_Value;
+
+            node.m_Value = value;
+
+            return ret;
+        }
+
+        /**
+         * Get an object that matches the key.
+         *
+         * @param key must be a 7-bit ASCII string
+         *
+         * @return The object that matches the key, or null.
+         */
+        public Object get(final String key)
+        {
+
+            final int len = key.length();
+
+            /* If the name is too long, we won't find it, this also keeps us
+             * from overflowing m_charBuffer
+             */
+            if (m_charBuffer.length < len)
+                return null;
+
+            Node node = m_Root;
+            switch (len) // optimize the look up based on the number of chars
+            {
+                // case 0 looks silly, but the generated bytecode runs
+                // faster for lookup of elements of length 2 with this in
+                // and a fair bit faster.  Don't know why.
+                case 0 :
+                    {
+                        return null;
+                    }
+
+                case 1 :
+                    {
+                        final char ch = key.charAt(0);
+                        if (ch < ALPHA_SIZE)
+                        {
+                            node = node.m_nextChar[ch];
+                            if (node != null)
+                                return node.m_Value;
+                        }
+                        return null;
+                    }
+                    //                comment out case 2 because the default is faster            
+                    //                case 2 :
+                    //                    {
+                    //                        final char ch0 = key.charAt(0);
+                    //                        final char ch1 = key.charAt(1);
+                    //                        if (ch0 < ALPHA_SIZE && ch1 < ALPHA_SIZE)
+                    //                        {
+                    //                            node = node.m_nextChar[ch0];
+                    //                            if (node != null)
+                    //                            {
+                    //                        
+                    //                                if (ch1 < ALPHA_SIZE) 
+                    //                                {
+                    //                                    node = node.m_nextChar[ch1];
+                    //                                    if (node != null)
+                    //                                        return node.m_Value;
+                    //                                }
+                    //                            }
+                    //                        }
+                    //                        return null;
+                    //                   }
+                default :
+                    {
+                        for (int i = 0; i < len; i++)
+                        {
+                            // A thread-safe way to loop over the characters
+                            final char ch = key.charAt(i);
+                            if (ALPHA_SIZE <= ch)
+                            {
+                                // the key is not 7-bit ASCII so we won't find it here
+                                return null;
+                            }
+
+                            node = node.m_nextChar[ch];
+                            if (node == null)
+                                return null;
+                        }
+
+                        return node.m_Value;
+                    }
+            }
+        }
+
+        /**
+         * The node representation for the trie.
+         * @xsl.usage internal
+         */
+        private static class Node
+        {
+
+            /**
+             * Constructor, creates a Node[ALPHA_SIZE].
+             */
+            Node()
+            {
+                m_nextChar = new Node[ALPHA_SIZE];
+                m_Value = null;
+            }
+
+            /** The next nodes.   */
+            final Node m_nextChar[];
+
+            /** The value.   */
+            Object m_Value;
+        }
+        /**
+         * Construct the trie from another Trie.
+         * Both the existing Trie and this new one share the same table for
+         * lookup, and it is assumed that the table is fully populated and
+         * not changing anymore.
+         * 
+         * @param existingTrie the Trie that this one is a copy of.
+         */
+        public Trie(Trie existingTrie)
+        {
+            // copy some fields from the existing Trie into this one.
+            m_Root = existingTrie.m_Root;
+            m_lowerCaseOnly = existingTrie.m_lowerCaseOnly;
+
+            // get a buffer just big enough to hold the longest key in the table.
+            int max = existingTrie.getLongestKeyLength();
+            m_charBuffer = new char[max];
+        }
+
+        /**
+         * Get an object that matches the key.
+         * This method is faster than get(), but is not thread-safe.
+         *
+         * @param key must be a 7-bit ASCII string
+         *
+         * @return The object that matches the key, or null.
+         */
+        public Object get2(final String key)
+        {
+
+            final int len = key.length();
+
+            /* If the name is too long, we won't find it, this also keeps us
+             * from overflowing m_charBuffer
+             */
+            if (m_charBuffer.length < len)
+                return null;
+
+            Node node = m_Root;
+            switch (len) // optimize the look up based on the number of chars
+            {
+                // case 0 looks silly, but the generated bytecode runs
+                // faster for lookup of elements of length 2 with this in
+                // and a fair bit faster.  Don't know why.
+                case 0 :
+                    {
+                        return null;
+                    }
+
+                case 1 :
+                    {
+                        final char ch = key.charAt(0);
+                        if (ch < ALPHA_SIZE)
+                        {
+                            node = node.m_nextChar[ch];
+                            if (node != null)
+                                return node.m_Value;
+                        }
+                        return null;
+                    }
+                default :
+                    {
+                        /* Copy string into array. This is not thread-safe because
+                         * it modifies the contents of m_charBuffer. If multiple
+                         * threads were to use this Trie they all would be
+                         * using this same array (not good). So this 
+                         * method is not thread-safe, but it is faster because
+                         * converting to a char[] and looping over elements of
+                         * the array is faster than a String's charAt(i).
+                         */
+                        key.getChars(0, len, m_charBuffer, 0);
+
+                        for (int i = 0; i < len; i++)
+                        {
+                            final char ch = m_charBuffer[i];
+                            if (ALPHA_SIZE <= ch)
+                            {
+                                // the key is not 7-bit ASCII so we won't find it here
+                                return null;
+                            }
+
+                            node = node.m_nextChar[ch];
+                            if (node == null)
+                                return null;
+                        }
+
+                        return node.m_Value;
+                    }
+            }
+        }
+
+        /**
+         * Get the length of the longest key used in the table. 
+         */
+        public int getLongestKeyLength()
+        {
+            return m_charBuffer.length;
+        }
+    }
+}
diff --git a/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java
new file mode 100644
index 0000000..3b90747
--- /dev/null
+++ b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java
@@ -0,0 +1,3616 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the  "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*
+ * $Id: ToStream.java 1225444 2011-12-29 05:52:39Z mrglavas $
+ */
+package org.apache.xml.serializer;
+
+import org.apache.xml.serializer.utils.MsgKey;
+import org.apache.xml.serializer.utils.Utils;
+import org.apache.xml.serializer.utils.WrappedRuntimeException;
+import org.w3c.dom.Node;
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.io.Writer;
+import java.util.EmptyStackException;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.Properties;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+/**
+ * This abstract class is a base class for other stream 
+ * serializers (xml, html, text ...) that write output to a stream.
+ *
+ * @xsl.usage internal
+ */
+abstract public class ToStream extends SerializerBase
+{
+
+    private static final String COMMENT_BEGIN = "<!--";
+    private static final String COMMENT_END = "-->";
+
+    /** Stack to keep track of disabling output escaping. */
+    protected BoolStack m_disableOutputEscapingStates = new BoolStack();
+
+
+    /**
+     * The encoding information associated with this serializer.
+     * Although initially there is no encoding,
+     * there is a dummy EncodingInfo object that will say
+     * that every character is in the encoding. This is useful
+     * for a serializer that is in temporary output state and has
+     * no associated encoding. A serializer in final output state
+     * will have an encoding, and will worry about whether 
+     * single chars or surrogate pairs of high/low chars form
+     * characters in the output encoding. 
+     */
+    EncodingInfo m_encodingInfo = new EncodingInfo(null,null, '\u0000');
+
+    /**
+     * Stack to keep track of whether or not we need to
+     * preserve whitespace.
+     *
+     * Used to push/pop values used for the field m_ispreserve, but
+     * m_ispreserve is only relevant if m_doIndent is true.
+     * If m_doIndent is false this field has no impact.
+     *
+     */
+    protected BoolStack m_preserves = new BoolStack();
+
+    /**
+     * State flag to tell if preservation of whitespace
+     * is important. 
+     *
+     * Used only in shouldIndent() but only if m_doIndent is true.
+     * If m_doIndent is false this flag has no impact.
+     *
+     */
+    protected boolean m_ispreserve = false;
+
+    /**
+     * State flag that tells if the previous node processed
+     * was text, so we can tell if we should preserve whitespace.
+     *
+     * Used in endDocument() and shouldIndent() but
+     * only if m_doIndent is true. 
+     * If m_doIndent is false this flag has no impact.
+     */
+    protected boolean m_isprevtext = false;
+
+    private static final char[] s_systemLineSep;
+    static {
+        s_systemLineSep = SecuritySupport.getSystemProperty("line.separator").toCharArray();
+    }
+
+    /**
+     * The system line separator for writing out line breaks.
+     * The default value is from the system property,
+     * but this value can be set through the xsl:output
+     * extension attribute xalan:line-separator.
+     */
+    protected char[] m_lineSep = s_systemLineSep;
+
+
+    /**
+     * True if the the system line separator is to be used.
+     */
+    protected boolean m_lineSepUse = true;
+
+    /**
+     * The length of the line seperator, since the write is done
+     * one character at a time.
+     */
+    protected int m_lineSepLen = m_lineSep.length;
+
+    /**
+     * Map that tells which characters should have special treatment, and it
+     *  provides character to entity name lookup.
+     */
+    protected CharInfo m_charInfo;
+
+    /** True if we control the buffer, and we should flush the output on endDocument. */
+    boolean m_shouldFlush = true;
+
+    /**
+     * Add space before '/>' for XHTML.
+     */
+    protected boolean m_spaceBeforeClose = false;
+
+    /**
+     * Flag to signal that a newline should be added.
+     *
+     * Used only in indent() which is called only if m_doIndent is true.
+     * If m_doIndent is false this flag has no impact.
+     */
+    boolean m_startNewLine;
+
+    /**
+     * Tells if we're in an internal document type subset.
+     */
+    protected boolean m_inDoctype = false;
+
+    /**
+     * Flag to quickly tell if the encoding is UTF8.
+     */
+    boolean m_isUTF8 = false;
+
+
+    /**
+     * remembers if we are in between the startCDATA() and endCDATA() callbacks
+     */
+    protected boolean m_cdataStartCalled = false;
+
+    /**
+     * If this flag is true DTD entity references are not left as-is,
+     * which is exiting older behavior.
+     */
+    private boolean m_expandDTDEntities = true;
+
+
+    /**
+     * Default constructor
+     */
+    public ToStream()
+    {
+    }
+
+    /**
+     * This helper method to writes out "]]>" when closing a CDATA section.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    protected void closeCDATA() throws org.xml.sax.SAXException
+    {
+        try
+        {
+            m_writer.write(CDATA_DELIMITER_CLOSE);
+            // write out a CDATA section closing "]]>"
+            m_cdataTagOpen = false; // Remember that we have done so.
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+    }
+
+    /**
+     * Serializes the DOM node. Throws an exception only if an I/O
+     * exception occured while serializing.
+     *
+     * @param node Node to serialize.
+     * @throws IOException An I/O exception occured while serializing
+     */
+    public void serialize(Node node) throws IOException
+    {
+
+        try
+        {
+            TreeWalker walker =
+                new TreeWalker(this);
+
+            walker.traverse(node);
+        }
+        catch (org.xml.sax.SAXException se)
+        {
+            throw new WrappedRuntimeException(se);
+        }
+    }
+
+    /**
+     * Taken from XSLTC 
+     */
+    protected boolean m_escaping = true;
+
+    /**
+     * Flush the formatter's result stream.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    protected final void flushWriter() throws org.xml.sax.SAXException
+    {
+        final java.io.Writer writer = m_writer;
+        if (null != writer)
+        {
+            try
+            {
+                if (writer instanceof WriterToUTF8Buffered)
+                {
+                    if (m_shouldFlush)
+                        ((WriterToUTF8Buffered) writer).flush();
+                    else
+                        ((WriterToUTF8Buffered) writer).flushBuffer();
+                }
+                if (writer instanceof WriterToASCI)
+                {
+                    if (m_shouldFlush)
+                        writer.flush();
+                }
+                else
+                {
+                    // Flush always. 
+                    // Not a great thing if the writer was created 
+                    // by this class, but don't have a choice.
+                    writer.flush();
+                }
+            }
+            catch (IOException ioe)
+            {
+                throw new org.xml.sax.SAXException(ioe);
+            }
+        }
+    }
+
+    OutputStream m_outputStream;
+    /**
+     * Get the output stream where the events will be serialized to.
+     *
+     * @return reference to the result stream, or null of only a writer was
+     * set.
+     */
+    public OutputStream getOutputStream()
+    {
+        return m_outputStream;
+    }
+
+    // Implement DeclHandler
+
+    /**
+     *   Report an element type declaration.
+     *
+     *   <p>The content model will consist of the string "EMPTY", the
+     *   string "ANY", or a parenthesised group, optionally followed
+     *   by an occurrence indicator.  The model will be normalized so
+     *   that all whitespace is removed,and will include the enclosing
+     *   parentheses.</p>
+     *
+     *   @param name The element type name.
+     *   @param model The content model as a normalized string.
+     *   @exception SAXException The application may raise an exception.
+     */
+    public void elementDecl(String name, String model) throws SAXException
+    {
+        // Do not inline external DTD
+        if (m_inExternalDTD)
+            return;
+        try
+        {
+            final java.io.Writer writer = m_writer;
+            DTDprolog();
+
+            writer.write("<!ELEMENT ");
+            writer.write(name);
+            writer.write(' ');
+            writer.write(model);
+            writer.write('>');
+            writer.write(m_lineSep, 0, m_lineSepLen);
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+
+    }
+
+    /**
+     * Report an internal entity declaration.
+     *
+     * <p>Only the effective (first) declaration for each entity
+     * will be reported.</p>
+     *
+     * @param name The name of the entity.  If it is a parameter
+     *        entity, the name will begin with '%'.
+     * @param value The replacement text of the entity.
+     * @exception SAXException The application may raise an exception.
+     * @see #externalEntityDecl
+     * @see org.xml.sax.DTDHandler#unparsedEntityDecl
+     */
+    public void internalEntityDecl(String name, String value)
+        throws SAXException
+    {
+        // Do not inline external DTD
+        if (m_inExternalDTD)
+            return;
+        try
+        {
+            DTDprolog();
+            outputEntityDecl(name, value);
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+
+    }
+
+    /**
+     * Output the doc type declaration.
+     *
+     * @param name non-null reference to document type name.
+     * NEEDSDOC @param value
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    void outputEntityDecl(String name, String value) throws IOException
+    {
+        final java.io.Writer writer = m_writer;
+        writer.write("<!ENTITY ");
+        writer.write(name);
+        writer.write(" \"");
+        writer.write(value);
+        writer.write("\">");
+        writer.write(m_lineSep, 0, m_lineSepLen);
+    }
+
+    /**
+     * Output a system-dependent line break.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    protected final void outputLineSep() throws IOException
+    {
+
+        m_writer.write(m_lineSep, 0, m_lineSepLen);
+    }
+
+    void setProp(String name, String val, boolean defaultVal) {
+        if (val != null) {
+
+
+            char first = getFirstCharLocName(name);
+            switch (first) {
+                case 'c':
+                    if (OutputKeys.CDATA_SECTION_ELEMENTS.equals(name)) {
+                        String cdataSectionNames = val;
+                        addCdataSectionElements(cdataSectionNames);
+                    }
+                    break;
+                case 'd':
+                    if (OutputKeys.DOCTYPE_SYSTEM.equals(name)) {
+                        this.m_doctypeSystem = val;
+                    } else if (OutputKeys.DOCTYPE_PUBLIC.equals(name)) {
+                        this.m_doctypePublic = val;
+                        if (val.startsWith("-//W3C//DTD XHTML"))
+                            m_spaceBeforeClose = true;
+                    }
+                    break;
+                case 'e':
+                    String newEncoding = val;
+                    if (OutputKeys.ENCODING.equals(name)) {
+                        String possible_encoding = Encodings.getMimeEncoding(val);
+                        if (possible_encoding != null) {
+                            // if the encoding is being set, try to get the
+                            // preferred
+                            // mime-name and set it too.
+                            super.setProp("mime-name", possible_encoding,
+                                          defaultVal);
+                        }
+                        final String oldExplicitEncoding = getOutputPropertyNonDefault(OutputKeys.ENCODING);
+                        final String oldDefaultEncoding  = getOutputPropertyDefault(OutputKeys.ENCODING);
+                        if ( (defaultVal && ( oldDefaultEncoding == null || !oldDefaultEncoding.equalsIgnoreCase(newEncoding)))
+                             || ( !defaultVal && (oldExplicitEncoding == null || !oldExplicitEncoding.equalsIgnoreCase(newEncoding) ))) {
+                            // We are trying to change the default or the non-default setting of the encoding to a different value
+                            // from what it was
+
+                            EncodingInfo encodingInfo = Encodings.getEncodingInfo(newEncoding);
+                            if (newEncoding != null && encodingInfo.name == null) {
+                                // We tried to get an EncodingInfo for Object for the given
+                                // encoding, but it came back with an internall null name
+                                // so the encoding is not supported by the JDK, issue a message.
+                                final String msg = Utils.messages.createMessage(
+                                    MsgKey.ER_ENCODING_NOT_SUPPORTED,new Object[]{ newEncoding });
+
+                                final String msg2 =
+                                    "Warning: encoding \"" + newEncoding + "\" not supported, using "
+                                    + Encodings.DEFAULT_MIME_ENCODING;
+                                try {
+                                    // Prepare to issue the warning message
+                                    final Transformer tran = super.getTransformer();
+                                    if (tran != null) {
+                                        final ErrorListener errHandler = tran
+                                            .getErrorListener();
+                                        // Issue the warning message
+                                        if (null != errHandler
+                                            && m_sourceLocator != null) {
+                                            errHandler
+                                                .warning(new TransformerException(
+                                                    msg, m_sourceLocator));
+                                            errHandler
+                                                .warning(new TransformerException(
+                                                    msg2, m_sourceLocator));
+                                        } else {
+                                            System.out.println(msg);
+                                            System.out.println(msg2);
+                                        }
+                                    } else {
+                                        System.out.println(msg);
+                                        System.out.println(msg2);
+                                    }
+                                } catch (Exception e) {
+                                }
+
+                                // We said we are using UTF-8, so use it
+                                newEncoding = Encodings.DEFAULT_MIME_ENCODING;
+                                val = Encodings.DEFAULT_MIME_ENCODING; // to store the modified value into the properties a little later
+                                encodingInfo = Encodings.getEncodingInfo(newEncoding);
+
+                            }
+                            // The encoding was good, or was forced to UTF-8 above
+
+
+                            // If there is already a non-default set encoding and we
+                            // are trying to set the default encoding, skip the this block
+                            // as the non-default value is already the one to use.
+                            if (defaultVal == false || oldExplicitEncoding == null) {
+                                m_encodingInfo = encodingInfo;
+                                if (newEncoding != null)
+                                    m_isUTF8 = newEncoding.equals(Encodings.DEFAULT_MIME_ENCODING);
+
+                                // if there was a previously set OutputStream
+                                OutputStream os = getOutputStream();
+                                if (os != null) {
+                                    Writer w = getWriter();
+
+                                    // If the writer was previously set, but
+                                    // set by the user, or if the new encoding is the same
+                                    // as the old encoding, skip this block
+                                    String oldEncoding = getOutputProperty(OutputKeys.ENCODING);
+                                    if ((w == null || !m_writer_set_by_user)
+                                        && !newEncoding.equalsIgnoreCase(oldEncoding)) {
+                                        // Make the change of encoding in our internal
+                                        // table, then call setOutputStreamInternal
+                                        // which will stomp on the old Writer (if any)
+                                        // with a new Writer with the new encoding.
+                                        super.setProp(name, val, defaultVal);
+                                        setOutputStreamInternal(os,false);
+                                    }
+                                }
+                            }
+                        }
+                    }
+                    break;
+                case 'i':
+                    if (OutputPropertiesFactory.S_KEY_INDENT_AMOUNT.equals(name)) {
+                        setIndentAmount(Integer.parseInt(val));
+                    } else if (OutputKeys.INDENT.equals(name)) {
+                        boolean b = "yes".equals(val) ? true : false;
+                        m_doIndent = b;
+                    }
+
+                    break;
+                case 'l':
+                    if (OutputPropertiesFactory.S_KEY_LINE_SEPARATOR.equals(name)) {
+                        m_lineSep = val.toCharArray();
+                        m_lineSepLen = m_lineSep.length;
+                    }
+
+                    break;
+                case 'm':
+                    if (OutputKeys.MEDIA_TYPE.equals(name)) {
+                        m_mediatype = val;
+                    }
+                    break;
+                case 'o':
+                    if (OutputKeys.OMIT_XML_DECLARATION.equals(name)) {
+                        boolean b = "yes".equals(val) ? true : false;
+                        this.m_shouldNotWriteXMLHeader = b;
+                    }
+                    break;
+                case 's':
+                    // if standalone was explicitly specified
+                    if (OutputKeys.STANDALONE.equals(name)) {
+                        if (defaultVal) {
+                            setStandaloneInternal(val);
+                        } else {
+                            m_standaloneWasSpecified = true;
+                            setStandaloneInternal(val);
+                        }
+                    }
+
+                    break;
+                case 'v':
+                    if (OutputKeys.VERSION.equals(name)) {
+                        m_version = val;
+                    }
+                    break;
+                default:
+                    break;
+
+            }
+            super.setProp(name, val, defaultVal);
+        }
+    }
+    /**
+     * Specifies an output format for this serializer. It the
+     * serializer has already been associated with an output format,
+     * it will switch to the new format. This method should not be
+     * called while the serializer is in the process of serializing
+     * a document.
+     *
+     * @param format The output format to use
+     */
+    public void setOutputFormat(Properties format)
+    {
+
+        boolean shouldFlush = m_shouldFlush;
+
+        if (format != null)
+        {
+            // Set the default values first,
+            // and the non-default values after that, 
+            // just in case there is some unexpected
+            // residual values left over from over-ridden default values
+            Enumeration propNames;
+            propNames = format.propertyNames();
+            while (propNames.hasMoreElements())
+            {
+                String key = (String) propNames.nextElement();
+                // Get the value, possibly a default value
+                String value = format.getProperty(key);
+                // Get the non-default value (if any).
+                String explicitValue = (String) format.get(key);
+                if (explicitValue == null && value != null) {
+                    // This is a default value
+                    this.setOutputPropertyDefault(key,value);
+                }
+                if (explicitValue != null) {
+                    // This is an explicit non-default value
+                    this.setOutputProperty(key,explicitValue);
+                }
+            }
+        }
+
+        // Access this only from the Hashtable level... we don't want to 
+        // get default properties.
+        String entitiesFileName =
+            (String) format.get(OutputPropertiesFactory.S_KEY_ENTITIES);
+
+        if (null != entitiesFileName)
+        {
+
+            String method =
+                (String) format.get(OutputKeys.METHOD);
+
+            m_charInfo = CharInfo.getCharInfo(entitiesFileName, method);
+        }
+
+
+
+
+        m_shouldFlush = shouldFlush;
+    }
+
+    /**
+     * Returns the output format for this serializer.
+     *
+     * @return The output format in use
+     */
+    public Properties getOutputFormat() {
+        Properties def = new Properties();
+        {
+            Set s = getOutputPropDefaultKeys();
+            Iterator i = s.iterator();
+            while (i.hasNext()) {
+                String key = (String) i.next();
+                String val = getOutputPropertyDefault(key);
+                def.put(key, val);
+            }
+        }
+
+        Properties props = new Properties(def);
+        {
+            Set s = getOutputPropKeys();
+            Iterator i = s.iterator();
+            while (i.hasNext()) {
+                String key = (String) i.next();
+                String val = getOutputPropertyNonDefault(key);
+                if (val != null)
+                    props.put(key, val);
+            }
+        }
+        return props;
+    }
+
+    /**
+     * Specifies a writer to which the document should be serialized.
+     * This method should not be called while the serializer is in
+     * the process of serializing a document.
+     *
+     * @param writer The output writer stream
+     */
+    public void setWriter(Writer writer)
+    {
+        setWriterInternal(writer, true);
+    }
+
+    private boolean m_writer_set_by_user;
+    private void setWriterInternal(Writer writer, boolean setByUser) {
+
+        m_writer_set_by_user = setByUser;
+        m_writer = writer;
+        // if we are tracing events we need to trace what
+        // characters are written to the output writer.
+        if (m_tracer != null) {
+            boolean noTracerYet = true;
+            Writer w2 = m_writer;
+            while (w2 instanceof WriterChain) {
+                if (w2 instanceof SerializerTraceWriter) {
+                    noTracerYet = false;
+                    break;
+                }
+                w2 = ((WriterChain)w2).getWriter();
+            }
+            if (noTracerYet)
+                m_writer = new SerializerTraceWriter(m_writer, m_tracer);
+        }
+    }
+
+    /**
+     * Set if the operating systems end-of-line line separator should
+     * be used when serializing.  If set false NL character 
+     * (decimal 10) is left alone, otherwise the new-line will be replaced on
+     * output with the systems line separator. For example on UNIX this is
+     * NL, while on Windows it is two characters, CR NL, where CR is the
+     * carriage-return (decimal 13).
+     *
+     * @param use_sytem_line_break True if an input NL is replaced with the 
+     * operating systems end-of-line separator.
+     * @return The previously set value of the serializer.
+     */
+    public boolean setLineSepUse(boolean use_sytem_line_break)
+    {
+        boolean oldValue = m_lineSepUse;
+        m_lineSepUse = use_sytem_line_break;
+        return oldValue;
+    }
+
+    /**
+     * Specifies an output stream to which the document should be
+     * serialized. This method should not be called while the
+     * serializer is in the process of serializing a document.
+     * <p>
+     * The encoding specified in the output properties is used, or
+     * if no encoding was specified, the default for the selected
+     * output method.
+     *
+     * @param output The output stream
+     */
+    public void setOutputStream(OutputStream output)
+    {
+        setOutputStreamInternal(output, true);
+    }
+
+    private void setOutputStreamInternal(OutputStream output, boolean setByUser)
+    {
+        m_outputStream = output;
+        String encoding = getOutputProperty(OutputKeys.ENCODING);
+        if (Encodings.DEFAULT_MIME_ENCODING.equalsIgnoreCase(encoding))
+        {
+            // We wrap the OutputStream with a writer, but
+            // not one set by the user
+            setWriterInternal(new WriterToUTF8Buffered(output), false);
+        } else if (
+            "WINDOWS-1250".equals(encoding)
+            || "US-ASCII".equals(encoding)
+            || "ASCII".equals(encoding))
+        {
+            setWriterInternal(new WriterToASCI(output), false);
+        } else if (encoding != null) {
+            Writer osw = null;
+            try
+            {
+                osw = Encodings.getWriter(output, encoding);
+            }
+            catch (UnsupportedEncodingException uee)
+            {
+                osw = null;
+            }
+
+
+            if (osw == null) {
+                System.out.println(
+                    "Warning: encoding \""
+                    + encoding
+                    + "\" not supported"
+                    + ", using "
+                    + Encodings.DEFAULT_MIME_ENCODING);
+
+                encoding = Encodings.DEFAULT_MIME_ENCODING;
+                setEncoding(encoding);
+                try {
+                    osw = Encodings.getWriter(output, encoding);
+                } catch (UnsupportedEncodingException e) {
+                    // We can't really get here, UTF-8 is always supported
+                    // This try-catch exists to make the compiler happy
+                    e.printStackTrace();
+                }
+            }
+            setWriterInternal(osw,false);
+        }
+        else {
+            // don't have any encoding, but we have an OutputStream
+            Writer osw = new OutputStreamWriter(output);
+            setWriterInternal(osw,false);
+        }
+    }
+
+    /**
+     * @see SerializationHandler#setEscaping(boolean)
+     */
+    public boolean setEscaping(boolean escape)
+    {
+        final boolean temp = m_escaping;
+        m_escaping = escape;
+        return temp;
+
+    }
+
+
+    /**
+     * Might print a newline character and the indentation amount
+     * of the given depth.
+     *
+     * @param depth the indentation depth (element nesting depth)
+     *
+     * @throws org.xml.sax.SAXException if an error occurs during writing.
+     */
+    protected void indent(int depth) throws IOException
+    {
+
+        if (m_startNewLine)
+            outputLineSep();
+        /* For m_indentAmount > 0 this extra test might be slower
+         * but Xalan's default value is 0, so this extra test
+         * will run faster in that situation.
+         */
+        if (m_indentAmount > 0)
+            printSpace(depth * m_indentAmount);
+
+    }
+
+    /**
+     * Indent at the current element nesting depth.
+     * @throws IOException
+     */
+    protected void indent() throws IOException
+    {
+        indent(m_elemContext.m_currentElemDepth);
+    }
+    /**
+     * Prints <var>n</var> spaces.
+     * @param n         Number of spaces to print.
+     *
+     * @throws org.xml.sax.SAXException if an error occurs when writing.
+     */
+    private void printSpace(int n) throws IOException
+    {
+        final java.io.Writer writer = m_writer;
+        for (int i = 0; i < n; i++)
+        {
+            writer.write(' ');
+        }
+
+    }
+
+    /**
+     * Report an attribute type declaration.
+     *
+     * <p>Only the effective (first) declaration for an attribute will
+     * be reported.  The type will be one of the strings "CDATA",
+     * "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY",
+     * "ENTITIES", or "NOTATION", or a parenthesized token group with
+     * the separator "|" and all whitespace removed.</p>
+     *
+     * @param eName The name of the associated element.
+     * @param aName The name of the attribute.
+     * @param type A string representing the attribute type.
+     * @param valueDefault A string representing the attribute default
+     *        ("#IMPLIED", "#REQUIRED", or "#FIXED") or null if
+     *        none of these applies.
+     * @param value A string representing the attribute's default value,
+     *        or null if there is none.
+     * @exception SAXException The application may raise an exception.
+     */
+    public void attributeDecl(
+        String eName,
+        String aName,
+        String type,
+        String valueDefault,
+        String value)
+        throws SAXException
+    {
+        // Do not inline external DTD
+        if (m_inExternalDTD)
+            return;
+        try
+        {
+            final java.io.Writer writer = m_writer;
+            DTDprolog();
+
+            writer.write("<!ATTLIST ");
+            writer.write(eName);
+            writer.write(' ');
+
+            writer.write(aName);
+            writer.write(' ');
+            writer.write(type);
+            if (valueDefault != null)
+            {
+                writer.write(' ');
+                writer.write(valueDefault);
+            }
+
+            //writer.write(" ");
+            //writer.write(value);
+            writer.write('>');
+            writer.write(m_lineSep, 0, m_lineSepLen);
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+    }
+
+    /**
+     * Get the character stream where the events will be serialized to.
+     *
+     * @return Reference to the result Writer, or null.
+     */
+    public Writer getWriter()
+    {
+        return m_writer;
+    }
+
+    /**
+     * Report a parsed external entity declaration.
+     *
+     * <p>Only the effective (first) declaration for each entity
+     * will be reported.</p>
+     *
+     * @param name The name of the entity.  If it is a parameter
+     *        entity, the name will begin with '%'.
+     * @param publicId The declared public identifier of the entity, or
+     *        null if none was declared.
+     * @param systemId The declared system identifier of the entity.
+     * @exception SAXException The application may raise an exception.
+     * @see #internalEntityDecl
+     * @see org.xml.sax.DTDHandler#unparsedEntityDecl
+     */
+    public void externalEntityDecl(
+        String name,
+        String publicId,
+        String systemId)
+        throws SAXException
+    {
+        try {
+            DTDprolog();
+
+            m_writer.write("<!ENTITY ");
+            m_writer.write(name);
+            if (publicId != null) {
+                m_writer.write(" PUBLIC \"");
+                m_writer.write(publicId);
+
+            }
+            else {
+                m_writer.write(" SYSTEM \"");
+                m_writer.write(systemId);
+            }
+            m_writer.write("\" >");
+            m_writer.write(m_lineSep, 0, m_lineSepLen);
+        } catch (IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+
+    }
+
+    /**
+     * Tell if this character can be written without escaping.
+     */
+    protected boolean escapingNotNeeded(char ch)
+    {
+        final boolean ret;
+        if (ch < 127)
+        {
+            // This is the old/fast code here, but is this 
+            // correct for all encodings?
+            if (ch >= CharInfo.S_SPACE || (CharInfo.S_LINEFEED == ch ||
+                                           CharInfo.S_CARRIAGERETURN == ch || CharInfo.S_HORIZONAL_TAB == ch))
+                ret= true;
+            else
+                ret = false;
+        }
+        else {
+            ret = m_encodingInfo.isInEncoding(ch);
+        }
+        return ret;
+    }
+
+    /**
+     * Once a surrogate has been detected, write out the pair of
+     * characters if it is in the encoding, or if there is no
+     * encoding, otherwise write out an entity reference
+     * of the value of the unicode code point of the character
+     * represented by the high/low surrogate pair.
+     * <p>
+     * An exception is thrown if there is no low surrogate in the pair,
+     * because the array ends unexpectely, or if the low char is there
+     * but its value is such that it is not a low surrogate.
+     *
+     * @param c the first (high) part of the surrogate, which
+     * must be confirmed before calling this method.
+     * @param ch Character array.
+     * @param i position Where the surrogate was detected.
+     * @param end The end index of the significant characters.
+     * @return 0 if the pair of characters was written out as-is,
+     * the unicode code point of the character represented by
+     * the surrogate pair if an entity reference with that value
+     * was written out. 
+     *
+     * @throws IOException
+     * @throws org.xml.sax.SAXException if invalid UTF-16 surrogate detected.
+     */
+    protected int writeUTF16Surrogate(char c, char ch[], int i, int end)
+        throws IOException
+    {
+        int codePoint = 0;
+        if (i + 1 >= end)
+        {
+            throw new IOException(
+                Utils.messages.createMessage(
+                    MsgKey.ER_INVALID_UTF16_SURROGATE,
+                    new Object[] { Integer.toHexString((int) c)}));
+        }
+
+        final char high = c;
+        final char low = ch[i+1];
+        if (!Encodings.isLowUTF16Surrogate(low)) {
+            throw new IOException(
+                Utils.messages.createMessage(
+                    MsgKey.ER_INVALID_UTF16_SURROGATE,
+                    new Object[] {
+                        Integer.toHexString((int) c)
+                        + " "
+                        + Integer.toHexString(low)}));
+        }
+
+        final java.io.Writer writer = m_writer;
+
+        // If we make it to here we have a valid high, low surrogate pair
+        if (m_encodingInfo.isInEncoding(c,low)) {
+            // If the character formed by the surrogate pair
+            // is in the encoding, so just write it out
+            writer.write(ch,i,2);
+        }
+        else {
+            // Don't know what to do with this char, it is
+            // not in the encoding and not a high char in
+            // a surrogate pair, so write out as an entity ref
+            final String encoding = getEncoding();
+            if (encoding != null) {
+                /* The output encoding is known,
+                 * so somthing is wrong.
+                 */
+                codePoint = Encodings.toCodePoint(high, low);
+                // not in the encoding, so write out a character reference
+                writer.write('&');
+                writer.write('#');
+                writer.write(Integer.toString(codePoint));
+                writer.write(';');
+            } else {
+                /* The output encoding is not known,
+                 * so just write it out as-is.
+                 */
+                writer.write(ch, i, 2);
+            }
+        }
+        // non-zero only if character reference was written out.
+        return codePoint;
+    }
+
+    /**
+     * Handle one of the default entities, return false if it
+     * is not a default entity.
+     *
+     * @param ch character to be escaped.
+     * @param i index into character array.
+     * @param chars non-null reference to character array.
+     * @param len length of chars.
+     * @param fromTextNode true if the characters being processed
+     * are from a text node, false if they are from an attribute value
+     * @param escLF true if the linefeed should be escaped.
+     *
+     * @return i+1 if the character was written, else i.
+     *
+     * @throws java.io.IOException
+     */
+    int accumDefaultEntity(
+        java.io.Writer writer,
+        char ch,
+        int i,
+        char[] chars,
+        int len,
+        boolean fromTextNode,
+        boolean escLF)
+        throws IOException
+    {
+
+        if (!escLF && CharInfo.S_LINEFEED == ch)
+        {
+            writer.write(m_lineSep, 0, m_lineSepLen);
+        }
+        else
+        {
+            // if this is text node character and a special one of those,
+            // or if this is a character from attribute value and a special one of those
+            if ((fromTextNode && m_charInfo.shouldMapTextChar(ch)) || (!fromTextNode && m_charInfo.shouldMapAttrChar(ch)))
+            {
+                String outputStringForChar = m_charInfo.getOutputStringForChar(ch);
+
+                if (null != outputStringForChar)
+                {
+                    writer.write(outputStringForChar);
+                }
+                else
+                    return i;
+            }
+            else
+                return i;
+        }
+
+        return i + 1;
+
+    }
+    /**
+     * Normalize the characters, but don't escape.
+     *
+     * @param ch The characters from the XML document.
+     * @param start The start position in the array.
+     * @param length The number of characters to read from the array.
+     * @param isCData true if a CDATA block should be built around the characters.
+     * @param useSystemLineSeparator true if the operating systems 
+     * end-of-line separator should be output rather than a new-line character.
+     *
+     * @throws IOException
+     * @throws org.xml.sax.SAXException
+     */
+    void writeNormalizedChars(
+        char ch[],
+        int start,
+        int length,
+        boolean isCData,
+        boolean useSystemLineSeparator)
+        throws IOException, org.xml.sax.SAXException
+    {
+        final java.io.Writer writer = m_writer;
+        int end = start + length;
+
+        for (int i = start; i < end; i++)
+        {
+            char c = ch[i];
+
+            if (CharInfo.S_LINEFEED == c && useSystemLineSeparator)
+            {
+                writer.write(m_lineSep, 0, m_lineSepLen);
+            }
+            else if (isCData && (!escapingNotNeeded(c)))
+            {
+                //                if (i != 0)
+                if (m_cdataTagOpen)
+                    closeCDATA();
+
+                // This needs to go into a function... 
+                if (Encodings.isHighUTF16Surrogate(c))
+                {
+                    writeUTF16Surrogate(c, ch, i, end);
+                    i++ ; // process two input characters
+                }
+                else
+                {
+                    writer.write("&#");
+
+                    String intStr = Integer.toString((int) c);
+
+                    writer.write(intStr);
+                    writer.write(';');
+                }
+
+                //                if ((i != 0) && (i < (end - 1)))
+                //                if (!m_cdataTagOpen && (i < (end - 1)))
+                //                {
+                //                    writer.write(CDATA_DELIMITER_OPEN);
+                //                    m_cdataTagOpen = true;
+                //                }
+            }
+            else if (
+                isCData
+                && ((i < (end - 2))
+                    && (']' == c)
+                    && (']' == ch[i + 1])
+                    && ('>' == ch[i + 2])))
+            {
+                writer.write(CDATA_CONTINUE);
+
+                i += 2;
+            }
+            else
+            {
+                if (escapingNotNeeded(c))
+                {
+                    if (isCData && !m_cdataTagOpen)
+                    {
+                        writer.write(CDATA_DELIMITER_OPEN);
+                        m_cdataTagOpen = true;
+                    }
+                    writer.write(c);
+                }
+
+                // This needs to go into a function... 
+                else if (Encodings.isHighUTF16Surrogate(c))
+                {
+                    if (m_cdataTagOpen)
+                        closeCDATA();
+                    writeUTF16Surrogate(c, ch, i, end);
+                    i++; // process two input characters
+                }
+                else
+                {
+                    if (m_cdataTagOpen)
+                        closeCDATA();
+                    writer.write("&#");
+
+                    String intStr = Integer.toString((int) c);
+
+                    writer.write(intStr);
+                    writer.write(';');
+                }
+            }
+        }
+
+    }
+
+    /**
+     * Ends an un-escaping section.
+     *
+     * @see #startNonEscaping
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public void endNonEscaping() throws org.xml.sax.SAXException
+    {
+        m_disableOutputEscapingStates.pop();
+    }
+
+    /**
+     * Starts an un-escaping section. All characters printed within an un-
+     * escaping section are printed as is, without escaping special characters
+     * into entity references. Only XML and HTML serializers need to support
+     * this method.
+     * <p> The contents of the un-escaping section will be delivered through the
+     * regular <tt>characters</tt> event.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public void startNonEscaping() throws org.xml.sax.SAXException
+    {
+        m_disableOutputEscapingStates.push(true);
+    }
+
+    /**
+     * Receive notification of cdata.
+     *
+     * <p>The Parser will call this method to report each chunk of
+     * character data.  SAX parsers may return all contiguous character
+     * data in a single chunk, or they may split it into several
+     * chunks; however, all of the characters in any single event
+     * must come from the same external entity, so that the Locator
+     * provides useful information.</p>
+     *
+     * <p>The application must not attempt to read from the array
+     * outside of the specified range.</p>
+     *
+     * <p>Note that some parsers will report whitespace using the
+     * ignorableWhitespace() method rather than this one (validating
+     * parsers must do so).</p>
+     *
+     * @param ch The characters from the XML document.
+     * @param start The start position in the array.
+     * @param length The number of characters to read from the array.
+     * @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see #ignorableWhitespace
+     * @see org.xml.sax.Locator
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    protected void cdata(char ch[], int start, final int length)
+        throws org.xml.sax.SAXException
+    {
+
+        try
+        {
+            final int old_start = start;
+            if (m_elemContext.m_startTagOpen)
+            {
+                closeStartTag();
+                m_elemContext.m_startTagOpen = false;
+            }
+            m_ispreserve = true;
+
+            if (shouldIndent())
+                indent();
+
+            boolean writeCDataBrackets =
+                (((length >= 1) && escapingNotNeeded(ch[start])));
+
+            /* Write out the CDATA opening delimiter only if
+             * we are supposed to, and if we are not already in
+             * the middle of a CDATA section
+             */
+            if (writeCDataBrackets && !m_cdataTagOpen)
+            {
+                m_writer.write(CDATA_DELIMITER_OPEN);
+                m_cdataTagOpen = true;
+            }
+
+            // writer.write(ch, start, length);
+            if (isEscapingDisabled())
+            {
+                charactersRaw(ch, start, length);
+            }
+            else
+                writeNormalizedChars(ch, start, length, true, m_lineSepUse);
+
+            /* used to always write out CDATA closing delimiter here,
+             * but now we delay, so that we can merge CDATA sections on output.
+             * need to write closing delimiter later
+             */
+            if (writeCDataBrackets)
+            {
+                /* if the CDATA section ends with ] don't leave it open
+                 * as there is a chance that an adjacent CDATA sections
+                 * starts with ]>.
+                 * We don't want to merge ]] with > , or ] with ]>
+                 */
+                if (ch[start + length - 1] == ']')
+                    closeCDATA();
+            }
+
+            // time to fire off CDATA event
+            if (m_tracer != null)
+                super.fireCDATAEvent(ch, old_start, length);
+        }
+        catch (IOException ioe)
+        {
+            throw new org.xml.sax.SAXException(
+                Utils.messages.createMessage(
+                    MsgKey.ER_OIERROR,
+                    null),
+                ioe);
+            //"IO error", ioe);
+        }
+    }
+
+    /**
+     * Tell if the character escaping should be disabled for the current state.
+     *
+     * @return true if the character escaping should be disabled.
+     */
+    private boolean isEscapingDisabled()
+    {
+        return m_disableOutputEscapingStates.peekOrFalse();
+    }
+
+    /**
+     * If available, when the disable-output-escaping attribute is used,
+     * output raw text without escaping.
+     *
+     * @param ch The characters from the XML document.
+     * @param start The start position in the array.
+     * @param length The number of characters to read from the array.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    protected void charactersRaw(char ch[], int start, int length)
+        throws org.xml.sax.SAXException
+    {
+
+        if (m_inEntityRef)
+            return;
+        try
+        {
+            if (m_elemContext.m_startTagOpen)
+            {
+                closeStartTag();
+                m_elemContext.m_startTagOpen = false;
+            }
+
+            m_ispreserve = true;
+
+            m_writer.write(ch, start, length);
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+
+    }
+
+    /**
+     * Receive notification of character data.
+     *
+     * <p>The Parser will call this method to report each chunk of
+     * character data.  SAX parsers may return all contiguous character
+     * data in a single chunk, or they may split it into several
+     * chunks; however, all of the characters in any single event
+     * must come from the same external entity, so that the Locator
+     * provides useful information.</p>
+     *
+     * <p>The application must not attempt to read from the array
+     * outside of the specified range.</p>
+     *
+     * <p>Note that some parsers will report whitespace using the
+     * ignorableWhitespace() method rather than this one (validating
+     * parsers must do so).</p>
+     *
+     * @param chars The characters from the XML document.
+     * @param start The start position in the array.
+     * @param length The number of characters to read from the array.
+     * @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see #ignorableWhitespace
+     * @see org.xml.sax.Locator
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public void characters(final char chars[], final int start, final int length)
+        throws org.xml.sax.SAXException
+    {
+        // It does not make sense to continue with rest of the method if the number of 
+        // characters to read from array is 0.
+        // Section 7.6.1 of XSLT 1.0 (http://www.w3.org/TR/xslt#value-of) suggest no text node
+        // is created if string is empty.	
+        if (length == 0 || (m_inEntityRef && !m_expandDTDEntities))
+            return;
+
+        m_docIsEmpty = false;
+
+        if (m_elemContext.m_startTagOpen)
+        {
+            closeStartTag();
+            m_elemContext.m_startTagOpen = false;
+        }
+        else if (m_needToCallStartDocument)
+        {
+            startDocumentInternal();
+        }
+
+        if (m_cdataStartCalled || m_elemContext.m_isCdataSection)
+        {
+            /* either due to startCDATA() being called or due to
+             * cdata-section-elements atribute, we need this as cdata
+             */
+            cdata(chars, start, length);
+
+            return;
+        }
+
+        if (m_cdataTagOpen)
+            closeCDATA();
+
+        if (m_disableOutputEscapingStates.peekOrFalse() || (!m_escaping))
+        {
+            charactersRaw(chars, start, length);
+
+            // time to fire off characters generation event
+            if (m_tracer != null)
+                super.fireCharEvent(chars, start, length);
+
+            return;
+        }
+
+        if (m_elemContext.m_startTagOpen)
+        {
+            closeStartTag();
+            m_elemContext.m_startTagOpen = false;
+        }
+
+
+        try
+        {
+            int i;
+            int startClean;
+
+            // skip any leading whitspace 
+            // don't go off the end and use a hand inlined version
+            // of isWhitespace(ch)
+            final int end = start + length;
+            int lastDirtyCharProcessed = start - 1; // last non-clean character that was processed
+            // that was processed
+            final Writer writer = m_writer;
+            boolean isAllWhitespace = true;
+
+            // process any leading whitspace
+            i = start;
+            while (i < end && isAllWhitespace) {
+                char ch1 = chars[i];
+
+                if (m_charInfo.shouldMapTextChar(ch1)) {
+                    // The character is supposed to be replaced by a String
+                    // so write out the clean whitespace characters accumulated
+                    // so far
+                    // then the String.
+                    writeOutCleanChars(chars, i, lastDirtyCharProcessed);
+                    String outputStringForChar = m_charInfo
+                        .getOutputStringForChar(ch1);
+                    writer.write(outputStringForChar);
+                    // We can't say that everything we are writing out is
+                    // all whitespace, we just wrote out a String.
+                    isAllWhitespace = false;
+                    lastDirtyCharProcessed = i; // mark the last non-clean
+                    // character processed
+                    i++;
+                } else {
+                    // The character is clean, but is it a whitespace ?
+                    switch (ch1) {
+                        // TODO: Any other whitespace to consider?
+                        case CharInfo.S_SPACE:
+                            // Just accumulate the clean whitespace
+                            i++;
+                            break;
+                        case CharInfo.S_LINEFEED:
+                            lastDirtyCharProcessed = processLineFeed(chars, i,
+                                                                     lastDirtyCharProcessed, writer);
+                            i++;
+                            break;
+                        case CharInfo.S_CARRIAGERETURN:
+                            writeOutCleanChars(chars, i, lastDirtyCharProcessed);
+                            writer.write("&#13;");
+                            lastDirtyCharProcessed = i;
+                            i++;
+                            break;
+                        case CharInfo.S_HORIZONAL_TAB:
+                            // Just accumulate the clean whitespace
+                            i++;
+                            break;
+                        default:
+                            // The character was clean, but not a whitespace
+                            // so break the loop to continue with this character
+                            // (we don't increment index i !!)
+                            isAllWhitespace = false;
+                            break;
+                    }
+                }
+            }
+
+            /* If there is some non-whitespace, mark that we may need
+             * to preserve this. This is only important if we have indentation on.
+             */
+            if (i < end || !isAllWhitespace)
+                m_ispreserve = true;
+
+
+            for (; i < end; i++)
+            {
+                char ch = chars[i];
+
+                if (m_charInfo.shouldMapTextChar(ch)) {
+                    // The character is supposed to be replaced by a String
+                    // e.g.   '&'  -->  "&amp;"
+                    // e.g.   '<'  -->  "&lt;"
+                    writeOutCleanChars(chars, i, lastDirtyCharProcessed);
+                    String outputStringForChar = m_charInfo.getOutputStringForChar(ch);
+                    writer.write(outputStringForChar);
+                    lastDirtyCharProcessed = i;
+                }
+                else {
+                    if (ch <= 0x1F) {
+                        // Range 0x00 through 0x1F inclusive
+                        //
+                        // This covers the non-whitespace control characters
+                        // in the range 0x1 to 0x1F inclusive.
+                        // It also covers the whitespace control characters in the same way:
+                        // 0x9   TAB
+                        // 0xA   NEW LINE
+                        // 0xD   CARRIAGE RETURN
+                        //
+                        // We also cover 0x0 ... It isn't valid
+                        // but we will output "&#0;" 
+
+                        // The default will handle this just fine, but this
+                        // is a little performance boost to handle the more
+                        // common TAB, NEW-LINE, CARRIAGE-RETURN
+                        switch (ch) {
+
+                            case CharInfo.S_HORIZONAL_TAB:
+                                // Leave whitespace TAB as a real character
+                                break;
+                            case CharInfo.S_LINEFEED:
+                                lastDirtyCharProcessed = processLineFeed(chars, i, lastDirtyCharProcessed, writer);
+                                break;
+                            case CharInfo.S_CARRIAGERETURN:
+                                writeOutCleanChars(chars, i, lastDirtyCharProcessed);
+                                writer.write("&#13;");
+                                lastDirtyCharProcessed = i;
+                                // Leave whitespace carriage return as a real character
+                                break;
+                            default:
+                                writeOutCleanChars(chars, i, lastDirtyCharProcessed);
+                                writer.write("&#");
+                                writer.write(Integer.toString(ch));
+                                writer.write(';');
+                                lastDirtyCharProcessed = i;
+                                break;
+
+                        }
+                    }
+                    else if (ch < 0x7F) {
+                        // Range 0x20 through 0x7E inclusive
+                        // Normal ASCII chars, do nothing, just add it to
+                        // the clean characters
+
+                    }
+                    else if (ch <= 0x9F){
+                        // Range 0x7F through 0x9F inclusive
+                        // More control characters, including NEL (0x85)
+                        writeOutCleanChars(chars, i, lastDirtyCharProcessed);
+                        writer.write("&#");
+                        writer.write(Integer.toString(ch));
+                        writer.write(';');
+                        lastDirtyCharProcessed = i;
+                    }
+                    else if (ch == CharInfo.S_LINE_SEPARATOR) {
+                        // LINE SEPARATOR
+                        writeOutCleanChars(chars, i, lastDirtyCharProcessed);
+                        writer.write("&#8232;");
+                        lastDirtyCharProcessed = i;
+                    }
+                    else if (m_encodingInfo.isInEncoding(ch)) {
+                        // If the character is in the encoding, and
+                        // not in the normal ASCII range, we also
+                        // just leave it get added on to the clean characters
+
+                    } else if (Encodings.isHighUTF16Surrogate(ch) &&
+                               i < end - 1 &&
+                               Encodings.isLowUTF16Surrogate(chars[i + 1])) {
+
+                        // So, this is a (valid) surrogate pair
+                        if (!m_encodingInfo.isInEncoding(ch, chars[i + 1])) {
+                            int codepoint = Encodings.toCodePoint(ch, chars[i + 1]);
+                            writeOutCleanChars(chars, i, lastDirtyCharProcessed);
+                            writer.write("&#");
+                            writer.write(Integer.toString(codepoint));
+                            writer.write(';');
+                            lastDirtyCharProcessed = i + 1;
+                        }
+                        i++; // skip the low surrogate, too
+                    } else {
+                        // This is a fallback plan, we get here if the
+                        // encoding doesn't contain ch and it's not part
+                        // of a surrogate pair
+                        // The right thing is to write out an entity
+                        writeOutCleanChars(chars, i, lastDirtyCharProcessed);
+                        writer.write("&#");
+                        writer.write(Integer.toString(ch));
+                        writer.write(';');
+                        lastDirtyCharProcessed = i;
+                    }
+                }
+            }
+
+            // we've reached the end. Any clean characters at the
+            // end of the array than need to be written out?
+            startClean = lastDirtyCharProcessed + 1;
+            if (i > startClean)
+            {
+                int lengthClean = i - startClean;
+                m_writer.write(chars, startClean, lengthClean);
+            }
+
+            // For indentation purposes, mark that we've just writen text out
+            m_isprevtext = true;
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+
+        // time to fire off characters generation event
+        if (m_tracer != null)
+            super.fireCharEvent(chars, start, length);
+    }
+
+    private int processLineFeed(final char[] chars, int i, int lastProcessed, final Writer writer) throws IOException {
+        if (!m_lineSepUse
+            || (m_lineSepLen ==1 && m_lineSep[0] == CharInfo.S_LINEFEED)){
+            // We are leaving the new-line alone, and it is just
+            // being added to the 'clean' characters,
+            // so the last dirty character processed remains unchanged
+        }
+        else {
+            writeOutCleanChars(chars, i, lastProcessed);
+            writer.write(m_lineSep, 0, m_lineSepLen);
+            lastProcessed = i;
+        }
+        return lastProcessed;
+    }
+
+    private void writeOutCleanChars(final char[] chars, int i, int lastProcessed) throws IOException {
+        int startClean;
+        startClean = lastProcessed + 1;
+        if (startClean < i)
+        {
+            int lengthClean = i - startClean;
+            m_writer.write(chars, startClean, lengthClean);
+        }
+    }
+    /**
+     * This method checks if a given character is between C0 or C1 range
+     * of Control characters.
+     * This method is added to support Control Characters for XML 1.1
+     * If a given character is TAB (0x09), LF (0x0A) or CR (0x0D), this method
+     * return false. Since they are whitespace characters, no special processing is needed.
+     *
+     * @param ch
+     * @return boolean
+     */
+    private static boolean isCharacterInC0orC1Range(char ch)
+    {
+        if(ch == 0x09 || ch == 0x0A || ch == 0x0D)
+            return false;
+        else
+            return (ch >= 0x7F && ch <= 0x9F)|| (ch >= 0x01 && ch <= 0x1F);
+    }
+    /**
+     * This method checks if a given character either NEL (0x85) or LSEP (0x2028)
+     * These are new end of line charcters added in XML 1.1.  These characters must be
+     * written as Numeric Character References (NCR) in XML 1.1 output document.
+     *
+     * @param ch
+     * @return boolean
+     */
+    private static boolean isNELorLSEPCharacter(char ch)
+    {
+        return (ch == 0x85 || ch == 0x2028);
+    }
+    /**
+     * Process a dirty character and any preeceding clean characters
+     * that were not yet processed.
+     * @param chars array of characters being processed
+     * @param end one (1) beyond the last character 
+     * in chars to be processed
+     * @param i the index of the dirty character
+     * @param ch the character in chars[i]
+     * @param lastDirty the last dirty character previous to i
+     * @param fromTextNode true if the characters being processed are
+     * from a text node, false if they are from an attribute value.
+     * @return the index of the last character processed
+     */
+    private int processDirty(
+        char[] chars,
+        int end,
+        int i,
+        char ch,
+        int lastDirty,
+        boolean fromTextNode) throws IOException
+    {
+        int startClean = lastDirty + 1;
+        // if we have some clean characters accumulated
+        // process them before the dirty one.                   
+        if (i > startClean)
+        {
+            int lengthClean = i - startClean;
+            m_writer.write(chars, startClean, lengthClean);
+        }
+
+        // process the "dirty" character
+        if (CharInfo.S_LINEFEED == ch && fromTextNode)
+        {
+            m_writer.write(m_lineSep, 0, m_lineSepLen);
+        }
+        else
+        {
+            startClean =
+                accumDefaultEscape(
+                    m_writer,
+                    (char)ch,
+                    i,
+                    chars,
+                    end,
+                    fromTextNode,
+                    false);
+            i = startClean - 1;
+        }
+        // Return the index of the last character that we just processed 
+        // which is a dirty character.
+        return i;
+    }
+
+    /**
+     * Receive notification of character data.
+     *
+     * @param s The string of characters to process.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public void characters(String s) throws org.xml.sax.SAXException
+    {
+        if (m_inEntityRef && !m_expandDTDEntities)
+            return;
+        final int length = s.length();
+        if (length > m_charsBuff.length)
+        {
+            m_charsBuff = new char[length * 2 + 1];
+        }
+        s.getChars(0, length, m_charsBuff, 0);
+        characters(m_charsBuff, 0, length);
+    }
+
+    /**
+     * Escape and writer.write a character.
+     *
+     * @param ch character to be escaped.
+     * @param i index into character array.
+     * @param chars non-null reference to character array.
+     * @param len length of chars.
+     * @param fromTextNode true if the characters being processed are
+     * from a text node, false if the characters being processed are from
+     * an attribute value.
+     * @param escLF true if the linefeed should be escaped.
+     *
+     * @return i+1 if a character was written, i+2 if two characters
+     * were written out, else return i.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    private int accumDefaultEscape(
+        Writer writer,
+        char ch,
+        int i,
+        char[] chars,
+        int len,
+        boolean fromTextNode,
+        boolean escLF)
+        throws IOException
+    {
+
+        int pos = accumDefaultEntity(writer, ch, i, chars, len, fromTextNode, escLF);
+
+        if (i == pos)
+        {
+            if (Encodings.isHighUTF16Surrogate(ch))
+            {
+
+                // Should be the UTF-16 low surrogate of the hig/low pair.
+                char next;
+                // Unicode code point formed from the high/low pair.
+                int codePoint = 0;
+
+                if (i + 1 >= len)
+                {
+                    throw new IOException(
+                        Utils.messages.createMessage(
+                            MsgKey.ER_INVALID_UTF16_SURROGATE,
+                            new Object[] { Integer.toHexString(ch)}));
+                    //"Invalid UTF-16 surrogate detected: "
+
+                    //+Integer.toHexString(ch)+ " ?");
+                }
+                else
+                {
+                    next = chars[++i];
+
+                    if (!(Encodings.isLowUTF16Surrogate(next)))
+                        throw new IOException(
+                            Utils.messages.createMessage(
+                                MsgKey
+                                    .ER_INVALID_UTF16_SURROGATE,
+                                new Object[] {
+                                    Integer.toHexString(ch)
+                                    + " "
+                                    + Integer.toHexString(next)}));
+                    //"Invalid UTF-16 surrogate detected: "
+
+                    //+Integer.toHexString(ch)+" "+Integer.toHexString(next));
+                    codePoint = Encodings.toCodePoint(ch,next);
+                }
+
+                writer.write("&#");
+                writer.write(Integer.toString(codePoint));
+                writer.write(';');
+                pos += 2; // count the two characters that went into writing out this entity
+            }
+            else
+            {
+                /*  This if check is added to support control characters in XML 1.1.
+                 *  If a character is a Control Character within C0 and C1 range, it is desirable
+                 *  to write it out as Numeric Character Reference(NCR) regardless of XML Version
+                 *  being used for output document.
+                 */
+                if (isCharacterInC0orC1Range(ch) || isNELorLSEPCharacter(ch))
+                {
+                    writer.write("&#");
+                    writer.write(Integer.toString(ch));
+                    writer.write(';');
+                }
+                else if ((!escapingNotNeeded(ch) ||
+                          (  (fromTextNode && m_charInfo.shouldMapTextChar(ch))
+                             || (!fromTextNode && m_charInfo.shouldMapAttrChar(ch))))
+                         && m_elemContext.m_currentElemDepth > 0)
+                {
+                    writer.write("&#");
+                    writer.write(Integer.toString(ch));
+                    writer.write(';');
+                }
+                else
+                {
+                    writer.write(ch);
+                }
+                pos++;  // count the single character that was processed
+            }
+
+        }
+        return pos;
+    }
+
+    /**
+     * Receive notification of the beginning of an element, although this is a
+     * SAX method additional namespace or attribute information can occur before
+     * or after this call, that is associated with this element.
+     *
+     *
+     * @param namespaceURI The Namespace URI, or the empty string if the
+     *        element has no Namespace URI or if Namespace
+     *        processing is not being performed.
+     * @param localName The local name (without prefix), or the
+     *        empty string if Namespace processing is not being
+     *        performed.
+     * @param name The element type name.
+     * @param atts The attributes attached to the element, if any.
+     * @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#startElement
+     * @see org.xml.sax.ContentHandler#endElement
+     * @see org.xml.sax.AttributeList
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public void startElement(
+        String namespaceURI,
+        String localName,
+        String name,
+        Attributes atts)
+        throws org.xml.sax.SAXException
+    {
+        if (m_inEntityRef)
+            return;
+
+        if (m_needToCallStartDocument)
+        {
+            startDocumentInternal();
+            m_needToCallStartDocument = false;
+            m_docIsEmpty = false;
+        }
+        else if (m_cdataTagOpen)
+            closeCDATA();
+        try
+        {
+            if (m_needToOutputDocTypeDecl) {
+                if(null != getDoctypeSystem()) {
+                    outputDocTypeDecl(name, true);
+                }
+                m_needToOutputDocTypeDecl = false;
+            }
+
+            /* before we over-write the current elementLocalName etc.
+             * lets close out the old one (if we still need to)
+             */
+            if (m_elemContext.m_startTagOpen)
+            {
+                closeStartTag();
+                m_elemContext.m_startTagOpen = false;
+            }
+
+            if (namespaceURI != null)
+                ensurePrefixIsDeclared(namespaceURI, name);
+
+            m_ispreserve = false;
+
+            if (shouldIndent() && m_startNewLine)
+            {
+                indent();
+            }
+
+            m_startNewLine = true;
+
+            final java.io.Writer writer = m_writer;
+            writer.write('<');
+            writer.write(name);
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+
+        // process the attributes now, because after this SAX call they might be gone
+        if (atts != null)
+            addAttributes(atts);
+
+        m_elemContext = m_elemContext.push(namespaceURI,localName,name);
+        m_isprevtext = false;
+
+        if (m_tracer != null)
+            firePseudoAttributes();
+    }
+
+    /**
+     * Receive notification of the beginning of an element, additional
+     * namespace or attribute information can occur before or after this call,
+     * that is associated with this element.
+     *
+     *
+     * @param elementNamespaceURI The Namespace URI, or the empty string if the
+     *        element has no Namespace URI or if Namespace
+     *        processing is not being performed.
+     * @param elementLocalName The local name (without prefix), or the
+     *        empty string if Namespace processing is not being
+     *        performed.
+     * @param elementName The element type name.
+     * @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#startElement
+     * @see org.xml.sax.ContentHandler#endElement
+     * @see org.xml.sax.AttributeList
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public void startElement(
+        String elementNamespaceURI,
+        String elementLocalName,
+        String elementName)
+        throws SAXException
+    {
+        startElement(elementNamespaceURI, elementLocalName, elementName, null);
+    }
+
+    public void startElement(String elementName) throws SAXException
+    {
+        startElement(null, null, elementName, null);
+    }
+
+    /**
+     * Output the doc type declaration.
+     *
+     * @param name non-null reference to document type name.
+     * NEEDSDOC @param closeDecl
+     *
+     * @throws java.io.IOException
+     */
+    void outputDocTypeDecl(String name, boolean closeDecl) throws SAXException
+    {
+        if (m_cdataTagOpen)
+            closeCDATA();
+        try
+        {
+            final java.io.Writer writer = m_writer;
+            writer.write("<!DOCTYPE ");
+            writer.write(name);
+
+            String doctypePublic = getDoctypePublic();
+            if (null != doctypePublic)
+            {
+                writer.write(" PUBLIC \"");
+                writer.write(doctypePublic);
+                writer.write('\"');
+            }
+
+            String doctypeSystem = getDoctypeSystem();
+            if (null != doctypeSystem)
+            {
+                if (null == doctypePublic)
+                    writer.write(" SYSTEM \"");
+                else
+                    writer.write(" \"");
+
+                writer.write(doctypeSystem);
+
+                if (closeDecl)
+                {
+                    writer.write("\">");
+                    writer.write(m_lineSep, 0, m_lineSepLen);
+                    closeDecl = false; // done closing
+                }
+                else
+                    writer.write('\"');
+            }
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+    }
+
+    /**
+     * Process the attributes, which means to write out the currently
+     * collected attributes to the writer. The attributes are not
+     * cleared by this method
+     *
+     * @param writer the writer to write processed attributes to.
+     * @param nAttrs the number of attributes in m_attributes 
+     * to be processed
+     *
+     * @throws java.io.IOException
+     * @throws org.xml.sax.SAXException
+     */
+    public void processAttributes(java.io.Writer writer, int nAttrs) throws IOException, SAXException
+    {
+        /* real SAX attributes are not passed in, so process the
+         * attributes that were collected after the startElement call.
+         * _attribVector is a "cheap" list for Stream serializer output
+         * accumulated over a series of calls to attribute(name,value)
+         */
+
+        String encoding = getEncoding();
+        for (int i = 0; i < nAttrs; i++)
+        {
+            // elementAt is JDK 1.1.8
+            final String name = m_attributes.getQName(i);
+            final String value = m_attributes.getValue(i);
+            writer.write(' ');
+            writer.write(name);
+            writer.write("=\"");
+            writeAttrString(writer, value, encoding);
+            writer.write('\"');
+        }
+    }
+
+    /**
+     * Returns the specified <var>string</var> after substituting <VAR>specials</VAR>,
+     * and UTF-16 surrogates for chracter references <CODE>&amp;#xnn</CODE>.
+     *
+     * @param   string      String to convert to XML format.
+     * @param   encoding    CURRENTLY NOT IMPLEMENTED.
+     *
+     * @throws java.io.IOException
+     */
+    public void writeAttrString(
+        Writer writer,
+        String string,
+        String encoding)
+        throws IOException
+    {
+        final int len = string.length();
+        if (len > m_attrBuff.length)
+        {
+            m_attrBuff = new char[len*2 + 1];
+        }
+        string.getChars(0,len, m_attrBuff, 0);
+        final char[] stringChars = m_attrBuff;
+
+        for (int i = 0; i < len; i++)
+        {
+            char ch = stringChars[i];
+
+            if (m_charInfo.shouldMapAttrChar(ch)) {
+                // The character is supposed to be replaced by a String
+                // e.g.   '&'  -->  "&amp;"
+                // e.g.   '<'  -->  "&lt;"
+                accumDefaultEscape(writer, ch, i, stringChars, len, false, true);
+            }
+            else {
+                if (0x0 <= ch && ch <= 0x1F) {
+                    // Range 0x00 through 0x1F inclusive
+                    // This covers the non-whitespace control characters
+                    // in the range 0x1 to 0x1F inclusive.
+                    // It also covers the whitespace control characters in the same way:
+                    // 0x9   TAB
+                    // 0xA   NEW LINE
+                    // 0xD   CARRIAGE RETURN
+                    //
+                    // We also cover 0x0 ... It isn't valid
+                    // but we will output "&#0;" 
+
+                    // The default will handle this just fine, but this
+                    // is a little performance boost to handle the more
+                    // common TAB, NEW-LINE, CARRIAGE-RETURN
+                    switch (ch) {
+
+                        case CharInfo.S_HORIZONAL_TAB:
+                            writer.write("&#9;");
+                            break;
+                        case CharInfo.S_LINEFEED:
+                            writer.write("&#10;");
+                            break;
+                        case CharInfo.S_CARRIAGERETURN:
+                            writer.write("&#13;");
+                            break;
+                        default:
+                            writer.write("&#");
+                            writer.write(Integer.toString(ch));
+                            writer.write(';');
+                            break;
+
+                    }
+                }
+                else if (ch < 0x7F) {
+                    // Range 0x20 through 0x7E inclusive
+                    // Normal ASCII chars
+                    writer.write(ch);
+                }
+                else if (ch <= 0x9F){
+                    // Range 0x7F through 0x9F inclusive
+                    // More control characters
+                    writer.write("&#");
+                    writer.write(Integer.toString(ch));
+                    writer.write(';');
+                }
+                else if (ch == CharInfo.S_LINE_SEPARATOR) {
+                    // LINE SEPARATOR
+                    writer.write("&#8232;");
+                }
+                else if (m_encodingInfo.isInEncoding(ch)) {
+                    // If the character is in the encoding, and
+                    // not in the normal ASCII range, we also
+                    // just write it out
+                    writer.write(ch);
+                }
+                else if (Encodings.isHighUTF16Surrogate(ch)) {
+                    writeUTF16Surrogate(ch, stringChars, i, len);
+                    i++; // process two input characters
+                }
+                else {
+                    // This is a fallback plan, we should never get here
+                    // but if the character wasn't previously handled
+                    // (i.e. isn't in the encoding, etc.) then what
+                    // should we do?  We choose to write out a character ref
+                    writer.write("&#");
+                    writer.write(Integer.toString(ch));
+                    writer.write(';');
+                }
+
+            }
+        }
+    }
+
+    /**
+     * Receive notification of the end of an element.
+     *
+     *
+     * @param namespaceURI The Namespace URI, or the empty string if the
+     *        element has no Namespace URI or if Namespace
+     *        processing is not being performed.
+     * @param localName The local name (without prefix), or the
+     *        empty string if Namespace processing is not being
+     *        performed.
+     * @param name The element type name
+     * @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public void endElement(String namespaceURI, String localName, String name)
+        throws org.xml.sax.SAXException
+    {
+        if (m_inEntityRef)
+            return;
+
+        // namespaces declared at the current depth are no longer valid
+        // so get rid of them    
+        m_prefixMap.popNamespaces(m_elemContext.m_currentElemDepth, null);
+
+        try
+        {
+            final java.io.Writer writer = m_writer;
+            if (m_elemContext.m_startTagOpen)
+            {
+                if (m_tracer != null)
+                    super.fireStartElem(m_elemContext.m_elementName);
+                int nAttrs = m_attributes.getLength();
+                if (nAttrs > 0)
+                {
+                    processAttributes(m_writer, nAttrs);
+                    // clear attributes object for re-use with next element
+                    m_attributes.clear();
+                }
+                if (m_spaceBeforeClose)
+                    writer.write(" />");
+                else
+                    writer.write("/>");
+                /* don't need to pop cdataSectionState because
+                 * this element ended so quickly that we didn't get
+                 * to push the state.
+                 */
+
+            }
+            else
+            {
+                if (m_cdataTagOpen)
+                    closeCDATA();
+
+                if (shouldIndent())
+                    indent(m_elemContext.m_currentElemDepth - 1);
+                writer.write('<');
+                writer.write('/');
+                writer.write(name);
+                writer.write('>');
+            }
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+
+        if (!m_elemContext.m_startTagOpen && m_doIndent)
+        {
+            m_ispreserve = m_preserves.isEmpty() ? false : m_preserves.pop();
+        }
+
+        m_isprevtext = false;
+
+        // fire off the end element event
+        if (m_tracer != null)
+            super.fireEndElem(name);
+        m_elemContext = m_elemContext.m_prev;
+    }
+
+    /**
+     * Receive notification of the end of an element.
+     * @param name The element type name
+     * @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *     wrapping another exception.
+     */
+    public void endElement(String name) throws org.xml.sax.SAXException
+    {
+        endElement(null, null, name);
+    }
+
+    /**
+     * Begin the scope of a prefix-URI Namespace mapping
+     * just before another element is about to start.
+     * This call will close any open tags so that the prefix mapping
+     * will not apply to the current element, but the up comming child.
+     *
+     * @see org.xml.sax.ContentHandler#startPrefixMapping
+     *
+     * @param prefix The Namespace prefix being declared.
+     * @param uri The Namespace URI the prefix is mapped to.
+     *
+     * @throws org.xml.sax.SAXException The client may throw
+     *            an exception during processing.
+     *
+     */
+    public void startPrefixMapping(String prefix, String uri)
+        throws org.xml.sax.SAXException
+    {
+        // the "true" causes the flush of any open tags
+        startPrefixMapping(prefix, uri, true);
+    }
+
+    /**
+     * Handle a prefix/uri mapping, which is associated with a startElement()
+     * that is soon to follow. Need to close any open start tag to make
+     * sure than any name space attributes due to this event are associated wih
+     * the up comming element, not the current one.
+     * @see ExtendedContentHandler#startPrefixMapping
+     *
+     * @param prefix The Namespace prefix being declared.
+     * @param uri The Namespace URI the prefix is mapped to.
+     * @param shouldFlush true if any open tags need to be closed first, this
+     * will impact which element the mapping applies to (open parent, or its up
+     * comming child)
+     * @return returns true if the call made a change to the current 
+     * namespace information, false if it did not change anything, e.g. if the
+     * prefix/namespace mapping was already in scope from before.
+     *
+     * @throws org.xml.sax.SAXException The client may throw
+     *            an exception during processing.
+     *
+     *
+     */
+    public boolean startPrefixMapping(
+        String prefix,
+        String uri,
+        boolean shouldFlush)
+        throws org.xml.sax.SAXException
+    {
+
+        /* Remember the mapping, and at what depth it was declared
+         * This is one greater than the current depth because these
+         * mappings will apply to the next depth. This is in
+         * consideration that startElement() will soon be called
+         */
+
+        boolean pushed;
+        int pushDepth;
+        if (shouldFlush)
+        {
+            flushPending();
+            // the prefix mapping applies to the child element (one deeper)
+            pushDepth = m_elemContext.m_currentElemDepth + 1;
+        }
+        else
+        {
+            // the prefix mapping applies to the current element
+            pushDepth = m_elemContext.m_currentElemDepth;
+        }
+        pushed = m_prefixMap.pushNamespace(prefix, uri, pushDepth);
+
+        if (pushed)
+        {
+            /* Brian M.: don't know if we really needto do this. The
+             * callers of this object should have injected both
+             * startPrefixMapping and the attributes.  We are
+             * just covering our butt here.
+             */
+            String name;
+            if (EMPTYSTRING.equals(prefix))
+            {
+                name = "xmlns";
+                addAttributeAlways(XMLNS_URI, name, name, "CDATA", uri, false);
+            }
+            else
+            {
+                if (!EMPTYSTRING.equals(uri))
+                // hack for XSLTC attribset16 test
+                { // that maps ns1 prefix to "" URI
+                    name = "xmlns:" + prefix;
+
+                    /* for something like xmlns:abc="w3.pretend.org"
+                     *  the      uri is the value, that is why we pass it in the
+                     * value, or 5th slot of addAttributeAlways()
+                     */
+                    addAttributeAlways(XMLNS_URI, prefix, name, "CDATA", uri, false);
+                }
+            }
+        }
+        return pushed;
+    }
+
+    /**
+     * Receive notification of an XML comment anywhere in the document. This
+     * callback will be used for comments inside or outside the document
+     * element, including comments in the external DTD subset (if read).
+     * @param ch An array holding the characters in the comment.
+     * @param start The starting position in the array.
+     * @param length The number of characters to use from the array.
+     * @throws org.xml.sax.SAXException The application may raise an exception.
+     */
+    public void comment(char ch[], int start, int length)
+        throws org.xml.sax.SAXException
+    {
+
+        int start_old = start;
+        if (m_inEntityRef)
+            return;
+        if (m_elemContext.m_startTagOpen)
+        {
+            closeStartTag();
+            m_elemContext.m_startTagOpen = false;
+        }
+        else if (m_needToCallStartDocument)
+        {
+            startDocumentInternal();
+            m_needToCallStartDocument = false;
+        }
+
+        try
+        {
+            final int limit = start + length;
+            boolean wasDash = false;
+            if (m_cdataTagOpen)
+                closeCDATA();
+
+            if (shouldIndent())
+                indent();
+
+            final java.io.Writer writer = m_writer;
+            writer.write(COMMENT_BEGIN);
+            // Detect occurrences of two consecutive dashes, handle as necessary.
+            for (int i = start; i < limit; i++)
+            {
+                if (wasDash && ch[i] == '-')
+                {
+                    writer.write(ch, start, i - start);
+                    writer.write(" -");
+                    start = i + 1;
+                }
+                wasDash = (ch[i] == '-');
+            }
+
+            // if we have some chars in the comment
+            if (length > 0)
+            {
+                // Output the remaining characters (if any)
+                final int remainingChars = (limit - start);
+                if (remainingChars > 0)
+                    writer.write(ch, start, remainingChars);
+                // Protect comment end from a single trailing dash
+                if (ch[limit - 1] == '-')
+                    writer.write(' ');
+            }
+            writer.write(COMMENT_END);
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+
+        /*
+         * Don't write out any indentation whitespace now,
+         * because there may be non-whitespace text after this.
+         *
+         * Simply mark that at this point if we do decide
+         * to indent that we should
+         * add a newline on the end of the current line before
+         * the indentation at the start of the next line.
+         */
+        m_startNewLine = true;
+        // time to generate comment event
+        if (m_tracer != null)
+            super.fireCommentEvent(ch, start_old,length);
+    }
+
+    /**
+     * Report the end of a CDATA section.
+     * @throws org.xml.sax.SAXException The application may raise an exception.
+     *
+     *  @see  #startCDATA
+     */
+    public void endCDATA() throws org.xml.sax.SAXException
+    {
+        if (m_cdataTagOpen)
+            closeCDATA();
+        m_cdataStartCalled = false;
+    }
+
+    /**
+     * Report the end of DTD declarations.
+     * @throws org.xml.sax.SAXException The application may raise an exception.
+     * @see #startDTD
+     */
+    public void endDTD() throws org.xml.sax.SAXException
+    {
+        try
+        {
+            if (m_needToOutputDocTypeDecl)
+            {
+                outputDocTypeDecl(m_elemContext.m_elementName, false);
+                m_needToOutputDocTypeDecl = false;
+            }
+            final java.io.Writer writer = m_writer;
+            if (!m_inDoctype)
+                writer.write("]>");
+            else
+            {
+                writer.write('>');
+            }
+
+            writer.write(m_lineSep, 0, m_lineSepLen);
+        }
+        catch (IOException e)
+        {
+            throw new SAXException(e);
+        }
+
+    }
+
+    /**
+     * End the scope of a prefix-URI Namespace mapping.
+     * @see org.xml.sax.ContentHandler#endPrefixMapping
+     *
+     * @param prefix The prefix that was being mapping.
+     * @throws org.xml.sax.SAXException The client may throw
+     *            an exception during processing.
+     */
+    public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException
+    { // do nothing
+    }
+
+    /**
+     * Receive notification of ignorable whitespace in element content.
+     *
+     * Not sure how to get this invoked quite yet.
+     *
+     * @param ch The characters from the XML document.
+     * @param start The start position in the array.
+     * @param length The number of characters to read from the array.
+     * @throws org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see #characters
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    public void ignorableWhitespace(char ch[], int start, int length)
+        throws org.xml.sax.SAXException
+    {
+
+        if (0 == length)
+            return;
+        characters(ch, start, length);
+    }
+
+    /**
+     * Receive notification of a skipped entity.
+     * @see org.xml.sax.ContentHandler#skippedEntity
+     *
+     * @param name The name of the skipped entity.  If it is a
+     *       parameter                   entity, the name will begin with '%',
+     * and if it is the external DTD subset, it will be the string
+     * "[dtd]".
+     * @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping
+     * another exception.
+     */
+    public void skippedEntity(String name) throws org.xml.sax.SAXException
+    { // TODO: Should handle
+    }
+
+    /**
+     * Report the start of a CDATA section.
+     *
+     * @throws org.xml.sax.SAXException The application may raise an exception.
+     * @see #endCDATA
+     */
+    public void startCDATA() throws org.xml.sax.SAXException
+    {
+        m_cdataStartCalled = true;
+    }
+
+    /**
+     * Report the beginning of an entity.
+     *
+     * The start and end of the document entity are not reported.
+     * The start and end of the external DTD subset are reported
+     * using the pseudo-name "[dtd]".  All other events must be
+     * properly nested within start/end entity events.
+     *
+     * @param name The name of the entity.  If it is a parameter
+     *        entity, the name will begin with '%'.
+     * @throws org.xml.sax.SAXException The application may raise an exception.
+     * @see #endEntity
+     * @see org.xml.sax.ext.DeclHandler#internalEntityDecl
+     * @see org.xml.sax.ext.DeclHandler#externalEntityDecl
+     */
+    public void startEntity(String name) throws org.xml.sax.SAXException
+    {
+        if (name.equals("[dtd]"))
+            m_inExternalDTD = true;
+
+        if (!m_expandDTDEntities && !m_inExternalDTD) {
+            /* Only leave the entity as-is if
+             * we've been told not to expand them
+             * and this is not the magic [dtd] name.
+             */
+            startNonEscaping();
+            characters("&" + name + ';');
+            endNonEscaping();
+        }
+
+        m_inEntityRef = true;
+    }
+
+    /**
+     * For the enclosing elements starting tag write out
+     * out any attributes followed by ">"
+     *
+     * @throws org.xml.sax.SAXException
+     */
+    protected void closeStartTag() throws SAXException
+    {
+
+        if (m_elemContext.m_startTagOpen)
+        {
+
+            try
+            {
+                if (m_tracer != null)
+                    super.fireStartElem(m_elemContext.m_elementName);
+                int nAttrs = m_attributes.getLength();
+                if (nAttrs > 0)
+                {
+                    processAttributes(m_writer, nAttrs);
+                    // clear attributes object for re-use with next element
+                    m_attributes.clear();
+                }
+                m_writer.write('>');
+            }
+            catch (IOException e)
+            {
+                throw new SAXException(e);
+            }
+
+            /* whether Xalan or XSLTC, we have the prefix mappings now, so
+             * lets determine if the current element is specified in the cdata-
+             * section-elements list.
+             */
+            if (m_CdataElems != null)
+                m_elemContext.m_isCdataSection = isCdataSection();
+
+            if (m_doIndent)
+            {
+                m_isprevtext = false;
+                m_preserves.push(m_ispreserve);
+            }
+        }
+
+    }
+
+    /**
+     * Report the start of DTD declarations, if any.
+     *
+     * Any declarations are assumed to be in the internal subset unless
+     * otherwise indicated.
+     *
+     * @param name The document type name.
+     * @param publicId The declared public identifier for the
+     *        external DTD subset, or null if none was declared.
+     * @param systemId The declared system identifier for the
+     *        external DTD subset, or null if none was declared.
+     * @throws org.xml.sax.SAXException The application may raise an
+     *            exception.
+     * @see #endDTD
+     * @see #startEntity
+     */
+    public void startDTD(String name, String publicId, String systemId)
+        throws org.xml.sax.SAXException
+    {
+        setDoctypeSystem(systemId);
+        setDoctypePublic(publicId);
+
+        m_elemContext.m_elementName = name;
+        m_inDoctype = true;
+    }
+
+    /**
+     * Returns the m_indentAmount.
+     * @return int
+     */
+    public int getIndentAmount()
+    {
+        return m_indentAmount;
+    }
+
+    /**
+     * Sets the m_indentAmount.
+     *
+     * @param m_indentAmount The m_indentAmount to set
+     */
+    public void setIndentAmount(int m_indentAmount)
+    {
+        this.m_indentAmount = m_indentAmount;
+    }
+
+    /**
+     * Tell if, based on space preservation constraints and the doIndent property,
+     * if an indent should occur.
+     *
+     * @return True if an indent should occur.
+     */
+    protected boolean shouldIndent()
+    {
+        return m_doIndent && (!m_ispreserve && !m_isprevtext) && m_elemContext.m_currentElemDepth > 0;
+    }
+
+    /**
+     * Searches for the list of qname properties with the specified key in the
+     * property list. If the key is not found in this property list, the default
+     * property list, and its defaults, recursively, are then checked. The
+     * method returns <code>null</code> if the property is not found.
+     *
+     * @param   key   the property key.
+     * @param props the list of properties to search in.
+     *
+     * Sets the vector of local-name/URI pairs of the cdata section elements
+     * specified in the cdata-section-elements property.
+     *
+     * This method is essentially a copy of getQNameProperties() from
+     * OutputProperties. Eventually this method should go away and a call
+     * to setCdataSectionElements(Vector v) should be made directly.
+     */
+    private void setCdataSectionElements(String key, Properties props)
+    {
+
+        String s = props.getProperty(key);
+
+        if (null != s)
+        {
+            // Vector of URI/LocalName pairs
+            Vector v = new Vector();
+            int l = s.length();
+            boolean inCurly = false;
+            StringBuffer buf = new StringBuffer();
+
+            // parse through string, breaking on whitespaces.  I do this instead
+            // of a tokenizer so I can track whitespace inside of curly brackets,
+            // which theoretically shouldn't happen if they contain legal URLs.
+            for (int i = 0; i < l; i++)
+            {
+                char c = s.charAt(i);
+
+                if (Character.isWhitespace(c))
+                {
+                    if (!inCurly)
+                    {
+                        if (buf.length() > 0)
+                        {
+                            addCdataSectionElement(buf.toString(), v);
+                            buf.setLength(0);
+                        }
+                        continue;
+                    }
+                }
+                else if ('{' == c)
+                    inCurly = true;
+                else if ('}' == c)
+                    inCurly = false;
+
+                buf.append(c);
+            }
+
+            if (buf.length() > 0)
+            {
+                addCdataSectionElement(buf.toString(), v);
+                buf.setLength(0);
+            }
+            // call the official, public method to set the collected names
+            setCdataSectionElements(v);
+        }
+
+    }
+
+    /**
+     * Adds a URI/LocalName pair of strings to the list.
+     *
+     * @param URI_and_localName String of the form "{uri}local" or "local" 
+     *
+     * @return a QName object
+     */
+    private void addCdataSectionElement(String URI_and_localName, Vector v)
+    {
+
+        StringTokenizer tokenizer =
+            new StringTokenizer(URI_and_localName, "{}", false);
+        String s1 = tokenizer.nextToken();
+        String s2 = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
+
+        if (null == s2)
+        {
+            // add null URI and the local name
+            v.addElement(null);
+            v.addElement(s1);
+        }
+        else
+        {
+            // add URI, then local name
+            v.addElement(s1);
+            v.addElement(s2);
+        }
+    }
+
+    /**
+     * Remembers the cdata sections specified in the cdata-section-elements.
+     * The "official way to set URI and localName pairs. 
+     * This method should be used by both Xalan and XSLTC.
+     *
+     * @param URI_and_localNames a vector of pairs of Strings (URI/local)
+     */
+    public void setCdataSectionElements(Vector URI_and_localNames)
+    {
+        // convert to the new way.
+        if (URI_and_localNames != null)
+        {
+            final int len = URI_and_localNames.size() - 1;
+            if (len > 0)
+            {
+                final StringBuffer sb = new StringBuffer();
+                for (int i = 0; i < len; i += 2)
+                {
+                    // whitspace separated "{uri1}local1 {uri2}local2 ..."
+                    if (i != 0)
+                        sb.append(' ');
+                    final String uri = (String) URI_and_localNames.elementAt(i);
+                    final String localName =
+                        (String) URI_and_localNames.elementAt(i + 1);
+                    if (uri != null)
+                    {
+                        // If there is no URI don't put this in, just the localName then.
+                        sb.append('{');
+                        sb.append(uri);
+                        sb.append('}');
+                    }
+                    sb.append(localName);
+                }
+                m_StringOfCDATASections = sb.toString();
+            }
+        }
+        initCdataElems(m_StringOfCDATASections);
+    }
+
+    /**
+     * Makes sure that the namespace URI for the given qualified attribute name
+     * is declared.
+     * @param ns the namespace URI
+     * @param rawName the qualified name 
+     * @return returns null if no action is taken, otherwise it returns the
+     * prefix used in declaring the namespace. 
+     * @throws SAXException
+     */
+    protected String ensureAttributesNamespaceIsDeclared(
+        String ns,
+        String localName,
+        String rawName)
+        throws org.xml.sax.SAXException
+    {
+
+        if (ns != null && ns.length() > 0)
+        {
+
+            // extract the prefix in front of the raw name
+            int index = 0;
+            String prefixFromRawName =
+                (index = rawName.indexOf(":")) < 0
+                ? ""
+                : rawName.substring(0, index);
+
+            if (index > 0)
+            {
+                // we have a prefix, lets see if it maps to a namespace 
+                String uri = m_prefixMap.lookupNamespace(prefixFromRawName);
+                if (uri != null && uri.equals(ns))
+                {
+                    // the prefix in the raw name is already maps to the given namespace uri
+                    // so we don't need to do anything
+                    return null;
+                }
+                else
+                {
+                    // The uri does not map to the prefix in the raw name,
+                    // so lets make the mapping.
+                    this.startPrefixMapping(prefixFromRawName, ns, false);
+                    this.addAttribute(
+                        "http://www.w3.org/2000/xmlns/",
+                        prefixFromRawName,
+                        "xmlns:" + prefixFromRawName,
+                        "CDATA",
+                        ns, false);
+                    return prefixFromRawName;
+                }
+            }
+            else
+            {
+                // we don't have a prefix in the raw name.
+                // Does the URI map to a prefix already?
+                String prefix = m_prefixMap.lookupPrefix(ns);
+                if (prefix == null)
+                {
+                    // uri is not associated with a prefix,
+                    // so lets generate a new prefix to use
+                    prefix = m_prefixMap.generateNextPrefix();
+                    this.startPrefixMapping(prefix, ns, false);
+                    this.addAttribute(
+                        "http://www.w3.org/2000/xmlns/",
+                        prefix,
+                        "xmlns:" + prefix,
+                        "CDATA",
+                        ns, false);
+                }
+
+                return prefix;
+
+            }
+        }
+        return null;
+    }
+
+    void ensurePrefixIsDeclared(String ns, String rawName)
+        throws org.xml.sax.SAXException
+    {
+
+        if (ns != null && ns.length() > 0)
+        {
+            int index;
+            final boolean no_prefix = ((index = rawName.indexOf(":")) < 0);
+            String prefix = (no_prefix) ? "" : rawName.substring(0, index);
+
+            if (null != prefix)
+            {
+                String foundURI = m_prefixMap.lookupNamespace(prefix);
+
+                if ((null == foundURI) || !foundURI.equals(ns))
+                {
+                    this.startPrefixMapping(prefix, ns);
+
+                    // Bugzilla1133: Generate attribute as well as namespace event.
+                    // SAX does expect both.
+
+                    this.addAttributeAlways(
+                        "http://www.w3.org/2000/xmlns/",
+                        no_prefix ? "xmlns" : prefix,  // local name
+                        no_prefix ? "xmlns" : ("xmlns:"+ prefix), // qname
+                        "CDATA",
+                        ns,
+                        false);
+                }
+
+            }
+        }
+    }
+
+    /**
+     * This method flushes any pending events, which can be startDocument()
+     * closing the opening tag of an element, or closing an open CDATA section.
+     */
+    public void flushPending() throws SAXException
+    {
+        if (m_needToCallStartDocument)
+        {
+            startDocumentInternal();
+            m_needToCallStartDocument = false;
+        }
+        if (m_elemContext.m_startTagOpen)
+        {
+            closeStartTag();
+            m_elemContext.m_startTagOpen = false;
+        }
+
+        if (m_cdataTagOpen)
+        {
+            closeCDATA();
+            m_cdataTagOpen = false;
+        }
+        if (m_writer != null) {
+            try {
+                m_writer.flush();
+            }
+            catch(IOException e) {
+                // what? me worry?
+            }
+        }
+    }
+
+    public void setContentHandler(ContentHandler ch)
+    {
+        // this method is really only useful in the ToSAXHandler classes but it is
+        // in the interface.  If the method defined here is ever called
+        // we are probably in trouble.
+    }
+
+    /**
+     * Adds the given attribute to the set of attributes, even if there is
+     * no currently open element. This is useful if a SAX startPrefixMapping()
+     * should need to add an attribute before the element name is seen.
+     *
+     * This method is a copy of its super classes method, except that some
+     * tracing of events is done.  This is so the tracing is only done for
+     * stream serializers, not for SAX ones.
+     *
+     * @param uri the URI of the attribute
+     * @param localName the local name of the attribute
+     * @param rawName   the qualified name of the attribute
+     * @param type the type of the attribute (probably CDATA)
+     * @param value the value of the attribute
+     * @param xslAttribute true if this attribute is coming from an xsl:attribute element.
+     * @return true if the attribute value was added, 
+     * false if the attribute already existed and the value was
+     * replaced with the new value.
+     */
+    public boolean addAttributeAlways(
+        String uri,
+        String localName,
+        String rawName,
+        String type,
+        String value,
+        boolean xslAttribute)
+    {
+        boolean was_added;
+        int index;
+        if (uri == null || localName == null || uri.length() == 0)
+            index = m_attributes.getIndex(rawName);
+        else {
+            index = m_attributes.getIndex(uri, localName);
+        }
+
+        if (index >= 0)
+        {
+            String old_value = null;
+            if (m_tracer != null)
+            {
+                old_value = m_attributes.getValue(index);
+                if (value.equals(old_value))
+                    old_value = null;
+            }
+
+            /* We've seen the attribute before.
+             * We may have a null uri or localName, but all we really
+             * want to re-set is the value anyway.
+             */
+            m_attributes.setValue(index, value);
+            was_added = false;
+            if (old_value != null)
+                firePseudoAttributes();
+
+        }
+        else
+        {
+            // the attribute doesn't exist yet, create it
+            if (xslAttribute)
+            {
+                /*
+                 * This attribute is from an xsl:attribute element so we take some care in
+                 * adding it, e.g.
+                 *   <elem1  foo:attr1="1" xmlns:foo="uri1">
+                 *       <xsl:attribute name="foo:attr2">2</xsl:attribute>
+                 *   </elem1>
+                 *
+                 * We are adding attr1 and attr2 both as attributes of elem1,
+                 * and this code is adding attr2 (the xsl:attribute ).
+                 * We could have a collision with the prefix like in the example above.
+                 */
+
+                // In the example above, is there a prefix like foo ?
+                final int colonIndex = rawName.indexOf(':');
+                if (colonIndex > 0)
+                {
+                    String prefix = rawName.substring(0,colonIndex);
+                    NamespaceMappings.MappingRecord existing_mapping = m_prefixMap.getMappingFromPrefix(prefix);
+
+                    /* Before adding this attribute (foo:attr2),
+                     * is the prefix for it (foo) already mapped at the current depth?
+                     */
+                    if (existing_mapping != null
+                        && existing_mapping.m_declarationDepth == m_elemContext.m_currentElemDepth
+                        && !existing_mapping.m_uri.equals(uri))
+                    {
+                        /*
+                         * There is an existing mapping of this prefix,
+                         * it differs from the one we need,
+                         * and unfortunately it is at the current depth so we
+                         * can not over-ride it.
+                         */
+
+                        /*
+                         * Are we lucky enough that an existing other prefix maps to this URI ?
+                         */
+                        prefix = m_prefixMap.lookupPrefix(uri);
+                        if (prefix == null)
+                        {
+                            /* Unfortunately there is no existing prefix that happens to map to ours,
+                             * so to avoid a prefix collision we must generated a new prefix to use.
+                             * This is OK because the prefix URI mapping
+                             * defined in the xsl:attribute is short in scope,
+                             * just the xsl:attribute element itself,
+                             * and at this point in serialization the body of the
+                             * xsl:attribute, if any, is just a String. Right?
+                             *   . . . I sure hope so - Brian M.
+                             */
+                            prefix = m_prefixMap.generateNextPrefix();
+                        }
+
+                        rawName = prefix + ':' + localName;
+                    }
+                }
+
+                try
+                {
+                    /* This is our last chance to make sure the namespace for this
+                     * attribute is declared, especially if we just generated an alternate
+                     * prefix to avoid a collision (the new prefix/rawName will go out of scope
+                     * soon and be lost ...  last chance here.
+                     */
+                    String prefixUsed =
+                        ensureAttributesNamespaceIsDeclared(
+                            uri,
+                            localName,
+                            rawName);
+                }
+                catch (SAXException e)
+                {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                }
+            }
+            m_attributes.addAttribute(uri, localName, rawName, type, value);
+            was_added = true;
+            if (m_tracer != null)
+                firePseudoAttributes();
+        }
+        return was_added;
+    }
+
+    /**
+     * To fire off the pseudo characters of attributes, as they currently
+     * exist. This method should be called everytime an attribute is added,
+     * or when an attribute value is changed, or an element is created.
+     */
+
+    protected void firePseudoAttributes()
+    {
+        if (m_tracer != null)
+        {
+            try
+            {
+                // flush out the "<elemName" if not already flushed
+                m_writer.flush();
+
+                // make a StringBuffer to write the name="value" pairs to.
+                StringBuffer sb = new StringBuffer();
+                int nAttrs = m_attributes.getLength();
+                if (nAttrs > 0)
+                {
+                    // make a writer that internally appends to the same
+                    // StringBuffer
+                    java.io.Writer writer =
+                        new ToStream.WritertoStringBuffer(sb);
+
+                    processAttributes(writer, nAttrs);
+                    // Don't clear the attributes! 
+                    // We only want to see what would be written out
+                    // at this point, we don't want to loose them.
+                }
+                sb.append('>');  // the potential > after the attributes.
+                // convert the StringBuffer to a char array and
+                // emit the trace event that these characters "might"
+                // be written                
+                char ch[] = sb.toString().toCharArray();
+                m_tracer.fireGenerateEvent(
+                    SerializerTrace.EVENTTYPE_OUTPUT_PSEUDO_CHARACTERS,
+                    ch,
+                    0,
+                    ch.length);
+            }
+            catch (IOException ioe)
+            {
+                // ignore ?
+            }
+            catch (SAXException se)
+            {
+                // ignore ?
+            }
+        }
+    }
+
+    /**
+     * This inner class is used only to collect attribute values
+     * written by the method writeAttrString() into a string buffer.
+     * In this manner trace events, and the real writing of attributes will use
+     * the same code.
+     */
+    private static class WritertoStringBuffer extends java.io.Writer
+    {
+        final private StringBuffer m_stringbuf;
+        /**
+         * @see java.io.Writer#write(char[], int, int)
+         */
+        WritertoStringBuffer(StringBuffer sb)
+        {
+            m_stringbuf = sb;
+        }
+
+        public void write(char[] arg0, int arg1, int arg2) throws IOException
+        {
+            m_stringbuf.append(arg0, arg1, arg2);
+        }
+        /**
+         * @see java.io.Writer#flush()
+         */
+        public void flush() throws IOException
+        {
+        }
+        /**
+         * @see java.io.Writer#close()
+         */
+        public void close() throws IOException
+        {
+        }
+
+        public void write(int i)
+        {
+            m_stringbuf.append((char) i);
+        }
+
+        public void write(String s)
+        {
+            m_stringbuf.append(s);
+        }
+    }
+
+    /**
+     * @see SerializationHandler#setTransformer(Transformer)
+     */
+    public void setTransformer(Transformer transformer) {
+        super.setTransformer(transformer);
+        if (m_tracer != null
+            && !(m_writer instanceof SerializerTraceWriter)  )
+            setWriterInternal(new SerializerTraceWriter(m_writer, m_tracer), false);
+
+
+    }
+    /**
+     * Try's to reset the super class and reset this class for 
+     * re-use, so that you don't need to create a new serializer 
+     * (mostly for performance reasons).
+     *
+     * @return true if the class was successfuly reset.
+     */
+    public boolean reset()
+    {
+        boolean wasReset = false;
+        if (super.reset())
+        {
+            resetToStream();
+            wasReset = true;
+        }
+        return wasReset;
+    }
+
+    /**
+     * Reset all of the fields owned by ToStream class
+     *
+     */
+    private void resetToStream()
+    {
+        this.m_cdataStartCalled = false;
+        /* The stream is being reset. It is one of
+         * ToXMLStream, ToHTMLStream ... and this type can't be changed
+         * so neither should m_charInfo which is associated with the
+         * type of Stream. Just leave m_charInfo as-is for the next re-use.
+         *
+         */
+        // this.m_charInfo = null; // don't set to null
+        this.m_disableOutputEscapingStates.clear();
+        // this.m_encodingInfo = null; // don't set to null
+
+        this.m_escaping = true;
+        // Leave m_format alone for now - Brian M.
+        // this.m_format = null;
+        this.m_expandDTDEntities = true;
+        this.m_inDoctype = false;
+        this.m_ispreserve = false;
+        this.m_isprevtext = false;
+        this.m_isUTF8 = false; //  ?? used anywhere ??
+        this.m_lineSep = s_systemLineSep;
+        this.m_lineSepLen = s_systemLineSep.length;
+        this.m_lineSepUse = true;
+        // this.m_outputStream = null; // Don't reset it may be re-used
+        this.m_preserves.clear();
+        this.m_shouldFlush = true;
+        this.m_spaceBeforeClose = false;
+        this.m_startNewLine = false;
+        this.m_writer_set_by_user = false;
+    }
+
+    /**
+     * Sets the character encoding coming from the xsl:output encoding stylesheet attribute.
+     * @param encoding the character encoding
+     */
+    public void setEncoding(String encoding)
+    {
+        setOutputProperty(OutputKeys.ENCODING,encoding);
+    }
+
+    /**
+     * Simple stack for boolean values.
+     *
+     * This class is a copy of the one in org.apache.xml.utils. 
+     * It exists to cut the serializers dependancy on that package.
+     * A minor changes from that package are:
+     * doesn't implement Clonable
+     *
+     * @xsl.usage internal
+     */
+    static final class BoolStack
+    {
+
+        /** Array of boolean values          */
+        private boolean m_values[];
+
+        /** Array size allocated           */
+        private int m_allocatedSize;
+
+        /** Index into the array of booleans          */
+        private int m_index;
+
+        /**
+         * Default constructor.  Note that the default
+         * block size is very small, for small lists.
+         */
+        public BoolStack()
+        {
+            this(32);
+        }
+
+        /**
+         * Construct a IntVector, using the given block size.
+         *
+         * @param size array size to allocate
+         */
+        public BoolStack(int size)
+        {
+
+            m_allocatedSize = size;
+            m_values = new boolean[size];
+            m_index = -1;
+        }
+
+        /**
+         * Get the length of the list.
+         *
+         * @return Current length of the list
+         */
+        public final int size()
+        {
+            return m_index + 1;
+        }
+
+        /**
+         * Clears the stack.
+         *
+         */
+        public final void clear()
+        {
+            m_index = -1;
+        }
+
+        /**
+         * Pushes an item onto the top of this stack.
+         *
+         *
+         * @param val the boolean to be pushed onto this stack.
+         * @return  the <code>item</code> argument.
+         */
+        public final boolean push(boolean val)
+        {
+
+            if (m_index == m_allocatedSize - 1)
+                grow();
+
+            return (m_values[++m_index] = val);
+        }
+
+        /**
+         * Removes the object at the top of this stack and returns that
+         * object as the value of this function.
+         *
+         * @return     The object at the top of this stack.
+         * @throws  EmptyStackException  if this stack is empty.
+         */
+        public final boolean pop()
+        {
+            return m_values[m_index--];
+        }
+
+        /**
+         * Removes the object at the top of this stack and returns the
+         * next object at the top as the value of this function.
+         *
+         *
+         * @return Next object to the top or false if none there
+         */
+        public final boolean popAndTop()
+        {
+
+            m_index--;
+
+            return (m_index >= 0) ? m_values[m_index] : false;
+        }
+
+        /**
+         * Set the item at the top of this stack
+         *
+         *
+         * @param b Object to set at the top of this stack
+         */
+        public final void setTop(boolean b)
+        {
+            m_values[m_index] = b;
+        }
+
+        /**
+         * Looks at the object at the top of this stack without removing it
+         * from the stack.
+         *
+         * @return     the object at the top of this stack.
+         * @throws  EmptyStackException  if this stack is empty.
+         */
+        public final boolean peek()
+        {
+            return m_values[m_index];
+        }
+
+        /**
+         * Looks at the object at the top of this stack without removing it
+         * from the stack.  If the stack is empty, it returns false.
+         *
+         * @return     the object at the top of this stack.
+         */
+        public final boolean peekOrFalse()
+        {
+            return (m_index > -1) ? m_values[m_index] : false;
+        }
+
+        /**
+         * Looks at the object at the top of this stack without removing it
+         * from the stack.  If the stack is empty, it returns true.
+         *
+         * @return     the object at the top of this stack.
+         */
+        public final boolean peekOrTrue()
+        {
+            return (m_index > -1) ? m_values[m_index] : true;
+        }
+
+        /**
+         * Tests if this stack is empty.
+         *
+         * @return  <code>true</code> if this stack is empty;
+         *          <code>false</code> otherwise.
+         */
+        public boolean isEmpty()
+        {
+            return (m_index == -1);
+        }
+
+        /**
+         * Grows the size of the stack
+         *
+         */
+        private void grow()
+        {
+
+            m_allocatedSize *= 2;
+
+            boolean newVector[] = new boolean[m_allocatedSize];
+
+            System.arraycopy(m_values, 0, newVector, 0, m_index + 1);
+
+            m_values = newVector;
+        }
+    }
+
+    // Implement DTDHandler
+    /**
+     * If this method is called, the serializer is used as a
+     * DTDHandler, which changes behavior how the serializer 
+     * handles document entities. 
+     * @see org.xml.sax.DTDHandler#notationDecl(java.lang.String, java.lang.String, java.lang.String)
+     */
+    public void notationDecl(String name, String pubID, String sysID) throws SAXException {
+        // TODO Auto-generated method stub
+        try {
+            DTDprolog();
+
+            m_writer.write("<!NOTATION ");
+            m_writer.write(name);
+            if (pubID != null) {
+                m_writer.write(" PUBLIC \"");
+                m_writer.write(pubID);
+
+            }
+            else {
+                m_writer.write(" SYSTEM \"");
+                m_writer.write(sysID);
+            }
+            m_writer.write("\" >");
+            m_writer.write(m_lineSep, 0, m_lineSepLen);
+        } catch (IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * If this method is called, the serializer is used as a
+     * DTDHandler, which changes behavior how the serializer 
+     * handles document entities. 
+     * @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
+     */
+    public void unparsedEntityDecl(String name, String pubID, String sysID, String notationName) throws SAXException {
+        // TODO Auto-generated method stub
+        try {
+            DTDprolog();
+
+            m_writer.write("<!ENTITY ");
+            m_writer.write(name);
+            if (pubID != null) {
+                m_writer.write(" PUBLIC \"");
+                m_writer.write(pubID);
+
+            }
+            else {
+                m_writer.write(" SYSTEM \"");
+                m_writer.write(sysID);
+            }
+            m_writer.write("\" NDATA ");
+            m_writer.write(notationName);
+            m_writer.write(" >");
+            m_writer.write(m_lineSep, 0, m_lineSepLen);
+        } catch (IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * A private helper method to output the 
+     * @throws SAXException
+     * @throws IOException
+     */
+    private void DTDprolog() throws SAXException, IOException {
+        final java.io.Writer writer = m_writer;
+        if (m_needToOutputDocTypeDecl)
+        {
+            outputDocTypeDecl(m_elemContext.m_elementName, false);
+            m_needToOutputDocTypeDecl = false;
+        }
+        if (m_inDoctype)
+        {
+            writer.write(" [");
+            writer.write(m_lineSep, 0, m_lineSepLen);
+            m_inDoctype = false;
+        }
+    }
+
+    /**
+     * If set to false the serializer does not expand DTD entities,
+     * but leaves them as is, the default value is true;
+     */
+    public void setDTDEntityExpansion(boolean expand) {
+        m_expandDTDEntities = expand;
+    }
+
+    /**
+     * Sets the end of line characters to be used during serialization
+     * @param eolChars A character array corresponding to the characters to be used.
+     */
+    public void setNewLine (char[] eolChars) {
+        m_lineSep = eolChars;
+        m_lineSepLen = eolChars.length;
+    }
+
+    /**
+     * Remembers the cdata sections specified in the cdata-section-elements by appending the given
+     * cdata section elements to the list. This method can be called multiple times, but once an
+     * element is put in the list of cdata section elements it can not be removed.
+     * This method should be used by both Xalan and XSLTC.
+     *
+     * @param URI_and_localNames a whitespace separated list of element names, each element
+     * is a URI in curly braces (optional) and a local name. An example of such a parameter is:
+     * "{http://company.com}price {myURI2}book chapter"
+     */
+    public void addCdataSectionElements(String URI_and_localNames)
+    {
+        if (URI_and_localNames != null)
+            initCdataElems(URI_and_localNames);
+        if (m_StringOfCDATASections == null)
+            m_StringOfCDATASections = URI_and_localNames;
+        else
+            m_StringOfCDATASections += (" " + URI_and_localNames);
+    }
+}


[tomee] 02/04: TOMEE-2938 Default copy of Xalan code before patching

Posted by jl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jlmonteiro pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 02feaaaf1185297b28b20b9fd0a5f12ca77a4a63
Author: Jean-Louis Monteiro <jl...@tomitribe.com>
AuthorDate: Tue Dec 8 14:47:38 2020 +0100

    TOMEE-2938 Default copy of Xalan code before patching
---
 .../org/apache/xml/serializer/ToHTMLStream.java    | 726 ++++++++++-----------
 .../java/org/apache/xml/serializer/ToStream.java   | 142 ++--
 2 files changed, 426 insertions(+), 442 deletions(-)

diff --git a/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java
index 637117d..0d501ef 100644
--- a/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java
+++ b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java
@@ -34,19 +34,19 @@ import org.xml.sax.SAXException;
  * This serializer takes a series of SAX or
  * SAX-like events and writes its output
  * to the given stream.
- * 
+ *
  * This class is not a public API, it is public
  * because it is used from another package.
- * 
+ *
  * @xsl.usage internal
  */
-public class ToHTMLStream extends ToStream 
+public class ToHTMLStream extends ToStream
 {
 
     /** This flag is set while receiving events from the DTD */
     protected boolean m_inDTD = false;
 
-    /** True if the current element is a block element.  (seems like 
+    /** True if the current element is a block element.  (seems like
      *  this needs to be a stack. -sb). */
     private boolean m_inBlockElem = false;
 
@@ -115,25 +115,25 @@ public class ToHTMLStream extends ToStream
             "BR",
             new ElemDesc(
                 0
-                    | ElemDesc.SPECIAL
-                    | ElemDesc.ASPECIAL
-                    | ElemDesc.EMPTY
-                    | ElemDesc.BLOCK));
+                | ElemDesc.SPECIAL
+                | ElemDesc.ASPECIAL
+                | ElemDesc.EMPTY
+                | ElemDesc.BLOCK));
         m_elementFlags.put("BODY", new ElemDesc(0 | ElemDesc.BLOCK));
         m_elementFlags.put(
             "ADDRESS",
             new ElemDesc(
                 0
-                    | ElemDesc.BLOCK
-                    | ElemDesc.BLOCKFORM
-                    | ElemDesc.BLOCKFORMFIELDSET));
+                | ElemDesc.BLOCK
+                | ElemDesc.BLOCKFORM
+                | ElemDesc.BLOCKFORMFIELDSET));
         m_elementFlags.put(
             "DIV",
             new ElemDesc(
                 0
-                    | ElemDesc.BLOCK
-                    | ElemDesc.BLOCKFORM
-                    | ElemDesc.BLOCKFORMFIELDSET));
+                | ElemDesc.BLOCK
+                | ElemDesc.BLOCKFORM
+                | ElemDesc.BLOCKFORMFIELDSET));
         m_elementFlags.put("A", new ElemDesc(0 | ElemDesc.SPECIAL));
         m_elementFlags.put(
             "MAP",
@@ -150,34 +150,34 @@ public class ToHTMLStream extends ToStream
             "IMG",
             new ElemDesc(
                 0
-                    | ElemDesc.SPECIAL
-                    | ElemDesc.ASPECIAL
-                    | ElemDesc.EMPTY
-                    | ElemDesc.WHITESPACESENSITIVE));
+                | ElemDesc.SPECIAL
+                | ElemDesc.ASPECIAL
+                | ElemDesc.EMPTY
+                | ElemDesc.WHITESPACESENSITIVE));
         m_elementFlags.put(
             "OBJECT",
             new ElemDesc(
                 0
-                    | ElemDesc.SPECIAL
-                    | ElemDesc.ASPECIAL
-                    | ElemDesc.HEADMISC
-                    | ElemDesc.WHITESPACESENSITIVE));
+                | ElemDesc.SPECIAL
+                | ElemDesc.ASPECIAL
+                | ElemDesc.HEADMISC
+                | ElemDesc.WHITESPACESENSITIVE));
         m_elementFlags.put("PARAM", new ElemDesc(0 | ElemDesc.EMPTY));
         m_elementFlags.put(
             "HR",
             new ElemDesc(
                 0
-                    | ElemDesc.BLOCK
-                    | ElemDesc.BLOCKFORM
-                    | ElemDesc.BLOCKFORMFIELDSET
-                    | ElemDesc.EMPTY));
+                | ElemDesc.BLOCK
+                | ElemDesc.BLOCKFORM
+                | ElemDesc.BLOCKFORMFIELDSET
+                | ElemDesc.EMPTY));
         m_elementFlags.put(
             "P",
             new ElemDesc(
                 0
-                    | ElemDesc.BLOCK
-                    | ElemDesc.BLOCKFORM
-                    | ElemDesc.BLOCKFORMFIELDSET));
+                | ElemDesc.BLOCK
+                | ElemDesc.BLOCKFORM
+                | ElemDesc.BLOCKFORMFIELDSET));
         m_elementFlags.put(
             "H1",
             new ElemDesc(0 | ElemDesc.HEAD | ElemDesc.BLOCK));
@@ -206,18 +206,18 @@ public class ToHTMLStream extends ToStream
             "BLOCKQUOTE",
             new ElemDesc(
                 0
-                    | ElemDesc.BLOCK
-                    | ElemDesc.BLOCKFORM
-                    | ElemDesc.BLOCKFORMFIELDSET));
+                | ElemDesc.BLOCK
+                | ElemDesc.BLOCKFORM
+                | ElemDesc.BLOCKFORMFIELDSET));
         m_elementFlags.put("INS", new ElemDesc(0));
         m_elementFlags.put("DEL", new ElemDesc(0));
         m_elementFlags.put(
             "DL",
             new ElemDesc(
                 0
-                    | ElemDesc.BLOCK
-                    | ElemDesc.BLOCKFORM
-                    | ElemDesc.BLOCKFORMFIELDSET));
+                | ElemDesc.BLOCK
+                | ElemDesc.BLOCKFORM
+                | ElemDesc.BLOCKFORMFIELDSET));
         m_elementFlags.put("DT", new ElemDesc(0 | ElemDesc.BLOCK));
         m_elementFlags.put("DD", new ElemDesc(0 | ElemDesc.BLOCK));
         m_elementFlags.put(
@@ -252,9 +252,9 @@ public class ToHTMLStream extends ToStream
             "TABLE",
             new ElemDesc(
                 0
-                    | ElemDesc.BLOCK
-                    | ElemDesc.BLOCKFORM
-                    | ElemDesc.BLOCKFORMFIELDSET));
+                | ElemDesc.BLOCK
+                | ElemDesc.BLOCKFORM
+                | ElemDesc.BLOCKFORMFIELDSET));
         m_elementFlags.put("CAPTION", new ElemDesc(0 | ElemDesc.BLOCK));
         m_elementFlags.put("THEAD", new ElemDesc(0 | ElemDesc.BLOCK));
         m_elementFlags.put("TFOOT", new ElemDesc(0 | ElemDesc.BLOCK));
@@ -285,17 +285,17 @@ public class ToHTMLStream extends ToStream
             "SCRIPT",
             new ElemDesc(
                 0
-                    | ElemDesc.SPECIAL
-                    | ElemDesc.ASPECIAL
-                    | ElemDesc.HEADMISC
-                    | ElemDesc.RAW));
+                | ElemDesc.SPECIAL
+                | ElemDesc.ASPECIAL
+                | ElemDesc.HEADMISC
+                | ElemDesc.RAW));
         m_elementFlags.put(
             "NOSCRIPT",
             new ElemDesc(
                 0
-                    | ElemDesc.BLOCK
-                    | ElemDesc.BLOCKFORM
-                    | ElemDesc.BLOCKFORMFIELDSET));
+                | ElemDesc.BLOCK
+                | ElemDesc.BLOCKFORM
+                | ElemDesc.BLOCKFORMFIELDSET));
         m_elementFlags.put("HTML", new ElemDesc(0 | ElemDesc.BLOCK | ElemDesc.HTMLELEM));
 
         // From "John Ky" <hand@syd.speednet.com.au
@@ -318,26 +318,26 @@ public class ToHTMLStream extends ToStream
             "IFRAME",
             new ElemDesc(
                 0
-                    | ElemDesc.BLOCK
-                    | ElemDesc.BLOCKFORM
-                    | ElemDesc.BLOCKFORMFIELDSET));
-                    
+                | ElemDesc.BLOCK
+                | ElemDesc.BLOCKFORM
+                | ElemDesc.BLOCKFORMFIELDSET));
+
         // Netscape 4 extension
         m_elementFlags.put(
             "LAYER",
             new ElemDesc(
                 0
-                    | ElemDesc.BLOCK
-                    | ElemDesc.BLOCKFORM
-                    | ElemDesc.BLOCKFORMFIELDSET));
-        // Netscape 4 extension                    
+                | ElemDesc.BLOCK
+                | ElemDesc.BLOCKFORM
+                | ElemDesc.BLOCKFORMFIELDSET));
+        // Netscape 4 extension
         m_elementFlags.put(
             "ILAYER",
             new ElemDesc(
                 0
-                    | ElemDesc.BLOCK
-                    | ElemDesc.BLOCKFORM
-                    | ElemDesc.BLOCKFORMFIELDSET));
+                | ElemDesc.BLOCK
+                | ElemDesc.BLOCKFORM
+                | ElemDesc.BLOCKFORMFIELDSET));
 
         // NOW FOR ATTRIBUTE INFORMATION . . .
         ElemDesc elemDesc;
@@ -347,7 +347,7 @@ public class ToHTMLStream extends ToStream
         elemDesc = (ElemDesc) m_elementFlags.get("a");
         elemDesc.setAttr("HREF", ElemDesc.ATTRURL);
         elemDesc.setAttr("NAME", ElemDesc.ATTRURL);
-        
+
         // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("area");
 
@@ -375,17 +375,17 @@ public class ToHTMLStream extends ToStream
         // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("dir");
         elemDesc.setAttr("COMPACT", ElemDesc.ATTREMPTY);
-           
+
         // ----------------------------------------------
-        
+
         elemDesc = (ElemDesc) m_elementFlags.get("div");
         elemDesc.setAttr("SRC", ElemDesc.ATTRURL); // Netscape 4 extension
         elemDesc.setAttr("NOWRAP", ElemDesc.ATTREMPTY); // Internet-Explorer extension
-   
-        // ----------------------------------------------        
+
+        // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("dl");
         elemDesc.setAttr("COMPACT", ElemDesc.ATTREMPTY);
-           
+
         // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("form");
         elemDesc.setAttr("ACTION", ElemDesc.ATTRURL);
@@ -401,10 +401,10 @@ public class ToHTMLStream extends ToStream
         elemDesc = (ElemDesc) m_elementFlags.get("head");
         elemDesc.setAttr("PROFILE", ElemDesc.ATTRURL);
 
-        // ----------------------------------------------        
+        // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("hr");
         elemDesc.setAttr("NOSHADE", ElemDesc.ATTREMPTY);
-        
+
         // ----------------------------------------------
         // HTML 4.0, section 16.5
         elemDesc = (ElemDesc) m_elementFlags.get("iframe");
@@ -432,7 +432,7 @@ public class ToHTMLStream extends ToStream
         elemDesc.setAttr("DISABLED", ElemDesc.ATTREMPTY);
         elemDesc.setAttr("ISMAP", ElemDesc.ATTREMPTY);
         elemDesc.setAttr("READONLY", ElemDesc.ATTREMPTY);
-        
+
         // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("ins");
         elemDesc.setAttr("CITE", ElemDesc.ATTRURL);
@@ -445,11 +445,11 @@ public class ToHTMLStream extends ToStream
         // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("link");
         elemDesc.setAttr("HREF", ElemDesc.ATTRURL);
-       
-        // ----------------------------------------------       
+
+        // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("menu");
         elemDesc.setAttr("COMPACT", ElemDesc.ATTREMPTY);
-        
+
         // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("object");
 
@@ -459,11 +459,11 @@ public class ToHTMLStream extends ToStream
         elemDesc.setAttr("ARCHIVE", ElemDesc.ATTRURL);
         elemDesc.setAttr("USEMAP", ElemDesc.ATTRURL);
         elemDesc.setAttr("DECLARE", ElemDesc.ATTREMPTY);
-        
-        // ----------------------------------------------        
+
+        // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("ol");
         elemDesc.setAttr("COMPACT", ElemDesc.ATTREMPTY);
-        
+
         // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("optgroup");
         elemDesc.setAttr("DISABLED", ElemDesc.ATTREMPTY);
@@ -472,7 +472,7 @@ public class ToHTMLStream extends ToStream
         elemDesc = (ElemDesc) m_elementFlags.get("option");
         elemDesc.setAttr("SELECTED", ElemDesc.ATTREMPTY);
         elemDesc.setAttr("DISABLED", ElemDesc.ATTREMPTY);
-        
+
         // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("q");
         elemDesc.setAttr("CITE", ElemDesc.ATTRURL);
@@ -491,8 +491,8 @@ public class ToHTMLStream extends ToStream
         // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("table");
         elemDesc.setAttr("NOWRAP", ElemDesc.ATTREMPTY); // Internet-Explorer extension
-        
-        // ----------------------------------------------        
+
+        // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("td");
         elemDesc.setAttr("NOWRAP", ElemDesc.ATTREMPTY);
 
@@ -500,18 +500,18 @@ public class ToHTMLStream extends ToStream
         elemDesc = (ElemDesc) m_elementFlags.get("textarea");
         elemDesc.setAttr("DISABLED", ElemDesc.ATTREMPTY);
         elemDesc.setAttr("READONLY", ElemDesc.ATTREMPTY);
-       
-        // ----------------------------------------------                
+
+        // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("th");
         elemDesc.setAttr("NOWRAP", ElemDesc.ATTREMPTY);
-        
+
         // ----------------------------------------------
         // The nowrap attribute of a tr element is both
-        // a Netscape and Internet-Explorer extension                
+        // a Netscape and Internet-Explorer extension
         elemDesc = (ElemDesc) m_elementFlags.get("tr");
         elemDesc.setAttr("NOWRAP", ElemDesc.ATTREMPTY);
-        
-        // ----------------------------------------------        
+
+        // ----------------------------------------------
         elemDesc = (ElemDesc) m_elementFlags.get("ul");
         elemDesc.setAttr("COMPACT", ElemDesc.ATTREMPTY);
     }
@@ -553,12 +553,12 @@ public class ToHTMLStream extends ToStream
      * it will switch to the new format. This method should not be
      * called while the serializer is in the process of serializing
      * a document.
-     * 
+     *
      * This method can be called multiple times before starting
      * the serialization of a particular result-tree. In principle
      * all serialization parameters can be changed, with the exception
      * of method="html" (it must be method="html" otherwise we
-     * shouldn't even have a ToHTMLStream object here!) 
+     * shouldn't even have a ToHTMLStream object here!)
      *
      * @param format The output format or serialzation parameters
      * to use.
@@ -570,7 +570,7 @@ public class ToHTMLStream extends ToStream
          * S_USE_URL_ESCAPING, then don't set this value at all,
          * just leave as-is rather than explicitly setting it.
          */
-        String value; 
+        String value;
         value = format.getProperty(OutputPropertiesFactory.S_USE_URL_ESCAPING);
         if (value != null) {
             m_specialEscapeURLs =
@@ -586,7 +586,7 @@ public class ToHTMLStream extends ToStream
          */
         value = format.getProperty(OutputPropertiesFactory.S_OMIT_META_TAG);
         if (value != null) {
-           m_omitMetaTag =
+            m_omitMetaTag =
                 OutputPropertyUtils.getBooleanProperty(
                     OutputPropertiesFactory.S_OMIT_META_TAG,
                     format);
@@ -620,7 +620,7 @@ public class ToHTMLStream extends ToStream
      *
      * @param name non-null name of element, case insensitive.
      *
-     * @return non-null reference to ElemDesc, which may be m_dummy if no 
+     * @return non-null reference to ElemDesc, which may be m_dummy if no
      *         element description matches the given name.
      */
     public static final ElemDesc getElemDesc(String name)
@@ -633,8 +633,8 @@ public class ToHTMLStream extends ToStream
             return (ElemDesc)obj;
         return m_dummy;
     }
-    
-    
+
+
     /**
      * A Trie that is just a copy of the "static" one.
      * We need this one to be able to use the faster, but not thread-safe
@@ -663,7 +663,7 @@ public class ToHTMLStream extends ToStream
         // we are just constructing this thing, no output properties
         // have been used, so we will set the right default for
         // indenting anyways
-        m_doIndent = true; 
+        m_doIndent = true;
         m_charInfo = m_htmlcharInfo;
         // initialize namespaces
         m_prefixMap = new NamespaceMappings();
@@ -685,7 +685,7 @@ public class ToHTMLStream extends ToStream
     {
         super.startDocumentInternal();
 
-        m_needToCallStartDocument = false; 
+        m_needToCallStartDocument = false;
         m_needToOutputDocTypeDecl = true;
         m_startNewLine = false;
         setOmitXMLDeclaration(true);
@@ -707,29 +707,29 @@ public class ToHTMLStream extends ToStream
                 final java.io.Writer writer = m_writer;
                 try
                 {
-                writer.write("<!DOCTYPE ");
-                writer.write(name);
+                    writer.write("<!DOCTYPE ");
+                    writer.write(name);
 
-                if (null != doctypePublic)
-                {
-                    writer.write(" PUBLIC \"");
-                    writer.write(doctypePublic);
-                    writer.write('"');
-                }
+                    if (null != doctypePublic)
+                    {
+                        writer.write(" PUBLIC \"");
+                        writer.write(doctypePublic);
+                        writer.write('"');
+                    }
 
-                if (null != doctypeSystem)
-                {
-                    if (null == doctypePublic)
-                        writer.write(" SYSTEM \"");
-                    else
-                        writer.write(" \"");
+                    if (null != doctypeSystem)
+                    {
+                        if (null == doctypePublic)
+                            writer.write(" SYSTEM \"");
+                        else
+                            writer.write(" \"");
 
-                    writer.write(doctypeSystem);
-                    writer.write('"');
-                }
+                        writer.write(doctypeSystem);
+                        writer.write('"');
+                    }
 
-                writer.write('>');
-                outputLineSep();
+                    writer.write('>');
+                    outputLineSep();
                 }
                 catch(IOException e)
                 {
@@ -742,7 +742,7 @@ public class ToHTMLStream extends ToStream
     }
 
     /**
-     * Receive notification of the end of a document. 
+     * Receive notification of the end of a document.
      *
      * @throws org.xml.sax.SAXException Any SAX exception, possibly
      *            wrapping another exception.
@@ -751,13 +751,13 @@ public class ToHTMLStream extends ToStream
      */
     public final void endDocument() throws org.xml.sax.SAXException
     {
-        
+
         flushPending();
         if (m_doIndent && !m_isprevtext)
         {
             try
             {
-            outputLineSep();
+                outputLineSep();
             }
             catch(IOException e)
             {
@@ -809,8 +809,8 @@ public class ToHTMLStream extends ToStream
             startDocumentInternal();
             m_needToCallStartDocument = false;
         }
-        
-        if (m_needToOutputDocTypeDecl) {            
+
+        if (m_needToOutputDocTypeDecl) {
             String n = name;
             if (n == null || n.length() == 0) {
                 // If the lexical QName is not given
@@ -828,7 +828,7 @@ public class ToHTMLStream extends ToStream
 
             return;
         }
-        
+
         try
         {
             // getElemDesc2(name) is faster than getElemDesc(name)
@@ -846,7 +846,7 @@ public class ToHTMLStream extends ToStream
                     (null != elemContext.m_elementName)
                     && (!m_inBlockElem
                         || isBlockElement) /* && !isWhiteSpaceSensitive */
-                    )
+                )
                 {
                     m_startNewLine = true;
 
@@ -858,7 +858,7 @@ public class ToHTMLStream extends ToStream
 
             // save any attributes for later processing
             if (atts != null)
-                addAttributes(atts);            
+                addAttributes(atts);
 
             m_isprevtext = false;
             final java.io.Writer writer = m_writer;
@@ -869,8 +869,8 @@ public class ToHTMLStream extends ToStream
 
             if (m_tracer != null)
                 firePseudoAttributes();
-            
-            if ((elemFlags & ElemDesc.EMPTY) != 0)  
+
+            if ((elemFlags & ElemDesc.EMPTY) != 0)
             {
                 // an optimization for elements which are expected
                 // to be empty.
@@ -880,8 +880,8 @@ public class ToHTMLStream extends ToStream
                  */
                 m_elemContext.m_elementName = name;
                 m_elemContext.m_elementDesc = elemDesc;
-                return;                
-            } 
+                return;
+            }
             else
             {
                 elemContext = elemContext.push(namespaceURI,localName,name);
@@ -889,7 +889,7 @@ public class ToHTMLStream extends ToStream
                 elemContext.m_elementDesc = elemDesc;
                 elemContext.m_isRaw = (elemFlags & ElemDesc.RAW) != 0;
             }
-            
+
 
             if ((elemFlags & ElemDesc.HEADELEM) != 0)
             {
@@ -982,7 +982,7 @@ public class ToHTMLStream extends ToStream
             {
                 // the start-tag open when this method was called,
                 // so we need to process it now.
-                
+
                 if (m_tracer != null)
                     super.fireStartElem(name);
 
@@ -1011,7 +1011,7 @@ public class ToHTMLStream extends ToStream
                     writer.write('>');
                 }
             }
-            
+
             // clean up because the element has ended
             if ((elemFlags & ElemDesc.WHITESPACESENSITIVE) != 0)
                 m_ispreserve = true;
@@ -1019,9 +1019,9 @@ public class ToHTMLStream extends ToStream
 
             // fire off the end element event
             if (m_tracer != null)
-                super.fireEndElem(name);            
-                           
-            // OPTIMIZE-EMPTY                
+                super.fireEndElem(name);
+
+            // OPTIMIZE-EMPTY
             if (elemEmpty)
             {
                 // a quick exit if the HTML element had no children.
@@ -1031,7 +1031,7 @@ public class ToHTMLStream extends ToStream
                 return;
             }
 
-            // some more clean because the element has ended. 
+            // some more clean because the element has ended.
             if (!elemContext.m_startTagOpen)
             {
                 if (m_doIndent && !m_preserves.isEmpty())
@@ -1051,7 +1051,7 @@ public class ToHTMLStream extends ToStream
      * @param   writer The writer to write the processed output to.
      * @param   name   The name of the attribute.
      * @param   value   The value of the attribute.
-     * @param   elemDesc The description of the HTML element 
+     * @param   elemDesc The description of the HTML element
      *           that has this attribute.
      *
      * @throws org.xml.sax.SAXException
@@ -1066,8 +1066,8 @@ public class ToHTMLStream extends ToStream
         writer.write(' ');
 
         if (   ((value.length() == 0) || value.equalsIgnoreCase(name))
-            && elemDesc != null 
-            && elemDesc.isAttrFlagSet(name, ElemDesc.ATTREMPTY))
+               && elemDesc != null
+               && elemDesc.isAttrFlagSet(name, ElemDesc.ATTREMPTY))
         {
             writer.write(name);
         }
@@ -1079,7 +1079,7 @@ public class ToHTMLStream extends ToStream
             writer.write(name);
             writer.write("=\"");
             if (   elemDesc != null
-                && elemDesc.isAttrFlagSet(name, ElemDesc.ATTRURL))
+                   && elemDesc.isAttrFlagSet(name, ElemDesc.ATTRURL))
                 writeAttrURI(writer, value, m_specialEscapeURLs);
             else
                 writeAttrString(writer, value, this.getEncoding());
@@ -1098,11 +1098,11 @@ public class ToHTMLStream extends ToStream
 
     /**
      * Make an integer into an HH hex value.
-     * Does no checking on the size of the input, since this 
+     * Does no checking on the size of the input, since this
      * is only meant to be used locally by writeAttrURI.
-     * 
+     *
      * @param i must be a value less than 255.
-     * 
+     *
      * @return should be a two character string.
      */
     private static String makeHHString(int i)
@@ -1116,11 +1116,11 @@ public class ToHTMLStream extends ToStream
     }
 
     /**
-    * Dmitri Ilyin: Makes sure if the String is HH encoded sign.
-    * @param str must be 2 characters long
-    *
-    * @return true or false
-    */
+     * Dmitri Ilyin: Makes sure if the String is HH encoded sign.
+     * @param str must be 2 characters long
+     *
+     * @return true or false
+     */
     private boolean isHHSign(String str)
     {
         boolean sign = true;
@@ -1140,7 +1140,7 @@ public class ToHTMLStream extends ToStream
      * with <CODE>%HH</CODE>, where HH is the hex of the byte value.
      *
      * @param   string      String to convert to XML format.
-     * @param doURLEscaping True if we should try to encode as 
+     * @param doURLEscaping True if we should try to encode as
      *                      per http://www.ietf.org/rfc/rfc2396.txt.
      *
      * @throws org.xml.sax.SAXException if a bad surrogate pair is detected.
@@ -1160,22 +1160,22 @@ public class ToHTMLStream extends ToStream
         // must be separated into its components before the escaped characters
         // within those components can be safely decoded.
         //
-        // ...So we do our best to do limited escaping of the URL, without 
-        // causing damage.  If the URL is already properly escaped, in theory, this 
+        // ...So we do our best to do limited escaping of the URL, without
+        // causing damage.  If the URL is already properly escaped, in theory, this
         // function should not change the string value.
 
         final int end = string.length();
         if (end > m_attrBuff.length)
         {
-           m_attrBuff = new char[end*2 + 1];               
+            m_attrBuff = new char[end*2 + 1];
         }
-        string.getChars(0,end, m_attrBuff, 0); 
+        string.getChars(0,end, m_attrBuff, 0);
         final char[] chars = m_attrBuff;
 
         int cleanStart = 0;
         int cleanLength = 0;
-        
-        
+
+
         char ch = 0;
         for (int i = 0; i < end; i++)
         {
@@ -1199,7 +1199,7 @@ public class ToHTMLStream extends ToStream
                     //  {
                     //    writer.write(ch);
                     //  }
-                    //  else 
+                    //  else
                     if (ch <= 0x7F)
                     {
                         writer.write('%');
@@ -1207,7 +1207,7 @@ public class ToHTMLStream extends ToStream
                     }
                     else if (ch <= 0x7FF)
                     {
-                        // Clear low 6 bits before rotate, put high 4 bits in low byte, 
+                        // Clear low 6 bits before rotate, put high 4 bits in low byte,
                         // and set two high bits.
                         int high = (ch >> 6) | 0xC0;
                         int low = (ch & 0x3F) | 0x80;
@@ -1219,11 +1219,11 @@ public class ToHTMLStream extends ToStream
                     }
                     else if (Encodings.isHighUTF16Surrogate(ch)) // high surrogate
                     {
-                        // I'm sure this can be done in 3 instructions, but I choose 
-                        // to try and do it exactly like it is done in the book, at least 
-                        // until we are sure this is totally clean.  I don't think performance 
-                        // is a big issue with this particular function, though I could be 
-                        // wrong.  Also, the stuff below clearly does more masking than 
+                        // I'm sure this can be done in 3 instructions, but I choose
+                        // to try and do it exactly like it is done in the book, at least
+                        // until we are sure this is totally clean.  I don't think performance
+                        // is a big issue with this particular function, though I could be
+                        // wrong.  Also, the stuff below clearly does more masking than
                         // it needs to do.
 
                         // Clear high 6 bits.
@@ -1231,7 +1231,7 @@ public class ToHTMLStream extends ToStream
 
                         // Middle 4 bits (wwww) + 1
                         // "Note that the value of wwww from the high surrogate bit pattern
-                        // is incremented to make the uuuuu bit pattern in the scalar value 
+                        // is incremented to make the uuuuu bit pattern in the scalar value
                         // so the surrogate pair don't address the BMP."
                         int wwww = ((highSurrogate & 0x03C0) >> 6);
                         int uuuuu = wwww + 1;
@@ -1295,14 +1295,14 @@ public class ToHTMLStream extends ToStream
                     writer.write(Integer.toString(ch));
                     writer.write(';');
                 }
-                // In this character range we have first written out any previously accumulated 
+                // In this character range we have first written out any previously accumulated
                 // "clean" characters, then processed the current more complicated character,
                 // which may have incremented "i".
                 // We now we reset the next possible clean character.
                 cleanStart = i + 1;
             }
             // Since http://www.ietf.org/rfc/rfc2396.txt refers to the URI grammar as
-            // not allowing quotes in the URI proper syntax, nor in the fragment 
+            // not allowing quotes in the URI proper syntax, nor in the fragment
             // identifier, we believe that it's OK to double escape quotes.
             else if (ch == '"')
             {
@@ -1320,9 +1320,9 @@ public class ToHTMLStream extends ToStream
                 {
                     writer.write(chars, cleanStart, cleanLength);
                     cleanLength = 0;
-                }   
-                
-                
+                }
+
+
                 // Mike Kay encodes this as &#34;, so he may know something I don't?
                 if (doURLEscaping)
                     writer.write("%22");
@@ -1331,20 +1331,20 @@ public class ToHTMLStream extends ToStream
 
                 // We have written out any clean characters, then the escaped '%' and now we
                 // We now we reset the next possible clean character.
-                cleanStart = i + 1;    
+                cleanStart = i + 1;
             }
             else if (ch == '&')
             {
-                // HTML 4.01 reads, "Authors should use "&amp;" (ASCII decimal 38) 
-                // instead of "&" to avoid confusion with the beginning of a character 
-                // reference (entity reference open delimiter). 
+                // HTML 4.01 reads, "Authors should use "&amp;" (ASCII decimal 38)
+                // instead of "&" to avoid confusion with the beginning of a character
+                // reference (entity reference open delimiter).
                 if (cleanLength > 0)
                 {
                     writer.write(chars, cleanStart, cleanLength);
                     cleanLength = 0;
-                } 
+                }
                 writer.write("&amp;");
-                cleanStart = i + 1; 
+                cleanStart = i + 1;
             }
             else
             {
@@ -1353,7 +1353,7 @@ public class ToHTMLStream extends ToStream
                 cleanLength++;
             }
         }
-        
+
         // are there any clean characters at the end of the array
         // that we haven't processed yet?
         if (cleanLength > 1)
@@ -1395,7 +1395,7 @@ public class ToHTMLStream extends ToStream
         string.getChars(0, end, m_attrBuff, 0);
         final char[] chars = m_attrBuff;
 
-        
+
 
         int cleanStart = 0;
         int cleanLength = 0;
@@ -1439,14 +1439,14 @@ public class ToHTMLStream extends ToStream
                 {
                     if (Encodings.isHighUTF16Surrogate(ch))
                     {
- 
-                            writeUTF16Surrogate(ch, chars, i, end);
-                            i++; // two input characters processed
-                                 // this increments by one and the for()
-                                 // loop itself increments by another one.
+
+                        writeUTF16Surrogate(ch, chars, i, end);
+                        i++; // two input characters processed
+                        // this increments by one and the for()
+                        // loop itself increments by another one.
                     }
 
-                    // The next is kind of a hack to keep from escaping in the case 
+                    // The next is kind of a hack to keep from escaping in the case
                     // of Shift_JIS and the like.
 
                     /*
@@ -1476,7 +1476,7 @@ public class ToHTMLStream extends ToStream
                 cleanStart = i + 1;
             }
         } // end of for()
-        
+
         // are there any clean characters at the end of the array
         // that we haven't processed yet?
         if (cleanLength > 1)
@@ -1531,7 +1531,7 @@ public class ToHTMLStream extends ToStream
     {
 
         if (m_elemContext.m_isRaw)
-        { 
+        {
             try
             {
                 // Clean up some pending issues.
@@ -1540,15 +1540,15 @@ public class ToHTMLStream extends ToStream
                     closeStartTag();
                     m_elemContext.m_startTagOpen = false;
                 }
-                
+
                 m_ispreserve = true;
-                
+
                 writeNormalizedChars(chars, start, length, false, m_lineSepUse);
-                
+
                 // time to generate characters event
                 if (m_tracer != null)
                     super.fireCharEvent(chars, start, length);
-                
+
                 return;
             }
             catch (IOException ioe)
@@ -1646,9 +1646,9 @@ public class ToHTMLStream extends ToStream
     {
 
         // Process any pending starDocument and startElement first.
-        flushPending(); 
-        
-        // Use a fairly nasty hack to tell if the next node is supposed to be 
+        flushPending();
+
+        // Use a fairly nasty hack to tell if the next node is supposed to be
         // unescaped text.
         if (target.equals(Result.PI_DISABLE_OUTPUT_ESCAPING))
         {
@@ -1676,51 +1676,51 @@ public class ToHTMLStream extends ToStream
                 {
                     startDocumentInternal();
                 }
-            
 
-            /*
-             * Perhaps processing instructions can be written out in HTML before
-             * the DOCTYPE, in which case this could be emitted with the
-             * startElement call, that knows the name of the document element
-             * doing it right.
-             */
-            if (true == m_needToOutputDocTypeDecl)
-                outputDocTypeDecl("html"); // best guess for the upcoming element
 
- 
-            if (shouldIndent())
-                indent();
+                /*
+                 * Perhaps processing instructions can be written out in HTML before
+                 * the DOCTYPE, in which case this could be emitted with the
+                 * startElement call, that knows the name of the document element
+                 * doing it right.
+                 */
+                if (true == m_needToOutputDocTypeDecl)
+                    outputDocTypeDecl("html"); // best guess for the upcoming element
 
-            final java.io.Writer writer = m_writer;
-            //writer.write("<?" + target);
-            writer.write("<?");
-            writer.write(target);
 
-            if (data.length() > 0 && !Character.isSpaceChar(data.charAt(0)))
-                writer.write(' '); 
+                if (shouldIndent())
+                    indent();
 
-            //writer.write(data + ">"); // different from XML
-            writer.write(data); // different from XML
-            writer.write('>'); // different from XML
+                final java.io.Writer writer = m_writer;
+                //writer.write("<?" + target);
+                writer.write("<?");
+                writer.write(target);
 
-            // Always output a newline char if not inside of an 
-            // element. The whitespace is not significant in that
-            // case.
-            if (m_elemContext.m_currentElemDepth <= 0)
-                outputLineSep();
+                if (data.length() > 0 && !Character.isSpaceChar(data.charAt(0)))
+                    writer.write(' ');
 
-            m_startNewLine = true;
+                //writer.write(data + ">"); // different from XML
+                writer.write(data); // different from XML
+                writer.write('>'); // different from XML
+
+                // Always output a newline char if not inside of an
+                // element. The whitespace is not significant in that
+                // case.
+                if (m_elemContext.m_currentElemDepth <= 0)
+                    outputLineSep();
+
+                m_startNewLine = true;
             }
             catch(IOException e)
             {
                 throw new SAXException(e);
             }
         }
-               
+
         // now generate the PI event
         if (m_tracer != null)
             super.fireEscapingEvent(target, data);
-     }
+    }
 
     /**
      * Receive notivication of a entityReference.
@@ -1735,11 +1735,11 @@ public class ToHTMLStream extends ToStream
         try
         {
 
-        final java.io.Writer writer = m_writer;
-        writer.write('&');
-        writer.write(name);
-        writer.write(';');
-        
+            final java.io.Writer writer = m_writer;
+            writer.write('&');
+            writer.write(name);
+            writer.write(';');
+
         } catch(IOException e)
         {
             throw new SAXException(e);
@@ -1757,9 +1757,9 @@ public class ToHTMLStream extends ToStream
      * Process the attributes, which means to write out the currently
      * collected attributes to the writer. The attributes are not
      * cleared by this method
-     * 
+     *
      * @param writer the writer to write processed attributes to.
-     * @param nAttrs the number of attributes in m_attributes 
+     * @param nAttrs the number of attributes in m_attributes
      * to be processed
      *
      * @throws org.xml.sax.SAXException
@@ -1767,17 +1767,17 @@ public class ToHTMLStream extends ToStream
     public void processAttributes(java.io.Writer writer, int nAttrs)
         throws IOException,SAXException
     {
-            /* 
-             * process the collected attributes
-             */
-            for (int i = 0; i < nAttrs; i++)
-            {
-                processAttribute(
-                    writer,
-                    m_attributes.getQName(i),
-                    m_attributes.getValue(i),
-                    m_elemContext.m_elementDesc);
-            }
+        /*
+         * process the collected attributes
+         */
+        for (int i = 0; i < nAttrs; i++)
+        {
+            processAttribute(
+                writer,
+                m_attributes.getQName(i),
+                m_attributes.getValue(i),
+                m_elemContext.m_elementDesc);
+        }
     }
 
     /**
@@ -1789,14 +1789,14 @@ public class ToHTMLStream extends ToStream
      */
     protected void closeStartTag() throws SAXException
     {
-            try
-            {
+        try
+        {
 
             // finish processing attributes, time to fire off the start element event
             if (m_tracer != null)
-                super.fireStartElem(m_elemContext.m_elementName);  
-            
-            int nAttrs = m_attributes.getLength();   
+                super.fireStartElem(m_elemContext.m_elementName);
+
+            int nAttrs = m_attributes.getLength();
             if (nAttrs>0)
             {
                 processAttributes(m_writer, nAttrs);
@@ -1817,45 +1817,45 @@ public class ToHTMLStream extends ToStream
                 m_isprevtext = false;
                 m_preserves.push(m_ispreserve);
             }
-            
-            }
-            catch(IOException e)
-            {
-                throw new SAXException(e);
-            }
+
+        }
+        catch(IOException e)
+        {
+            throw new SAXException(e);
+        }
     }
-    
 
-   
-        /**
-         * This method is used when a prefix/uri namespace mapping
-         * is indicated after the element was started with a
-         * startElement() and before and endElement().
-         * startPrefixMapping(prefix,uri) would be used before the
-         * startElement() call.
-         * @param uri the URI of the namespace
-         * @param prefix the prefix associated with the given URI.
-         *
-         * @see ExtendedContentHandler#namespaceAfterStartElement(String, String)
-         */
-        public void namespaceAfterStartElement(String prefix, String uri)
-            throws SAXException
+
+
+    /**
+     * This method is used when a prefix/uri namespace mapping
+     * is indicated after the element was started with a
+     * startElement() and before and endElement().
+     * startPrefixMapping(prefix,uri) would be used before the
+     * startElement() call.
+     * @param uri the URI of the namespace
+     * @param prefix the prefix associated with the given URI.
+     *
+     * @see ExtendedContentHandler#namespaceAfterStartElement(String, String)
+     */
+    public void namespaceAfterStartElement(String prefix, String uri)
+        throws SAXException
+    {
+        // hack for XSLTC with finding URI for default namespace
+        if (m_elemContext.m_elementURI == null)
         {
-            // hack for XSLTC with finding URI for default namespace
-            if (m_elemContext.m_elementURI == null)
+            String prefix1 = getPrefixPart(m_elemContext.m_elementName);
+            if (prefix1 == null && EMPTYSTRING.equals(prefix))
             {
-                String prefix1 = getPrefixPart(m_elemContext.m_elementName);
-                if (prefix1 == null && EMPTYSTRING.equals(prefix))
-                {
-                    // the elements URI is not known yet, and it
-                    // doesn't have a prefix, and we are currently
-                    // setting the uri for prefix "", so we have
-                    // the uri for the element... lets remember it
-                    m_elemContext.m_elementURI = uri;
-                }
-            }            
-            startPrefixMapping(prefix,uri,false);
+                // the elements URI is not known yet, and it
+                // doesn't have a prefix, and we are currently
+                // setting the uri for prefix "", so we have
+                // the uri for the element... lets remember it
+                m_elemContext.m_elementURI = uri;
+            }
         }
+        startPrefixMapping(prefix,uri,false);
+    }
 
     public void startDTD(String name, String publicId, String systemId)
         throws SAXException
@@ -1918,10 +1918,10 @@ public class ToHTMLStream extends ToStream
     }
 
     /**
-     * This method is used to add an attribute to the currently open element. 
+     * This method is used to add an attribute to the currently open element.
      * The caller has guaranted that this attribute is unique, which means that it
      * not been seen before and will not be seen again.
-     * 
+     *
      * @param name the qualified name of the attribute
      * @param value the value of the attribute which can contain only
      * ASCII printable characters characters in the range 32 to 127 inclusive.
@@ -1948,7 +1948,7 @@ public class ToHTMLStream extends ToStream
             }
             else if (
                 (flags & HTML_ATTREMPTY) > 0
-                    && (value.length() == 0 || value.equalsIgnoreCase(name)))
+                && (value.length() == 0 || value.equalsIgnoreCase(name)))
             {
                 writer.write(' ');
                 writer.write(name);
@@ -1974,12 +1974,12 @@ public class ToHTMLStream extends ToStream
     }
 
     public void comment(char ch[], int start, int length)
-            throws SAXException
+        throws SAXException
     {
         // The internal DTD subset is not serialized by the ToHTMLStream serializer
         if (m_inDTD)
             return;
-        
+
         // Clean up some pending issues, just in case
         // this call is coming right after a startElement()
         // or we are in the middle of writing out CDATA
@@ -2008,16 +2008,16 @@ public class ToHTMLStream extends ToStream
 
         super.comment(ch, start, length);
     }
-    
+
     public boolean reset()
     {
         boolean ret = super.reset();
         if (!ret)
             return false;
         resetToHTMLStream();
-        return true;        
+        return true;
     }
-    
+
     private void resetToHTMLStream()
     {
         // m_htmlcharInfo remains unchanged
@@ -2025,9 +2025,9 @@ public class ToHTMLStream extends ToStream
         m_inBlockElem = false;
         m_inDTD = false;
         m_omitMetaTag = false;
-        m_specialEscapeURLs = true;     
+        m_specialEscapeURLs = true;
     }
-    
+
     static class Trie
     {
         /**
@@ -2035,15 +2035,15 @@ public class ToHTMLStream extends ToStream
          * The API is a subset of java.util.Hashtable
          * The key must be a 7-bit ASCII string
          * The value may be any Java Object
-         * One can get an object stored in a trie from its key, 
-         * but the search is either case sensitive or case 
+         * One can get an object stored in a trie from its key,
+         * but the search is either case sensitive or case
          * insensitive to the characters in the key, and this
          * choice of sensitivity or insensitivity is made when
          * the Trie is created, before any objects are put in it.
-         * 
-         * This class is a copy of the one in org.apache.xml.utils. 
+         *
+         * This class is a copy of the one in org.apache.xml.utils.
          * It exists to cut the serializers dependancy on that package.
-         *  
+         *
          * @xsl.usage internal
          */
 
@@ -2115,7 +2115,7 @@ public class ToHTMLStream extends ToStream
                         Node newNode = new Node();
                         if (m_lowerCaseOnly)
                         {
-                            // put this value into the tree only with a lower case key 
+                            // put this value into the tree only with a lower case key
                             node.m_nextChar[Character.toLowerCase(
                                 key.charAt(i))] =
                                 newNode;
@@ -2168,61 +2168,61 @@ public class ToHTMLStream extends ToStream
                 // faster for lookup of elements of length 2 with this in
                 // and a fair bit faster.  Don't know why.
                 case 0 :
-                    {
-                        return null;
-                    }
+                {
+                    return null;
+                }
 
                 case 1 :
+                {
+                    final char ch = key.charAt(0);
+                    if (ch < ALPHA_SIZE)
                     {
-                        final char ch = key.charAt(0);
-                        if (ch < ALPHA_SIZE)
-                        {
-                            node = node.m_nextChar[ch];
-                            if (node != null)
-                                return node.m_Value;
-                        }
-                        return null;
+                        node = node.m_nextChar[ch];
+                        if (node != null)
+                            return node.m_Value;
                     }
-                    //                comment out case 2 because the default is faster            
-                    //                case 2 :
-                    //                    {
-                    //                        final char ch0 = key.charAt(0);
-                    //                        final char ch1 = key.charAt(1);
-                    //                        if (ch0 < ALPHA_SIZE && ch1 < ALPHA_SIZE)
-                    //                        {
-                    //                            node = node.m_nextChar[ch0];
-                    //                            if (node != null)
-                    //                            {
-                    //                        
-                    //                                if (ch1 < ALPHA_SIZE) 
-                    //                                {
-                    //                                    node = node.m_nextChar[ch1];
-                    //                                    if (node != null)
-                    //                                        return node.m_Value;
-                    //                                }
-                    //                            }
-                    //                        }
-                    //                        return null;
-                    //                   }
+                    return null;
+                }
+                //                comment out case 2 because the default is faster
+                //                case 2 :
+                //                    {
+                //                        final char ch0 = key.charAt(0);
+                //                        final char ch1 = key.charAt(1);
+                //                        if (ch0 < ALPHA_SIZE && ch1 < ALPHA_SIZE)
+                //                        {
+                //                            node = node.m_nextChar[ch0];
+                //                            if (node != null)
+                //                            {
+                //
+                //                                if (ch1 < ALPHA_SIZE)
+                //                                {
+                //                                    node = node.m_nextChar[ch1];
+                //                                    if (node != null)
+                //                                        return node.m_Value;
+                //                                }
+                //                            }
+                //                        }
+                //                        return null;
+                //                   }
                 default :
+                {
+                    for (int i = 0; i < len; i++)
                     {
-                        for (int i = 0; i < len; i++)
+                        // A thread-safe way to loop over the characters
+                        final char ch = key.charAt(i);
+                        if (ALPHA_SIZE <= ch)
                         {
-                            // A thread-safe way to loop over the characters
-                            final char ch = key.charAt(i);
-                            if (ALPHA_SIZE <= ch)
-                            {
-                                // the key is not 7-bit ASCII so we won't find it here
-                                return null;
-                            }
-
-                            node = node.m_nextChar[ch];
-                            if (node == null)
-                                return null;
+                            // the key is not 7-bit ASCII so we won't find it here
+                            return null;
                         }
 
-                        return node.m_Value;
+                        node = node.m_nextChar[ch];
+                        if (node == null)
+                            return null;
                     }
+
+                    return node.m_Value;
+                }
             }
         }
 
@@ -2253,7 +2253,7 @@ public class ToHTMLStream extends ToStream
          * Both the existing Trie and this new one share the same table for
          * lookup, and it is assumed that the table is fully populated and
          * not changing anymore.
-         * 
+         *
          * @param existingTrie the Trie that this one is a copy of.
          */
         public Trie(Trie existingTrie)
@@ -2293,49 +2293,49 @@ public class ToHTMLStream extends ToStream
                 // faster for lookup of elements of length 2 with this in
                 // and a fair bit faster.  Don't know why.
                 case 0 :
-                    {
-                        return null;
-                    }
+                {
+                    return null;
+                }
 
                 case 1 :
+                {
+                    final char ch = key.charAt(0);
+                    if (ch < ALPHA_SIZE)
                     {
-                        final char ch = key.charAt(0);
-                        if (ch < ALPHA_SIZE)
-                        {
-                            node = node.m_nextChar[ch];
-                            if (node != null)
-                                return node.m_Value;
-                        }
-                        return null;
+                        node = node.m_nextChar[ch];
+                        if (node != null)
+                            return node.m_Value;
                     }
+                    return null;
+                }
                 default :
+                {
+                    /* Copy string into array. This is not thread-safe because
+                     * it modifies the contents of m_charBuffer. If multiple
+                     * threads were to use this Trie they all would be
+                     * using this same array (not good). So this
+                     * method is not thread-safe, but it is faster because
+                     * converting to a char[] and looping over elements of
+                     * the array is faster than a String's charAt(i).
+                     */
+                    key.getChars(0, len, m_charBuffer, 0);
+
+                    for (int i = 0; i < len; i++)
                     {
-                        /* Copy string into array. This is not thread-safe because
-                         * it modifies the contents of m_charBuffer. If multiple
-                         * threads were to use this Trie they all would be
-                         * using this same array (not good). So this 
-                         * method is not thread-safe, but it is faster because
-                         * converting to a char[] and looping over elements of
-                         * the array is faster than a String's charAt(i).
-                         */
-                        key.getChars(0, len, m_charBuffer, 0);
-
-                        for (int i = 0; i < len; i++)
+                        final char ch = m_charBuffer[i];
+                        if (ALPHA_SIZE <= ch)
                         {
-                            final char ch = m_charBuffer[i];
-                            if (ALPHA_SIZE <= ch)
-                            {
-                                // the key is not 7-bit ASCII so we won't find it here
-                                return null;
-                            }
-
-                            node = node.m_nextChar[ch];
-                            if (node == null)
-                                return null;
+                            // the key is not 7-bit ASCII so we won't find it here
+                            return null;
                         }
 
-                        return node.m_Value;
+                        node = node.m_nextChar[ch];
+                        if (node == null)
+                            return null;
                     }
+
+                    return node.m_Value;
+                }
             }
         }
 
diff --git a/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java
index 3b90747..3389567 100644
--- a/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java
+++ b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java
@@ -20,18 +20,6 @@
  */
 package org.apache.xml.serializer;
 
-import org.apache.xml.serializer.utils.MsgKey;
-import org.apache.xml.serializer.utils.Utils;
-import org.apache.xml.serializer.utils.WrappedRuntimeException;
-import org.w3c.dom.Node;
-import org.xml.sax.Attributes;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-
-import javax.xml.transform.ErrorListener;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
@@ -45,8 +33,21 @@ import java.util.Set;
 import java.util.StringTokenizer;
 import java.util.Vector;
 
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+
+import org.apache.xml.serializer.utils.MsgKey;
+import org.apache.xml.serializer.utils.Utils;
+import org.apache.xml.serializer.utils.WrappedRuntimeException;
+import org.w3c.dom.Node;
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+
 /**
- * This abstract class is a base class for other stream 
+ * This abstract class is a base class for other stream
  * serializers (xml, html, text ...) that write output to a stream.
  *
  * @xsl.usage internal
@@ -68,9 +69,9 @@ abstract public class ToStream extends SerializerBase
      * that every character is in the encoding. This is useful
      * for a serializer that is in temporary output state and has
      * no associated encoding. A serializer in final output state
-     * will have an encoding, and will worry about whether 
+     * will have an encoding, and will worry about whether
      * single chars or surrogate pairs of high/low chars form
-     * characters in the output encoding. 
+     * characters in the output encoding.
      */
     EncodingInfo m_encodingInfo = new EncodingInfo(null,null, '\u0000');
 
@@ -87,7 +88,7 @@ abstract public class ToStream extends SerializerBase
 
     /**
      * State flag to tell if preservation of whitespace
-     * is important. 
+     * is important.
      *
      * Used only in shouldIndent() but only if m_doIndent is true.
      * If m_doIndent is false this flag has no impact.
@@ -100,7 +101,7 @@ abstract public class ToStream extends SerializerBase
      * was text, so we can tell if we should preserve whitespace.
      *
      * Used in endDocument() and shouldIndent() but
-     * only if m_doIndent is true. 
+     * only if m_doIndent is true.
      * If m_doIndent is false this flag has no impact.
      */
     protected boolean m_isprevtext = false;
@@ -225,7 +226,7 @@ abstract public class ToStream extends SerializerBase
     }
 
     /**
-     * Taken from XSLTC 
+     * Taken from XSLTC
      */
     protected boolean m_escaping = true;
 
@@ -255,8 +256,8 @@ abstract public class ToStream extends SerializerBase
                 }
                 else
                 {
-                    // Flush always. 
-                    // Not a great thing if the writer was created 
+                    // Flush always.
+                    // Not a great thing if the writer was created
                     // by this class, but don't have a choice.
                     writer.flush();
                 }
@@ -564,7 +565,7 @@ abstract public class ToStream extends SerializerBase
         if (format != null)
         {
             // Set the default values first,
-            // and the non-default values after that, 
+            // and the non-default values after that,
             // just in case there is some unexpected
             // residual values left over from over-ridden default values
             Enumeration propNames;
@@ -587,7 +588,7 @@ abstract public class ToStream extends SerializerBase
             }
         }
 
-        // Access this only from the Hashtable level... we don't want to 
+        // Access this only from the Hashtable level... we don't want to
         // get default properties.
         String entitiesFileName =
             (String) format.get(OutputPropertiesFactory.S_KEY_ENTITIES);
@@ -674,13 +675,13 @@ abstract public class ToStream extends SerializerBase
 
     /**
      * Set if the operating systems end-of-line line separator should
-     * be used when serializing.  If set false NL character 
+     * be used when serializing.  If set false NL character
      * (decimal 10) is left alone, otherwise the new-line will be replaced on
      * output with the systems line separator. For example on UNIX this is
      * NL, while on Windows it is two characters, CR NL, where CR is the
      * carriage-return (decimal 13).
      *
-     * @param use_sytem_line_break True if an input NL is replaced with the 
+     * @param use_sytem_line_break True if an input NL is replaced with the
      * operating systems end-of-line separator.
      * @return The previously set value of the serializer.
      */
@@ -940,7 +941,7 @@ abstract public class ToStream extends SerializerBase
         final boolean ret;
         if (ch < 127)
         {
-            // This is the old/fast code here, but is this 
+            // This is the old/fast code here, but is this
             // correct for all encodings?
             if (ch >= CharInfo.S_SPACE || (CharInfo.S_LINEFEED == ch ||
                                            CharInfo.S_CARRIAGERETURN == ch || CharInfo.S_HORIZONAL_TAB == ch))
@@ -973,7 +974,7 @@ abstract public class ToStream extends SerializerBase
      * @return 0 if the pair of characters was written out as-is,
      * the unicode code point of the character represented by
      * the surrogate pair if an entity reference with that value
-     * was written out. 
+     * was written out.
      *
      * @throws IOException
      * @throws org.xml.sax.SAXException if invalid UTF-16 surrogate detected.
@@ -1096,7 +1097,7 @@ abstract public class ToStream extends SerializerBase
      * @param start The start position in the array.
      * @param length The number of characters to read from the array.
      * @param isCData true if a CDATA block should be built around the characters.
-     * @param useSystemLineSeparator true if the operating systems 
+     * @param useSystemLineSeparator true if the operating systems
      * end-of-line separator should be output rather than a new-line character.
      *
      * @throws IOException
@@ -1127,7 +1128,7 @@ abstract public class ToStream extends SerializerBase
                 if (m_cdataTagOpen)
                     closeCDATA();
 
-                // This needs to go into a function... 
+                // This needs to go into a function...
                 if (Encodings.isHighUTF16Surrogate(c))
                 {
                     writeUTF16Surrogate(c, ch, i, end);
@@ -1173,7 +1174,7 @@ abstract public class ToStream extends SerializerBase
                     writer.write(c);
                 }
 
-                // This needs to go into a function... 
+                // This needs to go into a function...
                 else if (Encodings.isHighUTF16Surrogate(c))
                 {
                     if (m_cdataTagOpen)
@@ -1394,10 +1395,10 @@ abstract public class ToStream extends SerializerBase
     public void characters(final char chars[], final int start, final int length)
         throws org.xml.sax.SAXException
     {
-        // It does not make sense to continue with rest of the method if the number of 
+        // It does not make sense to continue with rest of the method if the number of
         // characters to read from array is 0.
         // Section 7.6.1 of XSLT 1.0 (http://www.w3.org/TR/xslt#value-of) suggest no text node
-        // is created if string is empty.	
+        // is created if string is empty.
         if (length == 0 || (m_inEntityRef && !m_expandDTDEntities))
             return;
 
@@ -1449,7 +1450,7 @@ abstract public class ToStream extends SerializerBase
             int i;
             int startClean;
 
-            // skip any leading whitspace 
+            // skip any leading whitspace
             // don't go off the end and use a hand inlined version
             // of isWhitespace(ch)
             final int end = start + length;
@@ -1543,7 +1544,7 @@ abstract public class ToStream extends SerializerBase
                         // 0xD   CARRIAGE RETURN
                         //
                         // We also cover 0x0 ... It isn't valid
-                        // but we will output "&#0;" 
+                        // but we will output "&#0;"
 
                         // The default will handle this just fine, but this
                         // is a little performance boost to handle the more
@@ -1598,25 +1599,12 @@ abstract public class ToStream extends SerializerBase
                         // not in the normal ASCII range, we also
                         // just leave it get added on to the clean characters
 
-                    } else if (Encodings.isHighUTF16Surrogate(ch) &&
-                               i < end - 1 &&
-                               Encodings.isLowUTF16Surrogate(chars[i + 1])) {
-
-                        // So, this is a (valid) surrogate pair
-                        if (!m_encodingInfo.isInEncoding(ch, chars[i + 1])) {
-                            int codepoint = Encodings.toCodePoint(ch, chars[i + 1]);
-                            writeOutCleanChars(chars, i, lastDirtyCharProcessed);
-                            writer.write("&#");
-                            writer.write(Integer.toString(codepoint));
-                            writer.write(';');
-                            lastDirtyCharProcessed = i + 1;
-                        }
-                        i++; // skip the low surrogate, too
-                    } else {
-                        // This is a fallback plan, we get here if the
-                        // encoding doesn't contain ch and it's not part
-                        // of a surrogate pair
-                        // The right thing is to write out an entity
+                    }
+                    else {
+                        // This is a fallback plan, we should never get here
+                        // but if the character wasn't previously handled
+                        // (i.e. isn't in the encoding, etc.) then what
+                        // should we do?  We choose to write out an entity
                         writeOutCleanChars(chars, i, lastDirtyCharProcessed);
                         writer.write("&#");
                         writer.write(Integer.toString(ch));
@@ -1705,7 +1693,7 @@ abstract public class ToStream extends SerializerBase
      * Process a dirty character and any preeceding clean characters
      * that were not yet processed.
      * @param chars array of characters being processed
-     * @param end one (1) beyond the last character 
+     * @param end one (1) beyond the last character
      * in chars to be processed
      * @param i the index of the dirty character
      * @param ch the character in chars[i]
@@ -1724,7 +1712,7 @@ abstract public class ToStream extends SerializerBase
     {
         int startClean = lastDirty + 1;
         // if we have some clean characters accumulated
-        // process them before the dirty one.                   
+        // process them before the dirty one.
         if (i > startClean)
         {
             int lengthClean = i - startClean;
@@ -1749,7 +1737,7 @@ abstract public class ToStream extends SerializerBase
                     false);
             i = startClean - 1;
         }
-        // Return the index of the last character that we just processed 
+        // Return the index of the last character that we just processed
         // which is a dirty character.
         return i;
     }
@@ -2064,7 +2052,7 @@ abstract public class ToStream extends SerializerBase
      * cleared by this method
      *
      * @param writer the writer to write processed attributes to.
-     * @param nAttrs the number of attributes in m_attributes 
+     * @param nAttrs the number of attributes in m_attributes
      * to be processed
      *
      * @throws java.io.IOException
@@ -2136,7 +2124,7 @@ abstract public class ToStream extends SerializerBase
                     // 0xD   CARRIAGE RETURN
                     //
                     // We also cover 0x0 ... It isn't valid
-                    // but we will output "&#0;" 
+                    // but we will output "&#0;"
 
                     // The default will handle this just fine, but this
                     // is a little performance boost to handle the more
@@ -2182,10 +2170,6 @@ abstract public class ToStream extends SerializerBase
                     // just write it out
                     writer.write(ch);
                 }
-                else if (Encodings.isHighUTF16Surrogate(ch)) {
-                    writeUTF16Surrogate(ch, stringChars, i, len);
-                    i++; // process two input characters
-                }
                 else {
                     // This is a fallback plan, we should never get here
                     // but if the character wasn't previously handled
@@ -2223,7 +2207,7 @@ abstract public class ToStream extends SerializerBase
             return;
 
         // namespaces declared at the current depth are no longer valid
-        // so get rid of them    
+        // so get rid of them
         m_prefixMap.popNamespaces(m_elemContext.m_currentElemDepth, null);
 
         try
@@ -2326,7 +2310,7 @@ abstract public class ToStream extends SerializerBase
      * @param shouldFlush true if any open tags need to be closed first, this
      * will impact which element the mapping applies to (open parent, or its up
      * comming child)
-     * @return returns true if the call made a change to the current 
+     * @return returns true if the call made a change to the current
      * namespace information, false if it did not change anything, e.g. if the
      * prefix/namespace mapping was already in scope from before.
      *
@@ -2788,7 +2772,7 @@ abstract public class ToStream extends SerializerBase
     /**
      * Adds a URI/LocalName pair of strings to the list.
      *
-     * @param URI_and_localName String of the form "{uri}local" or "local" 
+     * @param URI_and_localName String of the form "{uri}local" or "local"
      *
      * @return a QName object
      */
@@ -2816,7 +2800,7 @@ abstract public class ToStream extends SerializerBase
 
     /**
      * Remembers the cdata sections specified in the cdata-section-elements.
-     * The "official way to set URI and localName pairs. 
+     * The "official way to set URI and localName pairs.
      * This method should be used by both Xalan and XSLTC.
      *
      * @param URI_and_localNames a vector of pairs of Strings (URI/local)
@@ -2857,9 +2841,9 @@ abstract public class ToStream extends SerializerBase
      * Makes sure that the namespace URI for the given qualified attribute name
      * is declared.
      * @param ns the namespace URI
-     * @param rawName the qualified name 
+     * @param rawName the qualified name
      * @return returns null if no action is taken, otherwise it returns the
-     * prefix used in declaring the namespace. 
+     * prefix used in declaring the namespace.
      * @throws SAXException
      */
     protected String ensureAttributesNamespaceIsDeclared(
@@ -2881,7 +2865,7 @@ abstract public class ToStream extends SerializerBase
 
             if (index > 0)
             {
-                // we have a prefix, lets see if it maps to a namespace 
+                // we have a prefix, lets see if it maps to a namespace
                 String uri = m_prefixMap.lookupNamespace(prefixFromRawName);
                 if (uri != null && uri.equals(ns))
                 {
@@ -3017,7 +3001,7 @@ abstract public class ToStream extends SerializerBase
      * @param type the type of the attribute (probably CDATA)
      * @param value the value of the attribute
      * @param xslAttribute true if this attribute is coming from an xsl:attribute element.
-     * @return true if the attribute value was added, 
+     * @return true if the attribute value was added,
      * false if the attribute already existed and the value was
      * replaced with the new value.
      */
@@ -3170,14 +3154,14 @@ abstract public class ToStream extends SerializerBase
                         new ToStream.WritertoStringBuffer(sb);
 
                     processAttributes(writer, nAttrs);
-                    // Don't clear the attributes! 
+                    // Don't clear the attributes!
                     // We only want to see what would be written out
                     // at this point, we don't want to loose them.
                 }
                 sb.append('>');  // the potential > after the attributes.
                 // convert the StringBuffer to a char array and
                 // emit the trace event that these characters "might"
-                // be written                
+                // be written
                 char ch[] = sb.toString().toCharArray();
                 m_tracer.fireGenerateEvent(
                     SerializerTrace.EVENTTYPE_OUTPUT_PSEUDO_CHARACTERS,
@@ -3253,8 +3237,8 @@ abstract public class ToStream extends SerializerBase
 
     }
     /**
-     * Try's to reset the super class and reset this class for 
-     * re-use, so that you don't need to create a new serializer 
+     * Try's to reset the super class and reset this class for
+     * re-use, so that you don't need to create a new serializer
      * (mostly for performance reasons).
      *
      * @return true if the class was successfuly reset.
@@ -3318,7 +3302,7 @@ abstract public class ToStream extends SerializerBase
     /**
      * Simple stack for boolean values.
      *
-     * This class is a copy of the one in org.apache.xml.utils. 
+     * This class is a copy of the one in org.apache.xml.utils.
      * It exists to cut the serializers dependancy on that package.
      * A minor changes from that package are:
      * doesn't implement Clonable
@@ -3497,8 +3481,8 @@ abstract public class ToStream extends SerializerBase
     // Implement DTDHandler
     /**
      * If this method is called, the serializer is used as a
-     * DTDHandler, which changes behavior how the serializer 
-     * handles document entities. 
+     * DTDHandler, which changes behavior how the serializer
+     * handles document entities.
      * @see org.xml.sax.DTDHandler#notationDecl(java.lang.String, java.lang.String, java.lang.String)
      */
     public void notationDecl(String name, String pubID, String sysID) throws SAXException {
@@ -3527,8 +3511,8 @@ abstract public class ToStream extends SerializerBase
 
     /**
      * If this method is called, the serializer is used as a
-     * DTDHandler, which changes behavior how the serializer 
-     * handles document entities. 
+     * DTDHandler, which changes behavior how the serializer
+     * handles document entities.
      * @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
      */
     public void unparsedEntityDecl(String name, String pubID, String sysID, String notationName) throws SAXException {
@@ -3558,7 +3542,7 @@ abstract public class ToStream extends SerializerBase
     }
 
     /**
-     * A private helper method to output the 
+     * A private helper method to output the
      * @throws SAXException
      * @throws IOException
      */


[tomee] 03/04: TOMEE-2938 Fix encoding in Xalan and Serializer

Posted by jl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jlmonteiro pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit c01cff23dd9e098fe8d204796592e0de5fa6a5c8
Author: Jean-Louis Monteiro <jl...@tomitribe.com>
AuthorDate: Tue Dec 8 14:56:39 2020 +0100

    TOMEE-2938 Fix encoding in Xalan and Serializer
---
 .../org/apache/xml/serializer/ToHTMLStream.java    | 26 +++++++++++++---------
 .../java/org/apache/xml/serializer/ToStream.java   | 18 +++++++++++++++
 2 files changed, 33 insertions(+), 11 deletions(-)

diff --git a/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java
index 0d501ef..9602d8e 100644
--- a/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java
+++ b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToHTMLStream.java
@@ -1289,6 +1289,13 @@ public class ToHTMLStream extends ToStream
                 {
                     writer.write(ch);
                 }
+                else if (Encodings.isHighUTF16Surrogate(ch)) {
+                    writeUTF16Surrogate(ch, chars, i, end);
+                    i++;
+                    // two input characters processed
+                    // this increments by one and the for()
+                    // loop itself increments by another one.
+                }
                 else
                 {
                     writer.write("&#");
@@ -1435,20 +1442,17 @@ public class ToHTMLStream extends ToStream
                 {
                     i = pos - 1;
                 }
-                else
-                {
-                    if (Encodings.isHighUTF16Surrogate(ch))
-                    {
-
-                        writeUTF16Surrogate(ch, chars, i, end);
-                        i++; // two input characters processed
-                        // this increments by one and the for()
-                        // loop itself increments by another one.
-                    }
+                else if (Encodings.isHighUTF16Surrogate(ch)) {
+                    writeUTF16Surrogate(ch, chars, i, end);
+                    i++;
+                    // two input characters processed
+                    // this increments by one and the for()
+                    // loop itself increments by another one.
 
                     // The next is kind of a hack to keep from escaping in the case
                     // of Shift_JIS and the like.
-
+                }
+                else {
                     /*
                     else if ((ch < m_maxCharacter) && (m_maxCharacter == 0xFFFF)
                     && (ch != 160))
diff --git a/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java
index 3389567..f54a03c 100644
--- a/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java
+++ b/tomee/tomee-webapp/src/patch/java/org/apache/xml/serializer/ToStream.java
@@ -1600,6 +1600,20 @@ abstract public class ToStream extends SerializerBase
                         // just leave it get added on to the clean characters
 
                     }
+                    else if (Encodings.isHighUTF16Surrogate(ch) &&
+                               i < end - 1 &&
+                               Encodings.isLowUTF16Surrogate(chars[i + 1])) {
+                        // So, this is a (valid) surrogate pair
+                        if (!m_encodingInfo.isInEncoding(ch, chars[i + 1])) {
+                            int codepoint = Encodings.toCodePoint(ch, chars[i + 1]);
+                            writeOutCleanChars(chars, i, lastDirtyCharProcessed);
+                            writer.write("&#");
+                            writer.write(Integer.toString(codepoint));
+                            writer.write(';');
+                            lastDirtyCharProcessed = i + 1;
+                        }
+                        i++; // skip the low surrogate, too
+                    }
                     else {
                         // This is a fallback plan, we should never get here
                         // but if the character wasn't previously handled
@@ -2170,6 +2184,10 @@ abstract public class ToStream extends SerializerBase
                     // just write it out
                     writer.write(ch);
                 }
+                else if (Encodings.isHighUTF16Surrogate(ch)) {
+                    writeUTF16Surrogate(ch, stringChars, i, len);
+                    i++; // process two input characters
+                }
                 else {
                     // This is a fallback plan, we should never get here
                     // but if the character wasn't previously handled


[tomee] 04/04: TOMEE-2938 Properly configure patch plugin

Posted by jl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jlmonteiro pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit dff0f6b4b6e1c64322f28a4c7a96b36307707261
Author: Jean-Louis Monteiro <jl...@tomitribe.com>
AuthorDate: Tue Dec 8 15:10:10 2020 +0100

    TOMEE-2938 Properly configure patch plugin
---
 arquillian/arquillian-tomee-webapp-remote/pom.xml | 4 ----
 tomee/tomee-webapp/pom.xml                        | 2 +-
 2 files changed, 1 insertion(+), 5 deletions(-)

diff --git a/arquillian/arquillian-tomee-webapp-remote/pom.xml b/arquillian/arquillian-tomee-webapp-remote/pom.xml
index aeccbb9..c61bdb7 100644
--- a/arquillian/arquillian-tomee-webapp-remote/pom.xml
+++ b/arquillian/arquillian-tomee-webapp-remote/pom.xml
@@ -252,10 +252,6 @@
           <groupId>${project.groupId}</groupId>
         </exclusion>
         <exclusion>
-          <artifactId>openejb-bval</artifactId>
-          <groupId>org.apache.openejb.patch</groupId>
-        </exclusion>
-        <exclusion>
           <artifactId>mbean-annotation-api</artifactId>
           <groupId>${project.groupId}</groupId>
         </exclusion>
diff --git a/tomee/tomee-webapp/pom.xml b/tomee/tomee-webapp/pom.xml
index 122d84c..5cf9e4a 100644
--- a/tomee/tomee-webapp/pom.xml
+++ b/tomee/tomee-webapp/pom.xml
@@ -145,7 +145,7 @@
         <artifactId>tomee-patch-plugin</artifactId>
         <version>0.1</version>
         <configuration>
-          <select>apache-tomee.*\.zip</select>
+          <select>tomee-webapp.*\.war</select>
         </configuration>
         <executions>
           <execution>