changeset 43123:dd12865718f3

8169631: [JAXP] XALAN: transformation of XML via namespace-unaware SAX input yields a different result than namespace-unaware DOM input Reviewed-by: joehw
author clanger
date Mon, 16 Jan 2017 15:44:30 +0100
parents cf6fa122e5cb
children f524c12f3783
files jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/DOM2SAX.java jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/sax2dtm/SAX2DTM.java jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/sax2dtm/SAX2DTM2.java jaxp/test/javax/xml/jaxp/unittest/transform/TransformerTest.java
diffstat 4 files changed, 906 insertions(+), 1001 deletions(-) [+]
line wrap: on
line diff
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/DOM2SAX.java	Fri Jan 13 01:35:35 2017 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/DOM2SAX.java	Mon Jan 16 15:44:30 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,20 +17,16 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: DOM2SAX.java,v 1.2.4.1 2005/09/06 11:52:46 pvedula Exp $
- */
-
 
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
 import com.sun.org.apache.xalan.internal.xsltc.dom.SAXImpl;
 import com.sun.org.apache.xalan.internal.xsltc.runtime.BasisLibrary;
 import java.io.IOException;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Stack;
-import java.util.Vector;
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
 import org.xml.sax.ContentHandler;
@@ -58,7 +54,7 @@
     private ContentHandler _sax = null;
     private LexicalHandler _lex = null;
     private SAXImpl _saxImpl = null;
-    private Map<String, Stack> _nsPrefixes = new HashMap<>();
+    private Map<String, Stack<String>> _nsPrefixes = new HashMap<>();
 
     public DOM2SAX(Node root) {
         _dom = root;
@@ -73,7 +69,7 @@
     {
         _sax = handler;
         if (handler instanceof LexicalHandler) {
-            _lex = (LexicalHandler) handler;
+            _lex = (LexicalHandler)handler;
         }
 
         if (handler instanceof SAXImpl) {
@@ -90,25 +86,22 @@
         throws SAXException
     {
         boolean pushed = true;
-        Stack uriStack = _nsPrefixes.get(prefix);
+        Stack<String> uriStack = _nsPrefixes.get(prefix);
 
         if (uriStack != null) {
             if (uriStack.isEmpty()) {
                 _sax.startPrefixMapping(prefix, uri);
                 uriStack.push(uri);
-            }
-            else {
-                final String lastUri = (String) uriStack.peek();
+            } else {
+                final String lastUri = uriStack.peek();
                 if (!lastUri.equals(uri)) {
                     _sax.startPrefixMapping(prefix, uri);
                     uriStack.push(uri);
-                }
-                else {
+                } else {
                     pushed = false;
                 }
             }
-        }
-        else {
+        } else {
             _sax.startPrefixMapping(prefix, uri);
             _nsPrefixes.put(prefix, uriStack = new Stack());
             uriStack.push(uri);
@@ -123,7 +116,7 @@
     private void endPrefixMapping(String prefix)
         throws SAXException
     {
-        final Stack uriStack = _nsPrefixes.get(prefix);
+        final Stack<String> uriStack = _nsPrefixes.get(prefix);
 
         if (uriStack != null) {
             _sax.endPrefixMapping(prefix);
@@ -131,22 +124,6 @@
         }
     }
 
-    /**
-     * If the DOM was created using a DOM 1.0 API, the local name may be
-     * null. If so, get the local name from the qualified name before
-     * generating the SAX event.
-     */
-    private static String getLocalName(Node node) {
-        final String localName = node.getLocalName();
-
-        if (localName == null) {
-            final String qname = node.getNodeName();
-            final int col = qname.lastIndexOf(':');
-            return (col > 0) ? qname.substring(col + 1) : qname;
-        }
-        return localName;
-    }
-
     public void parse(InputSource unused) throws IOException, SAXException {
         parse(_dom);
     }
@@ -173,8 +150,8 @@
      * declarations.
      */
     private void parse(Node node) throws IOException, SAXException {
-        Node first = null;
-        if (node == null) return;
+        if (node == null)
+            return;
 
         switch (node.getNodeType()) {
         case Node.ATTRIBUTE_NODE:         // handled by ELEMENT_NODE
@@ -198,7 +175,6 @@
                 _sax.characters(cdata.toCharArray(), 0, cdata.length());
             }
             break;
-
         case Node.COMMENT_NODE:           // should be handled!!!
             if (_lex != null) {
                 final String value = node.getNodeValue();
@@ -216,10 +192,9 @@
             }
             _sax.endDocument();
             break;
-
         case Node.ELEMENT_NODE:
             String prefix;
-            Vector pushedPrefixes = new Vector();
+            ArrayList<String> pushedPrefixes = new ArrayList<>();
             final AttributesImpl attrs = new AttributesImpl();
             final NamedNodeMap map = node.getAttributes();
             final int length = map.getLength();
@@ -235,7 +210,7 @@
                     final int colon = qnameAttr.lastIndexOf(':');
                     prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING;
                     if (startPrefixMapping(prefix, uriAttr)) {
-                        pushedPrefixes.addElement(prefix);
+                        pushedPrefixes.add(prefix);
                     }
                 }
             }
@@ -248,27 +223,25 @@
                 // Ignore NS declarations here
                 if (!qnameAttr.startsWith(XMLNS_PREFIX)) {
                     final String uriAttr = attr.getNamespaceURI();
-                    final String localNameAttr = getLocalName(attr);
 
                     // Uri may be implicitly declared
                     if (uriAttr != null) {
                         final int colon = qnameAttr.lastIndexOf(':');
                         if (colon > 0) {
                             prefix = qnameAttr.substring(0, colon);
-                        }
-                        else {
+                        } else {
                             // If no prefix for this attr, we need to create
                             // one because we cannot use the default ns
                             prefix = BasisLibrary.generatePrefix();
                             qnameAttr = prefix + ':' + qnameAttr;
                         }
                         if (startPrefixMapping(prefix, uriAttr)) {
-                            pushedPrefixes.addElement(prefix);
+                            pushedPrefixes.add(prefix);
                         }
                     }
 
                     // Add attribute to list
-                    attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr),
+                    attrs.addAttribute(attr.getNamespaceURI(), attr.getLocalName(),
                         qnameAttr, "CDATA", attr.getNodeValue());
                 }
             }
@@ -276,22 +249,21 @@
             // Now process the element itself
             final String qname = node.getNodeName();
             final String uri = node.getNamespaceURI();
-            final String localName = getLocalName(node);
+            final String localName = node.getLocalName();
 
-            // Uri may be implicitly declared
+            // URI may be implicitly declared
             if (uri != null) {
                 final int colon = qname.lastIndexOf(':');
                 prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING;
                 if (startPrefixMapping(prefix, uri)) {
-                    pushedPrefixes.addElement(prefix);
+                    pushedPrefixes.add(prefix);
                 }
             }
 
             // Generate SAX event to start element
             if (_saxImpl != null) {
                 _saxImpl.startElement(uri, localName, qname, attrs, node);
-            }
-            else {
+            } else {
                 _sax.startElement(uri, localName, qname, attrs);
             }
 
@@ -308,15 +280,13 @@
             // Generate endPrefixMapping() for all pushed prefixes
             final int nPushedPrefixes = pushedPrefixes.size();
             for (int i = 0; i < nPushedPrefixes; i++) {
-                endPrefixMapping((String) pushedPrefixes.elementAt(i));
+                endPrefixMapping(pushedPrefixes.get(i));
             }
             break;
-
         case Node.PROCESSING_INSTRUCTION_NODE:
             _sax.processingInstruction(node.getNodeName(),
                                        node.getNodeValue());
             break;
-
         case Node.TEXT_NODE:
             final String data = node.getNodeValue();
             _sax.characters(data.toCharArray(), 0, data.length());
@@ -449,36 +419,4 @@
     public String getSystemId() {
         return null;
     }
-
-    // Debugging
-    private String getNodeTypeFromCode(short code) {
-        String retval = null;
-        switch (code) {
-        case Node.ATTRIBUTE_NODE :
-            retval = "ATTRIBUTE_NODE"; break;
-        case Node.CDATA_SECTION_NODE :
-            retval = "CDATA_SECTION_NODE"; break;
-        case Node.COMMENT_NODE :
-            retval = "COMMENT_NODE"; break;
-        case Node.DOCUMENT_FRAGMENT_NODE :
-            retval = "DOCUMENT_FRAGMENT_NODE"; break;
-        case Node.DOCUMENT_NODE :
-            retval = "DOCUMENT_NODE"; break;
-        case Node.DOCUMENT_TYPE_NODE :
-            retval = "DOCUMENT_TYPE_NODE"; break;
-        case Node.ELEMENT_NODE :
-            retval = "ELEMENT_NODE"; break;
-        case Node.ENTITY_NODE :
-            retval = "ENTITY_NODE"; break;
-        case Node.ENTITY_REFERENCE_NODE :
-            retval = "ENTITY_REFERENCE_NODE"; break;
-        case Node.NOTATION_NODE :
-            retval = "NOTATION_NODE"; break;
-        case Node.PROCESSING_INSTRUCTION_NODE :
-            retval = "PROCESSING_INSTRUCTION_NODE"; break;
-        case Node.TEXT_NODE:
-            retval = "TEXT_NODE"; break;
-        }
-        return retval;
-    }
 }
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/sax2dtm/SAX2DTM.java	Fri Jan 13 01:35:35 2017 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/sax2dtm/SAX2DTM.java	Mon Jan 16 15:44:30 2017 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,14 +17,18 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: SAX2DTM.java,v 1.2.4.1 2005/09/15 08:15:11 suresh_emailid Exp $
- */
+
 package com.sun.org.apache.xml.internal.dtm.ref.sax2dtm;
 
-
-import com.sun.org.apache.xml.internal.dtm.*;
-import com.sun.org.apache.xml.internal.dtm.ref.*;
+import com.sun.org.apache.xml.internal.dtm.DTM;
+import com.sun.org.apache.xml.internal.dtm.DTMManager;
+import com.sun.org.apache.xml.internal.dtm.DTMWSFilter;
+import com.sun.org.apache.xml.internal.dtm.ref.DTMDefaultBaseIterators;
+import com.sun.org.apache.xml.internal.dtm.ref.DTMManagerDefault;
+import com.sun.org.apache.xml.internal.dtm.ref.DTMStringPool;
+import com.sun.org.apache.xml.internal.dtm.ref.DTMTreeWalker;
+import com.sun.org.apache.xml.internal.dtm.ref.IncrementalSAXSource;
+import com.sun.org.apache.xml.internal.dtm.ref.NodeLocator;
 import com.sun.org.apache.xml.internal.res.XMLErrorResources;
 import com.sun.org.apache.xml.internal.res.XMLMessages;
 import com.sun.org.apache.xml.internal.utils.FastStringBuffer;
@@ -36,13 +40,23 @@
 import com.sun.org.apache.xml.internal.utils.WrappedRuntimeException;
 import com.sun.org.apache.xml.internal.utils.XMLString;
 import com.sun.org.apache.xml.internal.utils.XMLStringFactory;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Vector;
 import javax.xml.transform.Source;
 import javax.xml.transform.SourceLocator;
-import org.xml.sax.*;
-import org.xml.sax.ext.*;
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.ext.DeclHandler;
+import org.xml.sax.ext.LexicalHandler;
 
 /**
  * This class implements a DTM that tends to be optimized more for speed than
@@ -82,7 +96,6 @@
    *
    * Made protected rather than private so SAX2RTFDTM can access it.
    */
-  //private FastStringBuffer m_chars = new FastStringBuffer(13, 13);
   protected FastStringBuffer m_chars;
 
   /** This vector holds offset and length data.
@@ -102,8 +115,7 @@
   /** Namespace support, only relevent at construction time.
    * Made protected rather than private so SAX2RTFDTM can access it.
    */
-  transient protected java.util.Vector m_prefixMappings =
-    new java.util.Vector();
+  transient protected Vector<String> m_prefixMappings = new Vector<>();
 
   /** Namespace support, only relevent at construction time.
    * Made protected rather than private so SAX2RTFDTM can access it.
@@ -164,7 +176,7 @@
    * Vector of entities.  Each record is composed of four Strings:
    *  publicId, systemID, notationName, and name.
    */
-  private Vector m_entities = null;
+  private ArrayList<String> m_entities = null;
 
   /** m_entities public ID offset. */
   private static final int ENTITY_FIELD_PUBLICID = 0;
@@ -196,13 +208,15 @@
    */
   protected boolean m_useSourceLocationProperty = false;
 
-   /** Made protected for access by SAX2RTFDTM.
+  /** Made protected for access by SAX2RTFDTM.
    */
   protected StringVector m_sourceSystemId;
-   /** Made protected for access by SAX2RTFDTM.
+
+  /** Made protected for access by SAX2RTFDTM.
    */
   protected IntVector m_sourceLine;
-   /** Made protected for access by SAX2RTFDTM.
+
+  /** Made protected for access by SAX2RTFDTM.
    */
   protected IntVector m_sourceColumn;
 
@@ -252,23 +266,19 @@
                  boolean usePrevsib,
                  boolean newNameTable)
   {
-
     super(mgr, source, dtmIdentity, whiteSpaceFilter,
           xstringfactory, doIndexing, blocksize, usePrevsib, newNameTable);
 
     // %OPT% Use smaller sizes for all internal storage units when
     // the blocksize is small. This reduces the cost of creating an RTF.
-    if (blocksize <= 64)
-    {
+    if (blocksize <= 64) {
       m_data = new SuballocatedIntVector(blocksize, DEFAULT_NUMBLOCKS_SMALL);
       m_dataOrQName = new SuballocatedIntVector(blocksize, DEFAULT_NUMBLOCKS_SMALL);
       m_valuesOrPrefixes = new DTMStringPool(16);
       m_chars = new FastStringBuffer(7, 10);
       m_contextIndexes = new IntStack(4);
       m_parents = new IntStack(4);
-    }
-    else
-    {
+    } else {
       m_data = new SuballocatedIntVector(blocksize, DEFAULT_NUMBLOCKS);
       m_dataOrQName = new SuballocatedIntVector(blocksize, DEFAULT_NUMBLOCKS);
       m_valuesOrPrefixes = new DTMStringPool();
@@ -289,7 +299,7 @@
     // m_useSourceLocationProperty=com.sun.org.apache.xalan.internal.processor.TransformerFactoryImpl.m_source_location;
     m_useSourceLocationProperty = mgr.getSource_location();
     m_sourceSystemId = (m_useSourceLocationProperty) ? new StringVector() : null;
-        m_sourceLine = (m_useSourceLocationProperty) ?  new IntVector() : null;
+    m_sourceLine = (m_useSourceLocationProperty) ?  new IntVector() : null;
     m_sourceColumn = (m_useSourceLocationProperty) ?  new IntVector() : null;
   }
 
@@ -297,8 +307,7 @@
    * Set whether information about document source location
    * should be maintained or not.
    */
-  public void setUseSourceLocation(boolean useSourceLocation)
-  {
+  public void setUseSourceLocation(boolean useSourceLocation) {
     m_useSourceLocationProperty = useSourceLocation;
   }
 
@@ -309,17 +318,14 @@
    *
    * @return The data or qualified name, or DTM.NULL.
    */
-  protected int _dataOrQName(int identity)
-  {
-
+  protected int _dataOrQName(int identity) {
     if (identity < m_size)
       return m_dataOrQName.elementAt(identity);
 
     // Check to see if the information requested has been processed, and,
     // if not, advance the iterator until we the information has been
     // processed.
-    while (true)
-    {
+    while (true) {
       boolean isMore = nextNode();
 
       if (!isMore)
@@ -332,8 +338,7 @@
   /**
    * Ask the CoRoutine parser to doTerminate and clear the reference.
    */
-  public void clearCoRoutine()
-  {
+  public void clearCoRoutine() {
     clearCoRoutine(true);
   }
 
@@ -344,11 +349,8 @@
    * @param callDoTerminate true of doTerminate should be called on the
    * coRoutine parser.
    */
-  public void clearCoRoutine(boolean callDoTerminate)
-  {
-
-    if (null != m_incrementalSAXSource)
-    {
+  public void clearCoRoutine(boolean callDoTerminate) {
+    if (null != m_incrementalSAXSource) {
       if (callDoTerminate)
         m_incrementalSAXSource.deliverMoreNodes(false);
 
@@ -368,9 +370,7 @@
    * @param incrementalSAXSource The parser that we want to recieve events from
    * on demand.
    */
-  public void setIncrementalSAXSource(IncrementalSAXSource incrementalSAXSource)
-  {
-
+  public void setIncrementalSAXSource(IncrementalSAXSource incrementalSAXSource) {
     // Establish coroutine link so we can request more data
     //
     // Note: It's possible that some versions of IncrementalSAXSource may
@@ -406,11 +406,9 @@
    * Note that IncrementalSAXSource_Filter is package private, hence
    * it can be statically referenced using instanceof (CR 6537912).
    */
-  public ContentHandler getContentHandler()
-  {
-
-    if (m_incrementalSAXSource.getClass()
-        .getName().equals("com.sun.org.apache.xml.internal.dtm.ref.IncrementalSAXSource_Filter"))
+  public ContentHandler getContentHandler() {
+    if (m_incrementalSAXSource.getClass().getName()
+        .equals("com.sun.org.apache.xml.internal.dtm.ref.IncrementalSAXSource_Filter"))
       return (ContentHandler) m_incrementalSAXSource;
     else
       return this;
@@ -429,11 +427,9 @@
    * Note that IncrementalSAXSource_Filter is package private, hence
    * it can be statically referenced using instanceof (CR 6537912).
    */
-  public LexicalHandler getLexicalHandler()
-  {
-
-    if (m_incrementalSAXSource.getClass()
-        .getName().equals("com.sun.org.apache.xml.internal.dtm.ref.IncrementalSAXSource_Filter"))
+  public LexicalHandler getLexicalHandler() {
+    if (m_incrementalSAXSource.getClass().getName()
+        .equals("com.sun.org.apache.xml.internal.dtm.ref.IncrementalSAXSource_Filter"))
       return (LexicalHandler) m_incrementalSAXSource;
     else
       return this;
@@ -444,8 +440,7 @@
    *
    * @return null if this model doesn't respond to SAX entity ref events.
    */
-  public EntityResolver getEntityResolver()
-  {
+  public EntityResolver getEntityResolver() {
     return this;
   }
 
@@ -454,8 +449,7 @@
    *
    * @return null if this model doesn't respond to SAX dtd events.
    */
-  public DTDHandler getDTDHandler()
-  {
+  public DTDHandler getDTDHandler() {
     return this;
   }
 
@@ -464,8 +458,7 @@
    *
    * @return null if this model doesn't respond to SAX error events.
    */
-  public ErrorHandler getErrorHandler()
-  {
+  public ErrorHandler getErrorHandler() {
     return this;
   }
 
@@ -474,8 +467,7 @@
    *
    * @return null if this model doesn't respond to SAX Decl events.
    */
-  public DeclHandler getDeclHandler()
-  {
+  public DeclHandler getDeclHandler() {
     return this;
   }
 
@@ -485,8 +477,7 @@
    * transformation and the parse run simultaneously. Guidance to the
    * DTMManager.
    */
-  public boolean needsTwoThreads()
-  {
+  public boolean needsTwoThreads() {
     return null != m_incrementalSAXSource;
   }
 
@@ -509,9 +500,8 @@
    */
   public void dispatchCharactersEvents(int nodeHandle, ContentHandler ch,
                                        boolean normalize)
-          throws SAXException
+    throws SAXException
   {
-
     int identity = makeNodeIdentity(nodeHandle);
 
     if (identity == DTM.NULL)
@@ -519,8 +509,7 @@
 
     int type = _type(identity);
 
-    if (isTextType(type))
-    {
+    if (isTextType(type)) {
       int dataIndex = m_dataOrQName.elementAt(identity);
       int offset = m_data.elementAt(dataIndex);
       int length = m_data.elementAt(dataIndex + 1);
@@ -529,13 +518,10 @@
         m_chars.sendNormalizedSAXcharacters(ch, offset, length);
       else
         m_chars.sendSAXcharacters(ch, offset, length);
-    }
-    else
-    {
+    } else {
       int firstChild = _firstch(identity);
 
-      if (DTM.NULL != firstChild)
-      {
+      if (DTM.NULL != firstChild) {
         int offset = -1;
         int length = 0;
         int startNode = identity;
@@ -545,12 +531,10 @@
         do {
           type = _type(identity);
 
-          if (isTextType(type))
-          {
+          if (isTextType(type)) {
             int dataIndex = _dataOrQName(identity);
 
-            if (-1 == offset)
-            {
+            if (-1 == offset) {
               offset = m_data.elementAt(dataIndex);
             }
 
@@ -560,36 +544,31 @@
           identity = getNextNodeIdentity(identity);
         } while (DTM.NULL != identity && (_parent(identity) >= startNode));
 
-        if (length > 0)
-        {
+        if (length > 0) {
           if(normalize)
             m_chars.sendNormalizedSAXcharacters(ch, offset, length);
           else
             m_chars.sendSAXcharacters(ch, offset, length);
         }
-      }
-      else if(type != DTM.ELEMENT_NODE)
-      {
+      } else if(type != DTM.ELEMENT_NODE) {
         int dataIndex = _dataOrQName(identity);
 
-        if (dataIndex < 0)
-        {
+        if (dataIndex < 0) {
           dataIndex = -dataIndex;
           dataIndex = m_data.elementAt(dataIndex + 1);
         }
 
         String str = m_valuesOrPrefixes.indexToString(dataIndex);
 
-          if(normalize)
-            FastStringBuffer.sendNormalizedSAXcharacters(str.toCharArray(),
-                                                         0, str.length(), ch);
-          else
-            ch.characters(str.toCharArray(), 0, str.length());
+        if(normalize)
+          FastStringBuffer.sendNormalizedSAXcharacters(str.toCharArray(),
+                                                       0, str.length(), ch);
+        else
+          ch.characters(str.toCharArray(), 0, str.length());
       }
     }
   }
 
-
   /**
    * Given a node handle, return its DOM-style node name. This will
    * include names such as #text or #document.
@@ -599,39 +578,29 @@
    * %REVIEW% Document when empty string is possible...
    * %REVIEW-COMMENT% It should never be empty, should it?
    */
-  public String getNodeName(int nodeHandle)
-  {
-
+  public String getNodeName(int nodeHandle) {
     int expandedTypeID = getExpandedTypeID(nodeHandle);
     // If just testing nonzero, no need to shift...
     int namespaceID = m_expandedNameTable.getNamespaceID(expandedTypeID);
 
-    if (0 == namespaceID)
-    {
+    if (0 == namespaceID) {
       // Don't retrieve name until/unless needed
       // String name = m_expandedNameTable.getLocalName(expandedTypeID);
       int type = getNodeType(nodeHandle);
 
-      if (type == DTM.NAMESPACE_NODE)
-      {
+      if (type == DTM.NAMESPACE_NODE) {
         if (null == m_expandedNameTable.getLocalName(expandedTypeID))
           return "xmlns";
         else
           return "xmlns:" + m_expandedNameTable.getLocalName(expandedTypeID);
-      }
-      else if (0 == m_expandedNameTable.getLocalNameID(expandedTypeID))
-      {
+      } else if (0 == m_expandedNameTable.getLocalNameID(expandedTypeID)) {
         return m_fixednames[type];
-      }
-      else
+      } else
         return m_expandedNameTable.getLocalName(expandedTypeID);
-    }
-    else
-    {
+    } else {
       int qnameIndex = m_dataOrQName.elementAt(makeNodeIdentity(nodeHandle));
 
-      if (qnameIndex < 0)
-      {
+      if (qnameIndex < 0) {
         qnameIndex = -qnameIndex;
         qnameIndex = m_data.elementAt(qnameIndex);
       }
@@ -648,27 +617,21 @@
    * @param nodeHandle the id of the node.
    * @return String Name of this node, which may be an empty string.
    */
-  public String getNodeNameX(int nodeHandle)
-  {
-
+  public String getNodeNameX(int nodeHandle) {
     int expandedTypeID = getExpandedTypeID(nodeHandle);
     int namespaceID = m_expandedNameTable.getNamespaceID(expandedTypeID);
 
-    if (0 == namespaceID)
-    {
+    if (namespaceID == 0) {
       String name = m_expandedNameTable.getLocalName(expandedTypeID);
 
       if (name == null)
         return "";
       else
         return name;
-    }
-    else
-    {
+    } else {
       int qnameIndex = m_dataOrQName.elementAt(makeNodeIdentity(nodeHandle));
 
-      if (qnameIndex < 0)
-      {
+      if (qnameIndex < 0) {
         qnameIndex = -qnameIndex;
         qnameIndex = m_data.elementAt(qnameIndex);
       }
@@ -686,11 +649,9 @@
    * @return <code>true</code> if the attribute was specified;
    *         <code>false</code> if it was defaulted.
    */
-  public boolean isAttributeSpecified(int attributeHandle)
-  {
-
+  public boolean isAttributeSpecified(int attributeHandle) {
     // I'm not sure if I want to do anything with this...
-    return true;  // ??
+    return true; // ??
   }
 
   /**
@@ -701,9 +662,7 @@
    *
    * @return the system identifier String object, or null if there is none.
    */
-  public String getDocumentTypeDeclarationSystemIdentifier()
-  {
-
+  public String getDocumentTypeDeclarationSystemIdentifier() {
     /** @todo: implement this com.sun.org.apache.xml.internal.dtm.DTMDefaultBase abstract method */
     error(XMLMessages.createXMLMessage(XMLErrorResources.ER_METHOD_NOT_SUPPORTED, null));//"Not yet supported!");
 
@@ -717,14 +676,11 @@
    * @param identity The node identity (index).
    * @return identity+1, or DTM.NULL.
    */
-  protected int getNextNodeIdentity(int identity)
-  {
-
+  protected int getNextNodeIdentity(int identity) {
     identity += 1;
 
-    while (identity >= m_size)
-    {
-      if (null == m_incrementalSAXSource)
+    while (identity >= m_size) {
+      if (m_incrementalSAXSource == null)
         return DTM.NULL;
 
       nextNode();
@@ -739,10 +695,10 @@
    * @param nodeHandle The node ID.
    * @param ch A non-null reference to a ContentHandler.
    *
-   * @throws org.xml.sax.SAXException
+   * @throws SAXException
    */
-  public void dispatchToEvents(int nodeHandle, org.xml.sax.ContentHandler ch)
-          throws org.xml.sax.SAXException
+  public void dispatchToEvents(int nodeHandle, ContentHandler ch)
+          throws SAXException
   {
 
     DTMTreeWalker treeWalker = m_walker;
@@ -1087,28 +1043,22 @@
    * @return String containing the URI of the Unparsed Entity, or an
    * empty string if no such entity exists.
    */
-  public String getUnparsedEntityURI(String name)
-  {
-
+  public String getUnparsedEntityURI(String name) {
     String url = "";
 
-    if (null == m_entities)
+    if (null == m_entities) {
       return url;
+    }
 
     int n = m_entities.size();
 
-    for (int i = 0; i < n; i += ENTITY_FIELDS_PER)
-    {
-      String ename = (String) m_entities.elementAt(i + ENTITY_FIELD_NAME);
+    for (int i = 0; i < n; i += ENTITY_FIELDS_PER) {
+      String ename = m_entities.get(i + ENTITY_FIELD_NAME);
 
-      if (null != ename && ename.equals(name))
-      {
-        String nname = (String) m_entities.elementAt(i
-                         + ENTITY_FIELD_NOTATIONNAME);
+      if (null != ename && ename.equals(name)) {
+        String nname = m_entities.get(i + ENTITY_FIELD_NOTATIONNAME);
 
-        if (null != nname)
-        {
-
+        if (null != nname) {
           // The draft says: "The XSLT processor may use the public
           // identifier to generate a URI for the entity instead of the URI
           // specified in the system identifier. If the XSLT processor does
@@ -1118,11 +1068,10 @@
           // the resource containing the entity declaration as the base
           // URI [RFC2396]."
           // So I'm falling a bit short here.
-          url = (String) m_entities.elementAt(i + ENTITY_FIELD_SYSTEMID);
+          url = m_entities.get(i + ENTITY_FIELD_SYSTEMID);
 
-          if (null == url)
-          {
-            url = (String) m_entities.elementAt(i + ENTITY_FIELD_PUBLICID);
+          if (null == url) {
+            url = m_entities.get(i + ENTITY_FIELD_PUBLICID);
           }
         }
 
@@ -1400,26 +1349,18 @@
    *
    * @return The prefix if there is one, or null.
    */
-  public String getPrefix(String qname, String uri)
-  {
-
+  public String getPrefix(String qname, String uri) {
     String prefix;
     int uriIndex = -1;
 
-    if (null != uri && uri.length() > 0)
-    {
+    if (null != uri && uri.length() > 0) {
+      do {
+        uriIndex = m_prefixMappings.indexOf(uri, ++uriIndex);
+      } while ((uriIndex & 0x01) == 0);
 
-      do
-      {
-        uriIndex = m_prefixMappings.indexOf(uri, ++uriIndex);
-      } while ( (uriIndex & 0x01) == 0);
-
-      if (uriIndex >= 0)
-      {
-        prefix = (String) m_prefixMappings.elementAt(uriIndex - 1);
-      }
-      else if (null != qname)
-      {
+      if (uriIndex >= 0) {
+        prefix = m_prefixMappings.elementAt(uriIndex - 1);
+      } else if (null != qname) {
         int indexOfNSSep = qname.indexOf(':');
 
         if (qname.equals("xmlns"))
@@ -1429,33 +1370,24 @@
         else
           prefix = (indexOfNSSep > 0)
                    ? qname.substring(0, indexOfNSSep) : null;
-      }
-      else
-      {
+      } else {
         prefix = null;
       }
-    }
-    else if (null != qname)
-    {
+    } else if (null != qname) {
       int indexOfNSSep = qname.indexOf(':');
 
-      if (indexOfNSSep > 0)
-      {
+      if (indexOfNSSep > 0) {
         if (qname.startsWith("xmlns:"))
           prefix = qname.substring(indexOfNSSep + 1);
         else
           prefix = qname.substring(0, indexOfNSSep);
-      }
-      else
-      {
+      } else {
         if (qname.equals("xmlns"))
           prefix = "";
         else
           prefix = null;
       }
-    }
-    else
-    {
+    } else {
       prefix = null;
     }
 
@@ -1470,38 +1402,31 @@
    *
    * @return The prefix if there is one, or null.
    */
-  public int getIdForNamespace(String uri)
-  {
-
+  public int getIdForNamespace(String uri) {
      return m_valuesOrPrefixes.stringToIndex(uri);
-
   }
 
-    /**
+  /**
    * Get a prefix either from the qname or from the uri mapping, or just make
    * one up!
    *
    * @return The prefix if there is one, or null.
    */
-  public String getNamespaceURI(String prefix)
-  {
-
+  public String getNamespaceURI(String prefix) {
     String uri = "";
     int prefixIndex = m_contextIndexes.peek() - 1 ;
 
-    if(null == prefix)
+    if (null == prefix) {
       prefix = "";
+    }
 
-      do
-      {
-        prefixIndex = m_prefixMappings.indexOf(prefix, ++prefixIndex);
-      } while ( (prefixIndex >= 0) && (prefixIndex & 0x01) == 0x01);
+    do {
+      prefixIndex = m_prefixMappings.indexOf(prefix, ++prefixIndex);
+    } while ((prefixIndex >= 0) && (prefixIndex & 0x01) == 0x01);
 
-      if (prefixIndex > -1)
-      {
-        uri = (String) m_prefixMappings.elementAt(prefixIndex + 1);
-      }
-
+    if (prefixIndex > -1) {
+      uri = m_prefixMappings.elementAt(prefixIndex + 1);
+    }
 
     return uri;
   }
@@ -1578,7 +1503,7 @@
    *         default behaviour.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.EntityResolver#resolveEntity
+   * @see EntityResolver#resolveEntity
    *
    * @throws SAXException
    */
@@ -1605,7 +1530,7 @@
    * @param systemId The notation system identifier.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.DTDHandler#notationDecl
+   * @see DTDHandler#notationDecl
    *
    * @throws SAXException
    */
@@ -1630,41 +1555,35 @@
    * @param notationName The name of the associated notation.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.DTDHandler#unparsedEntityDecl
+   * @see DTDHandler#unparsedEntityDecl
    *
    * @throws SAXException
    */
-  public void unparsedEntityDecl(
-          String name, String publicId, String systemId, String notationName)
-            throws SAXException
+  public void unparsedEntityDecl(String name, String publicId, String systemId,
+                                 String notationName) throws SAXException
   {
-
-    if (null == m_entities)
-    {
-      m_entities = new Vector();
+    if (null == m_entities) {
+      m_entities = new ArrayList<>();
     }
 
-    try
-    {
+    try {
       systemId = SystemIDResolver.getAbsoluteURI(systemId,
                                                  getDocumentBaseURI());
-    }
-    catch (Exception e)
-    {
-      throw new org.xml.sax.SAXException(e);
+    } catch (Exception e) {
+      throw new SAXException(e);
     }
 
     //  private static final int ENTITY_FIELD_PUBLICID = 0;
-    m_entities.addElement(publicId);
+    m_entities.add(publicId);
 
     //  private static final int ENTITY_FIELD_SYSTEMID = 1;
-    m_entities.addElement(systemId);
+    m_entities.add(systemId);
 
     //  private static final int ENTITY_FIELD_NOTATIONNAME = 2;
-    m_entities.addElement(notationName);
+    m_entities.add(notationName);
 
     //  private static final int ENTITY_FIELD_NAME = 3;
-    m_entities.addElement(name);
+    m_entities.add(name);
   }
 
   ////////////////////////////////////////////////////////////////////
@@ -1679,8 +1598,8 @@
    * with other document events.</p>
    *
    * @param locator A locator for all SAX document events.
-   * @see org.xml.sax.ContentHandler#setDocumentLocator
-   * @see org.xml.sax.Locator
+   * @see ContentHandler#setDocumentLocator
+   * @see Locator
    */
   public void setDocumentLocator(Locator locator)
   {
@@ -1693,7 +1612,7 @@
    *
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#startDocument
+   * @see ContentHandler#startDocument
    */
   public void startDocument() throws SAXException
   {
@@ -1716,7 +1635,7 @@
    *
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#endDocument
+   * @see ContentHandler#endDocument
    */
   public void endDocument() throws SAXException
   {
@@ -1754,7 +1673,7 @@
    * @param uri The Namespace URI mapped to the prefix.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#startPrefixMapping
+   * @see ContentHandler#startPrefixMapping
    */
   public void startPrefixMapping(String prefix, String uri)
           throws SAXException
@@ -1780,7 +1699,7 @@
    * @param prefix The Namespace prefix being declared.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#endPrefixMapping
+   * @see ContentHandler#endPrefixMapping
    */
   public void endPrefixMapping(String prefix) throws SAXException
   {
@@ -1815,16 +1734,13 @@
    * @return true if the declaration has already been declared in the
    *         current context.
    */
-  protected boolean declAlreadyDeclared(String prefix)
-  {
-
+  protected boolean declAlreadyDeclared(String prefix) {
     int startDecls = m_contextIndexes.peek();
-    java.util.Vector prefixMappings = m_prefixMappings;
+    Vector<String> prefixMappings = m_prefixMappings;
     int nDecls = prefixMappings.size();
 
-    for (int i = startDecls; i < nDecls; i += 2)
-    {
-      String prefixDecl = (String) prefixMappings.elementAt(i);
+    for (int i = startDecls; i < nDecls; i += 2) {
+      String prefixDecl = prefixMappings.elementAt(i);
 
       if (prefixDecl == null)
         continue;
@@ -1836,7 +1752,7 @@
     return false;
   }
 
-        boolean m_pastFirstElement=false;
+  boolean m_pastFirstElement=false;
 
   /**
    * Receive notification of the start of an element.
@@ -1857,35 +1773,38 @@
    * @param attributes The specified or defaulted attributes.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#startElement
+   * @see ContentHandler#startElement
    */
-  public void startElement(
-          String uri, String localName, String qName, Attributes attributes)
-            throws SAXException
+  public void startElement(String uri, String localName, String qName,
+                           Attributes attributes) throws SAXException
   {
-   if (DEBUG)
-         {
-      System.out.println("startElement: uri: " + uri + ", localname: "
-                                                                                                 + localName + ", qname: "+qName+", atts: " + attributes);
+    if (DEBUG) {
+      System.out.println("startElement: uri: " + uri +
+                         ", localname: " + localName +
+                         ", qname: "+qName+", atts: " + attributes);
 
-                        boolean DEBUG_ATTRS=true;
-                        if(DEBUG_ATTRS & attributes!=null)
-                        {
-                                int n = attributes.getLength();
-                                if(n==0)
-                                        System.out.println("\tempty attribute list");
-                                else for (int i = 0; i < n; i++)
-                                        System.out.println("\t attr: uri: " + attributes.getURI(i) +
-                                                                                                                 ", localname: " + attributes.getLocalName(i) +
-                                                                                                                 ", qname: " + attributes.getQName(i) +
-                                                                                                                 ", type: " + attributes.getType(i) +
-                                                                                                                 ", value: " + attributes.getValue(i)
-                                                                                                                 );
-                        }
-         }
+      boolean DEBUG_ATTRS=true;
+      if (DEBUG_ATTRS & attributes!=null) {
+        int n = attributes.getLength();
+        if (n==0) {
+          System.out.println("\tempty attribute list");
+        } else for (int i = 0; i < n; i++) {
+          System.out.println("\t attr: uri: " + attributes.getURI(i) +
+                             ", localname: " + attributes.getLocalName(i) +
+                             ", qname: " + attributes.getQName(i) +
+                             ", type: " + attributes.getType(i) +
+                             ", value: " + attributes.getValue(i));
+        }
+      }
+    }
 
     charactersFlush();
 
+    if ((localName == null || localName.isEmpty()) &&
+        (uri == null || uri.isEmpty())) {
+      localName = qName;
+    }
+
     int exName = m_expandedNameTable.getExpandedTypeID(uri, localName, DTM.ELEMENT_NODE);
     String prefix = getPrefix(qName, uri);
     int prefixIndex = (null != prefix)
@@ -1894,20 +1813,18 @@
     int elemNode = addNode(DTM.ELEMENT_NODE, exName,
                            m_parents.peek(), m_previous, prefixIndex, true);
 
-    if(m_indexing)
+    if (m_indexing)
       indexNode(exName, elemNode);
 
-
     m_parents.push(elemNode);
 
     int startDecls = m_contextIndexes.peek();
     int nDecls = m_prefixMappings.size();
     int prev = DTM.NULL;
 
-    if(!m_pastFirstElement)
-    {
+    if (!m_pastFirstElement) {
       // SPECIAL CASE: Implied declaration at root element
-      prefix="xml";
+      prefix = "xml";
       String declURL = "http://www.w3.org/XML/1998/namespace";
       exName = m_expandedNameTable.getExpandedTypeID(null, prefix, DTM.NAMESPACE_NODE);
       int val = m_valuesOrPrefixes.stringToIndex(declURL);
@@ -1916,14 +1833,13 @@
       m_pastFirstElement=true;
     }
 
-    for (int i = startDecls; i < nDecls; i += 2)
-    {
-      prefix = (String) m_prefixMappings.elementAt(i);
+    for (int i = startDecls; i < nDecls; i += 2) {
+      prefix = m_prefixMappings.elementAt(i);
 
       if (prefix == null)
         continue;
 
-      String declURL = (String) m_prefixMappings.elementAt(i + 1);
+      String declURL = m_prefixMappings.elementAt(i + 1);
 
       exName = m_expandedNameTable.getExpandedTypeID(null, prefix, DTM.NAMESPACE_NODE);
 
@@ -1935,8 +1851,7 @@
 
     int n = attributes.getLength();
 
-    for (int i = 0; i < n; i++)
-    {
+    for (int i = 0; i < n; i++) {
       String attrUri = attributes.getURI(i);
       String attrQName = attributes.getQName(i);
       String valString = attributes.getValue(i);
@@ -1947,17 +1862,13 @@
 
        String attrLocalName = attributes.getLocalName(i);
 
-      if ((null != attrQName)
-              && (attrQName.equals("xmlns")
-                  || attrQName.startsWith("xmlns:")))
-      {
+      if ((null != attrQName) &&
+          (attrQName.equals("xmlns") || attrQName.startsWith("xmlns:"))) {
         if (declAlreadyDeclared(prefix))
           continue;  // go to the next attribute.
 
         nodeType = DTM.NAMESPACE_NODE;
-      }
-      else
-      {
+      } else {
         nodeType = DTM.ATTRIBUTE_NODE;
 
         if (attributes.getType(i).equalsIgnoreCase("ID"))
@@ -1966,15 +1877,13 @@
 
       // Bit of a hack... if somehow valString is null, stringToIndex will
       // return -1, which will make things very unhappy.
-      if(null == valString)
+      if (null == valString)
         valString = "";
 
       int val = m_valuesOrPrefixes.stringToIndex(valString);
       //String attrLocalName = attributes.getLocalName(i);
 
-      if (null != prefix)
-      {
-
+      if (null != prefix) {
         prefixIndex = m_valuesOrPrefixes.stringToIndex(attrQName);
 
         int dataIndex = m_data.size();
@@ -1993,8 +1902,7 @@
     if (DTM.NULL != prev)
       m_nextsib.setElementAt(DTM.NULL,prev);
 
-    if (null != m_wsfilter)
-    {
+    if (null != m_wsfilter) {
       short wsv = m_wsfilter.getShouldStripSpace(makeNodeHandle(elemNode), this);
       boolean shouldStrip = (DTMWSFilter.INHERIT == wsv)
                             ? getShouldStripWhitespace()
@@ -2026,7 +1934,7 @@
    *        empty string if qualified names are not available.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#endElement
+   * @see ContentHandler#endElement
    */
   public void endElement(String uri, String localName, String qName)
           throws SAXException
@@ -2074,7 +1982,7 @@
    *               character array.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#characters
+   * @see ContentHandler#characters
    */
   public void characters(char ch[], int start, int length) throws SAXException
   {
@@ -2109,7 +2017,7 @@
    *               character array.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#ignorableWhitespace
+   * @see ContentHandler#ignorableWhitespace
    */
   public void ignorableWhitespace(char ch[], int start, int length)
           throws SAXException
@@ -2133,7 +2041,7 @@
    *             none is supplied.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#processingInstruction
+   * @see ContentHandler#processingInstruction
    */
   public void processingInstruction(String target, String data)
           throws SAXException
@@ -2163,7 +2071,7 @@
    * @param name The name of the skipped entity.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#processingInstruction
+   * @see ContentHandler#processingInstruction
    */
   public void skippedEntity(String name) throws SAXException
   {
@@ -2187,8 +2095,8 @@
    * @param e The warning information encoded as an exception.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ErrorHandler#warning
-   * @see org.xml.sax.SAXParseException
+   * @see ErrorHandler#warning
+   * @see SAXParseException
    */
   public void warning(SAXParseException e) throws SAXException
   {
@@ -2208,8 +2116,8 @@
    * @param e The warning information encoded as an exception.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ErrorHandler#warning
-   * @see org.xml.sax.SAXParseException
+   * @see ErrorHandler#warning
+   * @see SAXParseException
    */
   public void error(SAXParseException e) throws SAXException
   {
@@ -2230,8 +2138,8 @@
    * @param e The error information encoded as an exception.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ErrorHandler#fatalError
-   * @see org.xml.sax.SAXParseException
+   * @see ErrorHandler#fatalError
+   * @see SAXParseException
    */
   public void fatalError(SAXParseException e) throws SAXException
   {
@@ -2299,7 +2207,7 @@
    * @param value The replacement text of the entity.
    * @throws SAXException The application may raise an exception.
    * @see #externalEntityDecl
-   * @see org.xml.sax.DTDHandler#unparsedEntityDecl
+   * @see DTDHandler#unparsedEntityDecl
    */
   public void internalEntityDecl(String name, String value)
           throws SAXException
@@ -2321,7 +2229,7 @@
    * @param systemId The declared system identifier of the entity.
    * @throws SAXException The application may raise an exception.
    * @see #internalEntityDecl
-   * @see org.xml.sax.DTDHandler#unparsedEntityDecl
+   * @see DTDHandler#unparsedEntityDecl
    */
   public void externalEntityDecl(
           String name, String publicId, String systemId) throws SAXException
@@ -2386,15 +2294,15 @@
    * properly nested within start/end entity events.</p>
    *
    * <p>Note that skipped entities will be reported through the
-   * {@link org.xml.sax.ContentHandler#skippedEntity skippedEntity}
+   * {@link ContentHandler#skippedEntity skippedEntity}
    * event, which is part of the ContentHandler interface.</p>
    *
    * @param name The name of the entity.  If it is a parameter
    *        entity, the name will begin with '%'.
    * @throws SAXException The application may raise an exception.
    * @see #endEntity
-   * @see org.xml.sax.ext.DeclHandler#internalEntityDecl
-   * @see org.xml.sax.ext.DeclHandler#externalEntityDecl
+   * @see DeclHandler#internalEntityDecl
+   * @see DeclHandler#externalEntityDecl
    */
   public void startEntity(String name) throws SAXException
   {
@@ -2419,7 +2327,7 @@
    * Report the start of a CDATA section.
    *
    * <p>The contents of the CDATA section will be reported through
-   * the regular {@link org.xml.sax.ContentHandler#characters
+   * the regular {@link ContentHandler#characters
    * characters} event.</p>
    *
    * @throws SAXException The application may raise an exception.
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/sax2dtm/SAX2DTM2.java	Fri Jan 13 01:35:35 2017 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/sax2dtm/SAX2DTM2.java	Mon Jan 16 15:44:30 2017 +0100
@@ -1,13 +1,13 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * Copyright 1999-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * 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
  *
@@ -17,13 +17,17 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: SAX2DTM2.java,v 1.2.4.1 2005/09/15 08:15:12 suresh_emailid Exp $
- */
+
 package com.sun.org.apache.xml.internal.dtm.ref.sax2dtm;
 
-import com.sun.org.apache.xml.internal.dtm.*;
-import com.sun.org.apache.xml.internal.dtm.ref.*;
+import com.sun.org.apache.xml.internal.dtm.DTM;
+import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator;
+import com.sun.org.apache.xml.internal.dtm.DTMException;
+import com.sun.org.apache.xml.internal.dtm.DTMManager;
+import com.sun.org.apache.xml.internal.dtm.DTMWSFilter;
+import com.sun.org.apache.xml.internal.dtm.ref.DTMDefaultBase;
+import com.sun.org.apache.xml.internal.dtm.ref.ExpandedNameTable;
+import com.sun.org.apache.xml.internal.dtm.ref.ExtendedType;
 import com.sun.org.apache.xml.internal.utils.FastStringBuffer;
 import com.sun.org.apache.xml.internal.utils.XMLString;
 import com.sun.org.apache.xml.internal.utils.XMLStringDefault;
@@ -31,11 +35,12 @@
 import com.sun.org.apache.xml.internal.res.XMLMessages;
 import com.sun.org.apache.xml.internal.res.XMLErrorResources;
 import com.sun.org.apache.xml.internal.serializer.SerializationHandler;
-
+import com.sun.org.apache.xml.internal.utils.SuballocatedIntVector;
+import java.util.ArrayList;
 import javax.xml.transform.Source;
-import java.util.Vector;
-import com.sun.org.apache.xml.internal.utils.SuballocatedIntVector;
-import org.xml.sax.*;
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
 
 /**
  * SAX2DTM2 is an optimized version of SAX2DTM which is used in non-incremental situation.
@@ -53,10 +58,6 @@
  * The design of SAX2DTM2 may limit its extensibilty. If you have a reason to extend the
  * SAX2DTM model, please extend from SAX2DTM instead of this class.
  * <p>
- * TODO: This class is currently only used by XSLTC. We need to investigate the possibility
- * of also using it in Xalan-J Interpretive. Xalan's performance is likely to get an instant
- * boost if we use SAX2DTM2 instead of SAX2DTM in non-incremental case.
- * <p>
  * %MK% The code in this class is critical to the XSLTC_DTM performance. Be very careful
  * when making changes here!
  */
@@ -87,11 +88,10 @@
      */
     public DTMAxisIterator setStartNode(int node)
     {
-//%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
+      //%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
       if (node == DTMDefaultBase.ROOTNODE)
         node = getDocument();
-      if (_isRestartable)
-      {
+      if (_isRestartable) {
         _startNode = node;
         _currentNode = (node == DTM.NULL) ? DTM.NULL
                                           : _firstch2(makeNodeIdentity(node));
@@ -108,8 +108,7 @@
      * @return The next node handle in the iteration, or END if no more
      * are available.
      */
-    public int next()
-    {
+    public int next() {
       if (_currentNode != NULL) {
         int node = _currentNode;
         _currentNode = _nextsib2(node);
@@ -139,13 +138,11 @@
      *
      * @return A DTMAxisIterator set to the start of the iteration.
      */
-    public DTMAxisIterator setStartNode(int node)
-    {
-//%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
+    public DTMAxisIterator setStartNode(int node) {
+      //%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
       if (node == DTMDefaultBase.ROOTNODE)
         node = getDocument();
-      if (_isRestartable)
-      {
+      if (_isRestartable) {
         _startNode = node;
 
         if (node != DTM.NULL)
@@ -229,8 +226,7 @@
      *
      * @param nodeType The extended type ID being requested.
      */
-    public TypedChildrenIterator(int nodeType)
-    {
+    public TypedChildrenIterator(int nodeType) {
       _nodeType = nodeType;
     }
 
@@ -242,17 +238,14 @@
      *
      * @return A DTMAxisIterator set to the start of the iteration.
      */
-    public DTMAxisIterator setStartNode(int node)
-    {
-//%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
+    public DTMAxisIterator setStartNode(int node) {
+      //%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
       if (node == DTMDefaultBase.ROOTNODE)
         node = getDocument();
-      if (_isRestartable)
-      {
+      if (_isRestartable) {
         _startNode = node;
-        _currentNode = (node == DTM.NULL)
-                                   ? DTM.NULL
-                                   : _firstch2(makeNodeIdentity(_startNode));
+        _currentNode = (node == DTM.NULL) ? DTM.NULL :
+                         _firstch2(makeNodeIdentity(_startNode));
 
         return resetPosition();
       }
@@ -265,8 +258,7 @@
      *
      * @return The next node handle in the iteration, or END.
      */
-    public int next()
-    {
+    public int next() {
       int node = _currentNode;
       if (node == DTM.NULL)
         return DTM.NULL;
@@ -301,14 +293,12 @@
         _currentNode = _nextsib2(node);
         return returnNode(makeNodeHandle(node));
       }
-
     }
 
     /**
      * Return the node at the given position.
      */
-    public int getNodeByPosition(int position)
-    {
+    public int getNodeByPosition(int position) {
       if (position <= 0)
         return DTM.NULL;
 
@@ -327,8 +317,7 @@
           node = _nextsib2(node);
         }
         return NULL;
-      }
-      else {
+      } else {
         while (node != DTM.NULL) {
           if (_exptype2(node) >= DTM.NTYPES) {
             pos++;
@@ -415,13 +404,11 @@
      *
      * @return A DTMAxisIterator set to the start of the iteration.
      */
-    public DTMAxisIterator setStartNode(int node)
-    {
-//%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
+    public DTMAxisIterator setStartNode(int node) {
+      //%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
       if (node == DTMDefaultBase.ROOTNODE)
         node = getDocument();
-      if (_isRestartable)
-      {
+      if (_isRestartable) {
         _startNode = node;
         _currentNode = makeNodeIdentity(node);
 
@@ -436,8 +423,7 @@
      *
      * @return The next node handle in the iteration, or END.
      */
-    public int next()
-    {
+    public int next() {
       _currentNode = (_currentNode == DTM.NULL) ? DTM.NULL
                                                 : _nextsib2(_currentNode);
       return returnNode(makeNodeHandle(_currentNode));
@@ -460,8 +446,7 @@
      *
      * @param type The extended type ID being requested.
      */
-    public TypedFollowingSiblingIterator(int type)
-    {
+    public TypedFollowingSiblingIterator(int type) {
       _nodeType = type;
     }
 
@@ -470,8 +455,7 @@
      *
      * @return The next node handle in the iteration, or END.
      */
-    public int next()
-    {
+    public int next() {
       if (_currentNode == DTM.NULL) {
         return DTM.NULL;
       }
@@ -481,8 +465,7 @@
 
       if (nodeType != DTM.ELEMENT_NODE) {
         while ((node = _nextsib2(node)) != DTM.NULL && _exptype2(node) != nodeType) {}
-      }
-      else {
+      } else {
         while ((node = _nextsib2(node)) != DTM.NULL && _exptype2(node) < DTM.NTYPES) {}
       }
 
@@ -498,9 +481,68 @@
   /**
    * Iterator that returns attribute nodes (of what nodes?)
    */
-  public final class AttributeIterator extends InternalAxisIteratorBase
+  public final class AttributeIterator extends InternalAxisIteratorBase {
+
+    // assumes caller will pass element nodes
+
+    /**
+     * Set start to END should 'close' the iterator,
+     * i.e. subsequent call to next() should return END.
+     *
+     * @param node Sets the root of the iteration.
+     *
+     * @return A DTMAxisIterator set to the start of the iteration.
+     */
+    public DTMAxisIterator setStartNode(int node) {
+      //%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
+      if (node == DTMDefaultBase.ROOTNODE)
+        node = getDocument();
+      if (_isRestartable) {
+        _startNode = node;
+        _currentNode = getFirstAttributeIdentity(makeNodeIdentity(node));
+
+        return resetPosition();
+      }
+
+      return this;
+    }
+
+    /**
+     * Get the next node in the iteration.
+     *
+     * @return The next node handle in the iteration, or END.
+     */
+    public int next() {
+      final int node = _currentNode;
+
+      if (node != NULL) {
+        _currentNode = getNextAttributeIdentity(node);
+        return returnNode(makeNodeHandle(node));
+      }
+
+      return NULL;
+    }
+  }  // end of AttributeIterator
+
+  /**
+   * Iterator that returns attribute nodes of a given type
+   */
+  public final class TypedAttributeIterator extends InternalAxisIteratorBase
   {
 
+    /** The extended type ID that was requested. */
+    private final int _nodeType;
+
+    /**
+     * Constructor TypedAttributeIterator
+     *
+     *
+     * @param nodeType The extended type ID that is requested.
+     */
+    public TypedAttributeIterator(int nodeType) {
+      _nodeType = nodeType;
+    }
+
     // assumes caller will pass element nodes
 
     /**
@@ -511,356 +553,267 @@
      *
      * @return A DTMAxisIterator set to the start of the iteration.
      */
+    public DTMAxisIterator setStartNode(int node) {
+      if (_isRestartable) {
+        _startNode = node;
+        _currentNode = getTypedAttribute(node, _nodeType);
+        return resetPosition();
+      }
+
+      return this;
+    }
+
+    /**
+     * Get the next node in the iteration.
+     *
+     * @return The next node handle in the iteration, or END.
+     */
+    public int next() {
+      final int node = _currentNode;
+
+      // singleton iterator, since there can only be one attribute of
+      // a given type.
+      _currentNode = NULL;
+
+      return returnNode(node);
+    }
+  }  // end of TypedAttributeIterator
+
+  /**
+   * Iterator that returns preceding siblings of a given node
+   */
+  public class PrecedingSiblingIterator extends InternalAxisIteratorBase
+  {
+
+    /**
+     * The node identity of _startNode for this iterator
+     */
+    protected int _startNodeID;
+
+    /**
+     * True if this iterator has a reversed axis.
+     *
+     * @return true.
+     */
+    public boolean isReverse() {
+      return true;
+    }
+
+    /**
+     * Set start to END should 'close' the iterator,
+     * i.e. subsequent call to next() should return END.
+     *
+     * @param node Sets the root of the iteration.
+     *
+     * @return A DTMAxisIterator set to the start of the iteration.
+     */
+    public DTMAxisIterator setStartNode(int node) {
+      //%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
+      if (node == DTMDefaultBase.ROOTNODE)
+        node = getDocument();
+      if (_isRestartable) {
+        _startNode = node;
+        node = _startNodeID = makeNodeIdentity(node);
+
+        if(node == NULL) {
+          _currentNode = node;
+          return resetPosition();
+        }
+
+        int type = _type2(node);
+        if (ExpandedNameTable.ATTRIBUTE == type ||
+            ExpandedNameTable.NAMESPACE == type)
+        {
+          _currentNode = node;
+        } else {
+          // Be careful to handle the Document node properly
+          _currentNode = _parent2(node);
+          if(NULL!=_currentNode)
+            _currentNode = _firstch2(_currentNode);
+          else
+            _currentNode = node;
+        }
+
+        return resetPosition();
+      }
+
+      return this;
+    }
+
+    /**
+     * Get the next node in the iteration.
+     *
+     * @return The next node handle in the iteration, or END.
+     */
+    public int next() {
+      if (_currentNode == _startNodeID || _currentNode == DTM.NULL) {
+        return NULL;
+      } else {
+        final int node = _currentNode;
+        _currentNode = _nextsib2(node);
+        return returnNode(makeNodeHandle(node));
+      }
+    }
+  }  // end of PrecedingSiblingIterator
+
+  /**
+   * Iterator that returns preceding siblings of a given type for
+   * a given node
+   */
+  public final class TypedPrecedingSiblingIterator
+          extends PrecedingSiblingIterator
+  {
+
+    /** The extended type ID that was requested. */
+    private final int _nodeType;
+
+    /**
+     * Constructor TypedPrecedingSiblingIterator
+     *
+     *
+     * @param type The extended type ID being requested.
+     */
+    public TypedPrecedingSiblingIterator(int type) {
+      _nodeType = type;
+    }
+
+    /**
+     * Get the next node in the iteration.
+     *
+     * @return The next node handle in the iteration, or END.
+     */
+    public int next() {
+      int node = _currentNode;
+
+      final int nodeType = _nodeType;
+      final int startNodeID = _startNodeID;
+
+      if (nodeType != DTM.ELEMENT_NODE) {
+        while (node != NULL && node != startNodeID && _exptype2(node) != nodeType) {
+          node = _nextsib2(node);
+        }
+      } else {
+        while (node != NULL && node != startNodeID && _exptype2(node) < DTM.NTYPES) {
+          node = _nextsib2(node);
+        }
+      }
+
+      if (node == DTM.NULL || node == startNodeID) {
+        _currentNode = NULL;
+        return NULL;
+      } else {
+        _currentNode = _nextsib2(node);
+        return returnNode(makeNodeHandle(node));
+      }
+    }
+
+    /**
+     * Return the index of the last node in this iterator.
+     */
+    public int getLast() {
+      if (_last != -1)
+        return _last;
+
+      setMark();
+
+      int node = _currentNode;
+      final int nodeType = _nodeType;
+      final int startNodeID = _startNodeID;
+
+      int last = 0;
+      if (nodeType != DTM.ELEMENT_NODE) {
+        while (node != NULL && node != startNodeID) {
+          if (_exptype2(node) == nodeType) {
+            last++;
+          }
+          node = _nextsib2(node);
+        }
+      } else {
+        while (node != NULL && node != startNodeID) {
+          if (_exptype2(node) >= DTM.NTYPES) {
+            last++;
+          }
+          node = _nextsib2(node);
+        }
+      }
+
+      gotoMark();
+
+      return (_last = last);
+    }
+  }  // end of TypedPrecedingSiblingIterator
+
+  /**
+   * Iterator that returns preceding nodes of a given node.
+   * This includes the node set {root+1, start-1}, but excludes
+   * all ancestors, attributes, and namespace nodes.
+   */
+  public class PrecedingIterator extends InternalAxisIteratorBase
+  {
+
+    /** The max ancestors, but it can grow... */
+    private final int _maxAncestors = 8;
+
+    /**
+     * The stack of start node + ancestors up to the root of the tree,
+     *  which we must avoid.
+     */
+    protected int[] _stack = new int[_maxAncestors];
+
+    /** (not sure yet... -sb) */
+    protected int _sp, _oldsp;
+
+    protected int _markedsp, _markedNode, _markedDescendant;
+
+    /* _currentNode precedes candidates.  This is the identity, not the handle! */
+
+    /**
+     * True if this iterator has a reversed axis.
+     *
+     * @return true since this iterator is a reversed axis.
+     */
+    public boolean isReverse()
+    {
+      return true;
+    }
+
+    /**
+     * Returns a deep copy of this iterator.   The cloned iterator is not reset.
+     *
+     * @return a deep copy of this iterator.
+     */
+    public DTMAxisIterator cloneIterator()
+    {
+      _isRestartable = false;
+
+      try
+      {
+        final PrecedingIterator clone = (PrecedingIterator) super.clone();
+        final int[] stackCopy = new int[_stack.length];
+        System.arraycopy(_stack, 0, stackCopy, 0, _stack.length);
+
+        clone._stack = stackCopy;
+
+        // return clone.reset();
+        return clone;
+      }
+      catch (CloneNotSupportedException e)
+      {
+        throw new DTMException(XMLMessages.createXMLMessage(XMLErrorResources.ER_ITERATOR_CLONE_NOT_SUPPORTED, null)); //"Iterator clone not supported.");
+      }
+    }
+
+    /**
+     * Set start to END should 'close' the iterator,
+     * i.e. subsequent call to next() should return END.
+     *
+     * @param node Sets the root of the iteration.
+     *
+     * @return A DTMAxisIterator set to the start of the iteration.
+     */
     public DTMAxisIterator setStartNode(int node)
     {
-//%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
-      if (node == DTMDefaultBase.ROOTNODE)
-        node = getDocument();
-      if (_isRestartable)
-      {
-        _startNode = node;
-        _currentNode = getFirstAttributeIdentity(makeNodeIdentity(node));
-
-        return resetPosition();
-      }
-
-      return this;
-    }
-
-    /**
-     * Get the next node in the iteration.
-     *
-     * @return The next node handle in the iteration, or END.
-     */
-    public int next()
-    {
-
-      final int node = _currentNode;
-
-      if (node != NULL) {
-        _currentNode = getNextAttributeIdentity(node);
-        return returnNode(makeNodeHandle(node));
-      }
-
-      return NULL;
-    }
-  }  // end of AttributeIterator
-
-  /**
-   * Iterator that returns attribute nodes of a given type
-   */
-  public final class TypedAttributeIterator extends InternalAxisIteratorBase
-  {
-
-    /** The extended type ID that was requested. */
-    private final int _nodeType;
-
-    /**
-     * Constructor TypedAttributeIterator
-     *
-     *
-     * @param nodeType The extended type ID that is requested.
-     */
-    public TypedAttributeIterator(int nodeType)
-    {
-      _nodeType = nodeType;
-    }
-
-    // assumes caller will pass element nodes
-
-    /**
-     * Set start to END should 'close' the iterator,
-     * i.e. subsequent call to next() should return END.
-     *
-     * @param node Sets the root of the iteration.
-     *
-     * @return A DTMAxisIterator set to the start of the iteration.
-     */
-    public DTMAxisIterator setStartNode(int node)
-    {
-      if (_isRestartable)
-      {
-        _startNode = node;
-
-        _currentNode = getTypedAttribute(node, _nodeType);
-
-        return resetPosition();
-      }
-
-      return this;
-    }
-
-    /**
-     * Get the next node in the iteration.
-     *
-     * @return The next node handle in the iteration, or END.
-     */
-    public int next()
-    {
-
-      final int node = _currentNode;
-
-      // singleton iterator, since there can only be one attribute of
-      // a given type.
-      _currentNode = NULL;
-
-      return returnNode(node);
-    }
-  }  // end of TypedAttributeIterator
-
-  /**
-   * Iterator that returns preceding siblings of a given node
-   */
-  public class PrecedingSiblingIterator extends InternalAxisIteratorBase
-  {
-
-    /**
-     * The node identity of _startNode for this iterator
-     */
-    protected int _startNodeID;
-
-    /**
-     * True if this iterator has a reversed axis.
-     *
-     * @return true.
-     */
-    public boolean isReverse()
-    {
-      return true;
-    }
-
-    /**
-     * Set start to END should 'close' the iterator,
-     * i.e. subsequent call to next() should return END.
-     *
-     * @param node Sets the root of the iteration.
-     *
-     * @return A DTMAxisIterator set to the start of the iteration.
-     */
-    public DTMAxisIterator setStartNode(int node)
-    {
-//%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
-      if (node == DTMDefaultBase.ROOTNODE)
-        node = getDocument();
-      if (_isRestartable)
-      {
-        _startNode = node;
-        node = _startNodeID = makeNodeIdentity(node);
-
-        if(node == NULL)
-        {
-          _currentNode = node;
-          return resetPosition();
-        }
-
-        int type = _type2(node);
-        if(ExpandedNameTable.ATTRIBUTE == type
-           || ExpandedNameTable.NAMESPACE == type )
-        {
-          _currentNode = node;
-        }
-        else
-        {
-          // Be careful to handle the Document node properly
-          _currentNode = _parent2(node);
-          if(NULL!=_currentNode)
-            _currentNode = _firstch2(_currentNode);
-          else
-            _currentNode = node;
-        }
-
-        return resetPosition();
-      }
-
-      return this;
-    }
-
-    /**
-     * Get the next node in the iteration.
-     *
-     * @return The next node handle in the iteration, or END.
-     */
-    public int next()
-    {
-
-      if (_currentNode == _startNodeID || _currentNode == DTM.NULL)
-      {
-        return NULL;
-      }
-      else
-      {
-        final int node = _currentNode;
-        _currentNode = _nextsib2(node);
-
-        return returnNode(makeNodeHandle(node));
-      }
-    }
-  }  // end of PrecedingSiblingIterator
-
-  /**
-   * Iterator that returns preceding siblings of a given type for
-   * a given node
-   */
-  public final class TypedPrecedingSiblingIterator
-          extends PrecedingSiblingIterator
-  {
-
-    /** The extended type ID that was requested. */
-    private final int _nodeType;
-
-    /**
-     * Constructor TypedPrecedingSiblingIterator
-     *
-     *
-     * @param type The extended type ID being requested.
-     */
-    public TypedPrecedingSiblingIterator(int type)
-    {
-      _nodeType = type;
-    }
-
-    /**
-     * Get the next node in the iteration.
-     *
-     * @return The next node handle in the iteration, or END.
-     */
-    public int next()
-    {
-      int node = _currentNode;
-
-      final int nodeType = _nodeType;
-      final int startNodeID = _startNodeID;
-
-      if (nodeType != DTM.ELEMENT_NODE) {
-        while (node != NULL && node != startNodeID && _exptype2(node) != nodeType) {
-          node = _nextsib2(node);
-        }
-      }
-      else {
-        while (node != NULL && node != startNodeID && _exptype2(node) < DTM.NTYPES) {
-          node = _nextsib2(node);
-        }
-      }
-
-      if (node == DTM.NULL || node == startNodeID) {
-        _currentNode = NULL;
-        return NULL;
-      }
-      else {
-        _currentNode = _nextsib2(node);
-        return returnNode(makeNodeHandle(node));
-      }
-    }
-
-    /**
-     * Return the index of the last node in this iterator.
-     */
-    public int getLast()
-    {
-      if (_last != -1)
-        return _last;
-
-      setMark();
-
-      int node = _currentNode;
-      final int nodeType = _nodeType;
-      final int startNodeID = _startNodeID;
-
-      int last = 0;
-      if (nodeType != DTM.ELEMENT_NODE) {
-        while (node != NULL && node != startNodeID) {
-          if (_exptype2(node) == nodeType) {
-            last++;
-          }
-          node = _nextsib2(node);
-        }
-      }
-      else {
-        while (node != NULL && node != startNodeID) {
-          if (_exptype2(node) >= DTM.NTYPES) {
-            last++;
-          }
-          node = _nextsib2(node);
-        }
-      }
-
-      gotoMark();
-
-      return (_last = last);
-    }
-  }  // end of TypedPrecedingSiblingIterator
-
-  /**
-   * Iterator that returns preceding nodes of a given node.
-   * This includes the node set {root+1, start-1}, but excludes
-   * all ancestors, attributes, and namespace nodes.
-   */
-  public class PrecedingIterator extends InternalAxisIteratorBase
-  {
-
-    /** The max ancestors, but it can grow... */
-    private final int _maxAncestors = 8;
-
-    /**
-     * The stack of start node + ancestors up to the root of the tree,
-     *  which we must avoid.
-     */
-    protected int[] _stack = new int[_maxAncestors];
-
-    /** (not sure yet... -sb) */
-    protected int _sp, _oldsp;
-
-    protected int _markedsp, _markedNode, _markedDescendant;
-
-    /* _currentNode precedes candidates.  This is the identity, not the handle! */
-
-    /**
-     * True if this iterator has a reversed axis.
-     *
-     * @return true since this iterator is a reversed axis.
-     */
-    public boolean isReverse()
-    {
-      return true;
-    }
-
-    /**
-     * Returns a deep copy of this iterator.   The cloned iterator is not reset.
-     *
-     * @return a deep copy of this iterator.
-     */
-    public DTMAxisIterator cloneIterator()
-    {
-      _isRestartable = false;
-
-      try
-      {
-        final PrecedingIterator clone = (PrecedingIterator) super.clone();
-        final int[] stackCopy = new int[_stack.length];
-        System.arraycopy(_stack, 0, stackCopy, 0, _stack.length);
-
-        clone._stack = stackCopy;
-
-        // return clone.reset();
-        return clone;
-      }
-      catch (CloneNotSupportedException e)
-      {
-        throw new DTMException(XMLMessages.createXMLMessage(XMLErrorResources.ER_ITERATOR_CLONE_NOT_SUPPORTED, null)); //"Iterator clone not supported.");
-      }
-    }
-
-    /**
-     * Set start to END should 'close' the iterator,
-     * i.e. subsequent call to next() should return END.
-     *
-     * @param node Sets the root of the iteration.
-     *
-     * @return A DTMAxisIterator set to the start of the iteration.
-     */
-    public DTMAxisIterator setStartNode(int node)
-    {
-//%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
+      //%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
       if (node == DTMDefaultBase.ROOTNODE)
         node = getDocument();
       if (_isRestartable)
@@ -1799,9 +1752,7 @@
   // %OPT% These values are unlikely to be equal. Storing
   // them in a plain Vector is more efficient than storing in the
   // DTMStringPool because we can save the cost for hash calculation.
-  //
-  // %REVISIT% Do we need a custom class (e.g. StringVector) here?
-  protected Vector m_values;
+  protected ArrayList<String> m_values;
 
   // The current index into the m_values Vector.
   private int m_valueIndex = 0;
@@ -1881,9 +1832,8 @@
     m_buildIdIndex = buildIdIndex;
 
     // Some documents do not have attribute nodes. That is why
-    // we set the initial size of this Vector to be small and set
-    // the increment to a bigger number.
-    m_values = new Vector(32, 512);
+    // we set the initial size of this ArrayList to be small.
+    m_values = new ArrayList<>(32);
 
     m_maxNodeIndex = 1 << DTMManager.IDENT_DTM_NODE_BITS;
 
@@ -1953,10 +1903,7 @@
    * @param identity A node identity, which <em>must not</em> be equal to
    *        <code>DTM.NULL</code>
    */
-  public final int _firstch2(int identity)
-  {
-    //return m_firstch.elementAt(identity);
-
+  public final int _firstch2(int identity) {
     if (identity < m_blocksize)
       return m_firstch_map0[identity];
     else
@@ -1969,10 +1916,7 @@
    * @param identity A node identity, which <em>must not</em> be equal to
    *        <code>DTM.NULL</code>
    */
-  public final int _parent2(int identity)
-  {
-    //return m_parent.elementAt(identity);
-
+  public final int _parent2(int identity) {
     if (identity < m_blocksize)
       return m_parent_map0[identity];
     else
@@ -1985,9 +1929,7 @@
    * @param identity A node identity, which <em>must not</em> be equal to
    *        <code>DTM.NULL</code>
    */
-  public final int _type2(int identity)
-  {
-    //int eType = _exptype2(identity);
+  public final int _type2(int identity) {
     int eType;
     if (identity < m_blocksize)
       eType = m_exptype_map0[identity];
@@ -2006,12 +1948,9 @@
    * <p>This one is only used by DOMAdapter.getExpandedTypeID(int), which
    * is mostly called from the compiled translets.
    */
-  public final int getExpandedTypeID2(int nodeHandle)
-  {
+  public final int getExpandedTypeID2(int nodeHandle) {
     int nodeID = makeNodeIdentity(nodeHandle);
 
-    //return (nodeID != NULL) ? _exptype2(nodeID) : NULL;
-
     if (nodeID != NULL) {
       if (nodeID < m_blocksize)
         return m_exptype_map0[nodeID];
@@ -2026,12 +1965,10 @@
    *                 END of DTM base accessor interfaces
    *************************************************************************/
 
-
   /**
    * Return the node type from the expanded type
    */
-  public final int _exptype2Type(int exptype)
-  {
+  public final int _exptype2Type(int exptype) {
     if (NULL != exptype)
       return m_extendedTypes[exptype].getNodeType();
     else
@@ -2046,16 +1983,14 @@
    *
    * @return The prefix if there is one, or null.
    */
-  public int getIdForNamespace(String uri)
-  {
+  public int getIdForNamespace(String uri) {
      int index = m_values.indexOf(uri);
-     if (index < 0)
-     {
-       m_values.addElement(uri);
+     if (index < 0) {
+       m_values.add(uri);
        return m_valueIndex++;
+     } else {
+       return index;
      }
-     else
-       return index;
   }
 
   /**
@@ -2079,15 +2014,25 @@
    * @param attributes The specified or defaulted attributes.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#startElement
+   * @see ContentHandler#startElement
    */
-  public void startElement(String uri, String localName, String qName, Attributes attributes)
-      throws SAXException
+  public void startElement(String uri, String localName, String qName,
+                           Attributes attributes) throws SAXException
   {
-
     charactersFlush();
 
-    int exName = m_expandedNameTable.getExpandedTypeID(uri, localName, DTM.ELEMENT_NODE);
+    // in case URI and localName are empty, the input is not using the
+    // namespaces feature. Then we should take the part after the last
+    // colon of qName as localName (strip all namespace prefixes)
+    if ((uri == null || uri.isEmpty()) &&
+        (localName == null || localName.isEmpty()))
+    {
+      final int colon = qName.lastIndexOf(':');
+      localName = (colon > -1) ? qName.substring(colon + 1) : qName;
+    }
+
+    int exName = m_expandedNameTable.getExpandedTypeID(uri, localName,
+                                                       DTM.ELEMENT_NODE);
 
     int prefixIndex = (qName.length() != localName.length())
                       ? m_valuesOrPrefixes.stringToIndex(qName) : 0;
@@ -2095,7 +2040,7 @@
     int elemNode = addNode(DTM.ELEMENT_NODE, exName,
                            m_parents.peek(), m_previous, prefixIndex, true);
 
-    if(m_indexing)
+    if (m_indexing)
       indexNode(exName, elemNode);
 
     m_parents.push(elemNode);
@@ -2104,31 +2049,31 @@
     int nDecls = m_prefixMappings.size();
     String prefix;
 
-    if(!m_pastFirstElement)
-    {
+    if (!m_pastFirstElement) {
       // SPECIAL CASE: Implied declaration at root element
-      prefix="xml";
+      prefix = "xml";
       String declURL = "http://www.w3.org/XML/1998/namespace";
-      exName = m_expandedNameTable.getExpandedTypeID(null, prefix, DTM.NAMESPACE_NODE);
-      m_values.addElement(declURL);
+      exName = m_expandedNameTable.getExpandedTypeID(null, prefix,
+                                                     DTM.NAMESPACE_NODE);
+      m_values.add(declURL);
       int val = m_valueIndex++;
       addNode(DTM.NAMESPACE_NODE, exName, elemNode,
                      DTM.NULL, val, false);
       m_pastFirstElement=true;
     }
 
-    for (int i = startDecls; i < nDecls; i += 2)
-    {
-      prefix = (String) m_prefixMappings.elementAt(i);
+    for (int i = startDecls; i < nDecls; i += 2) {
+      prefix = m_prefixMappings.elementAt(i);
 
       if (prefix == null)
         continue;
 
-      String declURL = (String) m_prefixMappings.elementAt(i + 1);
-
-      exName = m_expandedNameTable.getExpandedTypeID(null, prefix, DTM.NAMESPACE_NODE);
-
-      m_values.addElement(declURL);
+      String declURL = m_prefixMappings.elementAt(i + 1);
+
+      exName = m_expandedNameTable.getExpandedTypeID(null, prefix,
+                                                     DTM.NAMESPACE_NODE);
+
+      m_values.add(declURL);
       int val = m_valueIndex++;
 
       addNode(DTM.NAMESPACE_NODE, exName, elemNode, DTM.NULL, val, false);
@@ -2136,28 +2081,37 @@
 
     int n = attributes.getLength();
 
-    for (int i = 0; i < n; i++)
-    {
+    for (int i = 0; i < n; i++) {
       String attrUri = attributes.getURI(i);
+      String attrLocalName = attributes.getLocalName(i);
       String attrQName = attributes.getQName(i);
       String valString = attributes.getValue(i);
 
+      // in case URI and localName are empty, the input is not using the
+      // namespaces feature. Then we should take the part after the last
+      // colon of qName as localName (strip all namespace prefixes)
+      // When the URI is empty but localName has colons then we can also
+      // assume non namespace aware and prefixes can be stripped
+      if (attrUri == null || attrUri.isEmpty()) {
+        if (attrLocalName == null || attrLocalName.isEmpty()) {
+          final int colon = attrQName.lastIndexOf(':');
+          attrLocalName = (colon > -1) ? attrQName.substring(colon + 1) : attrQName;
+        } else {
+          final int colon = attrLocalName.lastIndexOf(':');
+          attrLocalName = (colon > -1) ? attrLocalName.substring(colon + 1) : attrLocalName;
+        }
+      }
+
       int nodeType;
-
-      String attrLocalName = attributes.getLocalName(i);
-
-      if ((null != attrQName)
-              && (attrQName.equals("xmlns")
-                  || attrQName.startsWith("xmlns:")))
+      if ((null != attrQName) &&
+          (attrQName.equals("xmlns") || attrQName.startsWith("xmlns:")))
       {
         prefix = getPrefix(attrQName, attrUri);
         if (declAlreadyDeclared(prefix))
           continue;  // go to the next attribute.
 
         nodeType = DTM.NAMESPACE_NODE;
-      }
-      else
-      {
+      } else {
         nodeType = DTM.ATTRIBUTE_NODE;
 
         if (m_buildIdIndex && attributes.getType(i).equalsIgnoreCase("ID"))
@@ -2166,36 +2120,31 @@
 
       // Bit of a hack... if somehow valString is null, stringToIndex will
       // return -1, which will make things very unhappy.
-      if(null == valString)
+      if (null == valString)
         valString = "";
 
-      m_values.addElement(valString);
+      m_values.add(valString);
       int val = m_valueIndex++;
 
-      if (attrLocalName.length() != attrQName.length())
-      {
-
+      if (attrLocalName.length() != attrQName.length()) {
         prefixIndex = m_valuesOrPrefixes.stringToIndex(attrQName);
-
         int dataIndex = m_data.size();
-
         m_data.addElement(prefixIndex);
         m_data.addElement(val);
-
         val = -dataIndex;
       }
 
-      exName = m_expandedNameTable.getExpandedTypeID(attrUri, attrLocalName, nodeType);
-      addNode(nodeType, exName, elemNode, DTM.NULL, val,
-                     false);
+      exName = m_expandedNameTable.getExpandedTypeID(attrUri, attrLocalName,
+                                                     nodeType);
+      addNode(nodeType, exName, elemNode, DTM.NULL, val, false);
     }
 
-    if (null != m_wsfilter)
-    {
-      short wsv = m_wsfilter.getShouldStripSpace(makeNodeHandle(elemNode), this);
-      boolean shouldStrip = (DTMWSFilter.INHERIT == wsv)
-                            ? getShouldStripWhitespace()
-                            : (DTMWSFilter.STRIP == wsv);
+    if (null != m_wsfilter) {
+      short wsv = m_wsfilter.getShouldStripSpace(makeNodeHandle(elemNode),
+                                                 this);
+      boolean shouldStrip = (DTMWSFilter.INHERIT == wsv) ?
+                            getShouldStripWhitespace() :
+                            (DTMWSFilter.STRIP == wsv);
 
       pushShouldStripWhitespace(shouldStrip);
     }
@@ -2223,7 +2172,7 @@
    *        empty string if qualified names are not available.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#endElement
+   * @see ContentHandler#endElement
    */
   public void endElement(String uri, String localName, String qName)
           throws SAXException
@@ -2257,9 +2206,7 @@
    * @param length The number of characters to use from the array.
    * @throws SAXException The application may raise an exception.
    */
-  public void comment(char ch[], int start, int length) throws SAXException
-  {
-
+  public void comment(char ch[], int start, int length) throws SAXException {
     if (m_insideDTD)      // ignore comments if we're inside the DTD
       return;
 
@@ -2267,7 +2214,7 @@
 
     // %OPT% Saving the comment string in a Vector has a lower cost than
     // saving it in DTMStringPool.
-    m_values.addElement(new String(ch, start, length));
+    m_values.add(new String(ch, start, length));
     int dataIndex = m_valueIndex++;
 
     m_previous = addNode(DTM.COMMENT_NODE, DTM.COMMENT_NODE,
@@ -2279,13 +2226,10 @@
    *
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#startDocument
+   * @see ContentHandler#startDocument
    */
-  public void startDocument() throws SAXException
-  {
-
-    int doc = addNode(DTM.DOCUMENT_NODE,
-                      DTM.DOCUMENT_NODE,
+  public void startDocument() throws SAXException {
+    int doc = addNode(DTM.DOCUMENT_NODE, DTM.DOCUMENT_NODE,
                       DTM.NULL, DTM.NULL, 0, true);
 
     m_parents.push(doc);
@@ -2299,10 +2243,9 @@
    *
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#endDocument
+   * @see ContentHandler#endDocument
    */
-  public void endDocument() throws SAXException
-  {
+  public void endDocument() throws SAXException {
     super.endDocument();
 
     // Add a NULL entry to the end of the node arrays as
@@ -2334,16 +2277,15 @@
    * @return The index identity of the node that was added.
    */
   protected final int addNode(int type, int expandedTypeID,
-                        int parentIndex, int previousSibling,
-                        int dataOrPrefix, boolean canHaveFirstChild)
+                              int parentIndex, int previousSibling,
+                              int dataOrPrefix, boolean canHaveFirstChild)
   {
     // Common to all nodes:
     int nodeIndex = m_size++;
 
     // Have we overflowed a DTM Identity's addressing range?
     //if(m_dtmIdent.size() == (nodeIndex>>>DTMManager.IDENT_DTM_NODE_BITS))
-    if (nodeIndex == m_maxNodeIndex)
-    {
+    if (nodeIndex == m_maxNodeIndex) {
       addNewDTMID(nodeIndex);
       m_maxNodeIndex += (1 << DTMManager.IDENT_DTM_NODE_BITS);
     }
@@ -2366,8 +2308,7 @@
     // is called, to handle successive characters() events.
 
     // Special handling by type: Declare namespaces, attach first child
-    switch(type)
-    {
+    switch(type) {
     case DTM.NAMESPACE_NODE:
       declareNamespaceInContext(parentIndex,nodeIndex);
       break;
@@ -2376,8 +2317,7 @@
     default:
       if (DTM.NULL != previousSibling) {
         m_nextsib.setElementAt(nodeIndex,previousSibling);
-      }
-      else if (DTM.NULL != parentIndex) {
+      } else if (DTM.NULL != parentIndex) {
         m_firstch.setElementAt(nodeIndex,parentIndex);
       }
       break;
@@ -2390,16 +2330,12 @@
    * Check whether accumulated text should be stripped; if not,
    * append the appropriate flavor of text/cdata node.
    */
-  protected final void charactersFlush()
-  {
-
-    if (m_textPendingStart >= 0)  // -1 indicates no-text-in-progress
-    {
+  protected final void charactersFlush() {
+    if (m_textPendingStart >= 0) { // -1 indicates no-text-in-progress
       int length = m_chars.size() - m_textPendingStart;
       boolean doStrip = false;
 
-      if (getShouldStripWhitespace())
-      {
+      if (getShouldStripWhitespace()) {
         doStrip = m_chars.isWhitespace(m_textPendingStart, length);
       }
 
@@ -2412,19 +2348,19 @@
           // If the offset and length do not exceed the given limits
           // (offset < 2^21 and length < 2^10), then save both the offset
           // and length in a bitwise encoded value.
-          if (length <= TEXT_LENGTH_MAX
-                  && m_textPendingStart <= TEXT_OFFSET_MAX) {
+          if (length <= TEXT_LENGTH_MAX &&
+              m_textPendingStart <= TEXT_OFFSET_MAX) {
             m_previous = addNode(m_coalescedTextType, DTM.TEXT_NODE,
-                             m_parents.peek(), m_previous,
-                             length + (m_textPendingStart << TEXT_LENGTH_BITS),
-                             false);
+                                 m_parents.peek(), m_previous,
+                                 length + (m_textPendingStart << TEXT_LENGTH_BITS),
+                                 false);
 
           } else {
             // Store offset and length in the m_data array if one exceeds
             // the given limits. Use a negative dataIndex as an indication.
             int dataIndex = m_data.size();
             m_previous = addNode(m_coalescedTextType, DTM.TEXT_NODE,
-                               m_parents.peek(), m_previous, -dataIndex, false);
+                                 m_parents.peek(), m_previous, -dataIndex, false);
 
             m_data.addElement(m_textPendingStart);
             m_data.addElement(length);
@@ -2452,7 +2388,7 @@
    *             none is supplied.
    * @throws SAXException Any SAX exception, possibly
    *            wrapping another exception.
-   * @see org.xml.sax.ContentHandler#processingInstruction
+   * @see ContentHandler#processingInstruction
    */
   public void processingInstruction(String target, String data)
           throws SAXException
@@ -2467,7 +2403,7 @@
                          -dataIndex, false);
 
     m_data.addElement(m_valuesOrPrefixes.stringToIndex(target));
-    m_values.addElement(data);
+    m_values.add(data);
     m_data.addElement(m_valueIndex++);
 
   }
@@ -2865,9 +2801,9 @@
       }
 
       if (m_xstrf != null)
-        return m_xstrf.newstr((String)m_values.elementAt(dataIndex));
+        return m_xstrf.newstr(m_values.get(dataIndex));
       else
-        return new XMLStringDefault((String)m_values.elementAt(dataIndex));
+        return new XMLStringDefault(m_values.get(dataIndex));
     }
   }
 
@@ -2966,7 +2902,7 @@
         dataIndex = m_data.elementAt(dataIndex + 1);
       }
 
-      return (String)m_values.elementAt(dataIndex);
+      return m_values.get(dataIndex);
     }
   }
 
@@ -3106,7 +3042,7 @@
         dataIndex = m_data.elementAt(dataIndex + 1);
       }
 
-      String str = (String)m_values.elementAt(dataIndex);
+      String str = m_values.get(dataIndex);
 
       if(normalize)
         FastStringBuffer.sendNormalizedSAXcharacters(str.toCharArray(),
@@ -3160,7 +3096,7 @@
         dataIndex = m_data.elementAt(dataIndex + 1);
       }
 
-      return (String)m_values.elementAt(dataIndex);
+      return m_values.get(dataIndex);
     }
   }
 
@@ -3202,8 +3138,7 @@
         if (uri.length() == 0) {
             handler.startElement(name);
             return name;
-        }
-        else {
+        } else {
             int qnameIndex = m_dataOrQName.elementAt(nodeID);
 
             if (qnameIndex == 0) {
@@ -3223,14 +3158,12 @@
             String prefix;
             if (prefixIndex > 0) {
                 prefix = qName.substring(0, prefixIndex);
-            }
-            else {
+            } else {
                 prefix = null;
             }
             handler.namespaceAfterStartElement(prefix, uri);
             return qName;
         }
-
     }
 
     /**
@@ -3285,7 +3218,7 @@
                 dataIndex = m_data.elementAt(dataIndex + 1);
             }
 
-            String nodeValue = (String)m_values.elementAt(dataIndex);
+            String nodeValue = m_values.get(dataIndex);
 
             handler.namespaceAfterStartElement(nodeName, nodeValue);
 
@@ -3335,7 +3268,6 @@
     }
 
 
-
     /**
      * Copy an Attribute node to a SerializationHandler
      *
@@ -3347,14 +3279,6 @@
         SerializationHandler handler)
         throws SAXException
     {
-        /*
-            final String uri = getNamespaceName(node);
-            if (uri.length() != 0) {
-                final String prefix = getPrefix(node);
-                handler.namespaceAfterStartElement(prefix, uri);
-            }
-            handler.addAttribute(getNodeName(node), getNodeValue(node));
-        */
         final ExtendedType extType = m_extendedTypes[exptype];
         final String uri = extType.getNamespace();
         final String localName = extType.getLocalName();
@@ -3377,7 +3301,7 @@
             }
 
         String nodeName = (prefix != null) ? qname : localName;
-        String nodeValue = (String)m_values.elementAt(valueIndex);
+        String nodeValue = m_values.get(valueIndex);
 
         handler.addAttribute(uri, localName, nodeName, "CDATA", nodeValue);
     }
--- a/jaxp/test/javax/xml/jaxp/unittest/transform/TransformerTest.java	Fri Jan 13 01:35:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/transform/TransformerTest.java	Mon Jan 16 15:44:30 2017 +0100
@@ -37,6 +37,7 @@
 
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParserFactory;
 import javax.xml.transform.Transformer;
 import javax.xml.transform.TransformerException;
 import javax.xml.transform.TransformerFactory;
@@ -74,11 +75,30 @@
  * @run testng/othervm -DrunSecMngr=true transform.TransformerTest
  * @run testng/othervm transform.TransformerTest
  * @summary Transformer Tests
- * @bug 6272879 6305029 6505031 8150704 8162598 8169112 8169772
+ * @bug 6272879 6305029 6505031 8150704 8162598 8169112 8169631 8169772
  */
 @Listeners({jaxp.library.FilePolicy.class})
 public class TransformerTest {
 
+    // some global constants
+    private static final String LINE_SEPARATOR =
+        getSystemProperty("line.separator");
+
+    private static final String NAMESPACES =
+        "http://xml.org/sax/features/namespaces";
+
+    private static final String NAMESPACE_PREFIXES =
+        "http://xml.org/sax/features/namespace-prefixes";
+
+    private static abstract class TestTemplate {
+        protected void printSnippet(String title, String snippet) {
+            StringBuilder div = new StringBuilder();
+            for (int i = 0; i < title.length(); i++)
+                div.append("=");
+            System.out.println(title + "\n" + div + "\n" + snippet + "\n");
+        }
+    }
+
     /**
      * Reads the contents of the given file into a string.
      * WARNING: this method adds a final line feed even if the last line of the file doesn't contain one.
@@ -101,44 +121,7 @@
         }
     }
 
-    /**
-     * Utility method for testBug8162598().
-     * Provides a convenient way to check/assert the expected namespaces
-     * of a Node and its siblings.
-     *
-     * @param test
-     * The node to check
-     * @param nstest
-     * Expected namespace of the node
-     * @param nsb
-     * Expected namespace of the first sibling
-     * @param nsc
-     * Expected namespace of the first sibling of the first sibling
-     */
-    private void checkNodeNS8162598(Node test, String nstest, String nsb, String nsc) {
-        String testNodeName = test.getNodeName();
-        if (nstest == null) {
-            Assert.assertNull(test.getNamespaceURI(), "unexpected namespace for " + testNodeName);
-        } else {
-            Assert.assertEquals(test.getNamespaceURI(), nstest, "unexpected namespace for " + testNodeName);
-        }
-        Node b = test.getChildNodes().item(0);
-        if (nsb == null) {
-            Assert.assertNull(b.getNamespaceURI(), "unexpected namespace for " + testNodeName + "->b");
-        } else {
-            Assert.assertEquals(b.getNamespaceURI(), nsb, "unexpected namespace for " + testNodeName + "->b");
-        }
-        Node c = b.getChildNodes().item(0);
-        if (nsc == null) {
-            Assert.assertNull(c.getNamespaceURI(), "unexpected namespace for " + testNodeName + "->b->c");
-        } else {
-            Assert.assertEquals(c.getNamespaceURI(), nsc, "unexpected namespace for " + testNodeName + "->b->c");
-        }
-    }
-
     private class XMLReaderFor6305029 implements XMLReader {
-        private static final String NAMESPACES = "http://xml.org/sax/features/namespaces";
-        private static final String NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes";
         private boolean namespaces = true;
         private boolean namespacePrefixes = false;
         private EntityResolver resolver;
@@ -235,8 +218,6 @@
      */
     @Test
     public final void testBug6272879() throws IOException, TransformerException {
-        final String LINE_SEPARATOR = getSystemProperty("line.separator");
-
         final String xsl =
                 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + LINE_SEPARATOR +
                 "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + LINE_SEPARATOR +
@@ -349,9 +330,125 @@
         Assert.assertTrue(s.contains("map1key1value") && s.contains("map2key1value"));
     }
 
+    private static class Test8169631 extends TestTemplate {
+        private final static String xsl =
+            "<?xml version=\"1.0\"?>" + LINE_SEPARATOR +
+            "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + LINE_SEPARATOR +
+            "  <xsl:template match=\"/\">" + LINE_SEPARATOR +
+            "    <xsl:variable name=\"Counter\" select=\"count(//row)\"/>" + LINE_SEPARATOR +
+            "    <xsl:variable name=\"AttribCounter\" select=\"count(//@attrib)\"/>" + LINE_SEPARATOR +
+            "    <Counter><xsl:value-of select=\"$Counter\"/></Counter>" + LINE_SEPARATOR +
+            "    <AttribCounter><xsl:value-of select=\"$AttribCounter\"/></AttribCounter>" + LINE_SEPARATOR +
+            "  </xsl:template>" + LINE_SEPARATOR +
+            "</xsl:stylesheet>" + LINE_SEPARATOR;
+
+        private final static String sourceXml =
+            "<?xml version=\"1.0\"?>" + LINE_SEPARATOR +
+            "<envelope xmlns=\"http://www.sap.com/myns\" xmlns:sap=\"http://www.sap.com/myns\">" + LINE_SEPARATOR +
+            "  <sap:row sap:attrib=\"a\">1</sap:row>" + LINE_SEPARATOR +
+            "  <row attrib=\"b\">2</row>" + LINE_SEPARATOR +
+            "  <row sap:attrib=\"c\">3</row>" + LINE_SEPARATOR +
+            "</envelope>" + LINE_SEPARATOR;
+
+        /**
+         * Utility method to print out transformation result and check values.
+         *
+         * @param type
+         * Text describing type of transformation
+         * @param result
+         * Resulting output of transformation
+         * @param elementCount
+         * Counter of elements to check
+         * @param attribCount
+         * Counter of attributes to check
+         */
+        private void verifyResult(String type, String result, int elementCount,
+                                  int attribCount)
+        {
+            printSnippet("Result of transformation from " + type + ":",
+                         result);
+            Assert.assertEquals(
+                result.contains("<Counter>" + elementCount + "</Counter>"),
+                true, "Result of transformation from " + type +
+                " should have count of " + elementCount + " elements.");
+            Assert.assertEquals(
+                result.contains("<AttribCounter>" + attribCount +
+                "</AttribCounter>"), true, "Result of transformation from " +
+                type + " should have count of "+ attribCount + " attributes.");
+        }
+
+        public void run() throws IOException, TransformerException,
+            SAXException, ParserConfigurationException
+        {
+            printSnippet("Source:", sourceXml);
+
+            printSnippet("Stylesheet:", xsl);
+
+            // create default transformer (namespace aware)
+            TransformerFactory tf1 = TransformerFactory.newInstance();
+            ByteArrayInputStream bais = new ByteArrayInputStream(xsl.getBytes());
+            Transformer t1 = tf1.newTransformer(new StreamSource(bais));
+
+            // test transformation from stream source with namespace support
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            bais = new ByteArrayInputStream(sourceXml.getBytes());
+            t1.transform(new StreamSource(bais), new StreamResult(baos));
+            verifyResult("StreamSource with namespace support", baos.toString(), 0, 1);
+
+            // test transformation from DOM source with namespace support
+            bais.reset();
+            baos.reset();
+            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+            dbf.setNamespaceAware(true);
+            Document doc = dbf.newDocumentBuilder().parse(new InputSource(bais));
+            t1.transform(new DOMSource(doc), new StreamResult(baos));
+            verifyResult("DOMSource with namespace support", baos.toString(), 0, 1);
+
+            // test transformation from DOM source without namespace support
+            bais.reset();
+            baos.reset();
+            dbf.setNamespaceAware(false);
+            doc = dbf.newDocumentBuilder().parse(new InputSource(bais));
+            t1.transform(new DOMSource(doc), new StreamResult(baos));
+            verifyResult("DOMSource without namespace support", baos.toString(), 3, 3);
+
+            // test transformation from SAX source with namespace support
+            bais.reset();
+            baos.reset();
+            SAXParserFactory spf = SAXParserFactory.newInstance();
+            spf.setNamespaceAware(true);
+            XMLReader xmlr = spf.newSAXParser().getXMLReader();
+            SAXSource saxS = new SAXSource(xmlr, new InputSource(bais));
+            t1.transform(saxS, new StreamResult(baos));
+            verifyResult("SAXSource with namespace support", baos.toString(), 0, 1);
+
+            // test transformation from SAX source without namespace support
+            bais.reset();
+            baos.reset();
+            spf.setNamespaceAware(false);
+            xmlr = spf.newSAXParser().getXMLReader();
+            saxS = new SAXSource(xmlr, new InputSource(bais));
+            t1.transform(saxS, new StreamResult(baos));
+            verifyResult("SAXSource without namespace support", baos.toString(), 3, 3);
+        }
+    }
+
+    /*
+     * @bug 8169631
+     * @summary Test combinations of namespace awareness settings on
+     *          XSL transformations
+     */
+    @Test
+    public final void testBug8169631() throws IOException, SAXException,
+        TransformerException, ParserConfigurationException
+    {
+        new Test8169631().run();
+    }
+
     /*
      * @bug 8150704
-     * @summary Test that XSL transformation with lots of temporary result trees will not run out of DTM IDs.
+     * @summary Test that XSL transformation with lots of temporary result
+     *          trees will not run out of DTM IDs.
      */
     @Test
     public final void testBug8150704() throws TransformerException, IOException {
@@ -375,16 +472,8 @@
         System.out.println("Passed.");
     }
 
-    /*
-     * @bug 8162598
-     * @summary Test XSLTC handling of namespaces, especially empty namespace definitions to reset the
-     *          default namespace
-     */
-    @Test
-    public final void testBug8162598() throws IOException, TransformerException {
-        final String LINE_SEPARATOR = getSystemProperty("line.separator");
-
-        final String xsl =
+    private static class Test8162598 extends TestTemplate {
+        private static final String xsl =
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + LINE_SEPARATOR +
             "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + LINE_SEPARATOR +
             "    <xsl:template match=\"/\">" + LINE_SEPARATOR +
@@ -402,39 +491,85 @@
             "    </xsl:template>" + LINE_SEPARATOR +
             "</xsl:stylesheet>";
 
+        private static final String sourceXml =
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?><aaa></aaa>" + LINE_SEPARATOR;
+        /**
+         * Utility method for testBug8162598().
+         * Provides a convenient way to check/assert the expected namespaces
+         * of a Node and its siblings.
+         *
+         * @param test
+         * The node to check
+         * @param nstest
+         * Expected namespace of the node
+         * @param nsb
+         * Expected namespace of the first sibling
+         * @param nsc
+         * Expected namespace of the first sibling of the first sibling
+         */
 
-        final String sourceXml =
-                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><aaa></aaa>" + LINE_SEPARATOR;
+        private void checkNodeNS(Node test, String nstest, String nsb, String nsc) {
+            String testNodeName = test.getNodeName();
+            if (nstest == null) {
+                Assert.assertNull(test.getNamespaceURI(), "unexpected namespace for " + testNodeName);
+            } else {
+                Assert.assertEquals(test.getNamespaceURI(), nstest, "unexpected namespace for " + testNodeName);
+            }
+            Node b = test.getChildNodes().item(0);
+            if (nsb == null) {
+                Assert.assertNull(b.getNamespaceURI(), "unexpected namespace for " + testNodeName + "->b");
+            } else {
+                Assert.assertEquals(b.getNamespaceURI(), nsb, "unexpected namespace for " + testNodeName + "->b");
+            }
+            Node c = b.getChildNodes().item(0);
+            if (nsc == null) {
+                Assert.assertNull(c.getNamespaceURI(), "unexpected namespace for " + testNodeName + "->b->c");
+            } else {
+                Assert.assertEquals(c.getNamespaceURI(), nsc, "unexpected namespace for " + testNodeName + "->b->c");
+            }
+        }
 
-        System.out.println("Stylesheet:");
-        System.out.println("=============================");
-        System.out.println(xsl);
-        System.out.println();
+        public void run()  throws IOException, TransformerException {
+            printSnippet("Source:", sourceXml);
 
-        System.out.println("Source before transformation:");
-        System.out.println("=============================");
-        System.out.println(sourceXml);
-        System.out.println();
+            printSnippet("Stylesheet:", xsl);
 
-        // transform to DOM result
-        TransformerFactory tf = TransformerFactory.newInstance();
-        Transformer t = tf.newTransformer(new StreamSource(new ByteArrayInputStream(xsl.getBytes())));
-        DOMResult result = new DOMResult();
-        t.transform(new StreamSource(new ByteArrayInputStream(sourceXml.getBytes())), result);
-        Document document = (Document)result.getNode();
+            // transform to DOM result
+            TransformerFactory tf = TransformerFactory.newInstance();
+            ByteArrayInputStream bais = new ByteArrayInputStream(xsl.getBytes());
+            Transformer t = tf.newTransformer(new StreamSource(bais));
+            DOMResult result = new DOMResult();
+            bais = new ByteArrayInputStream(sourceXml.getBytes());
+            t.transform(new StreamSource(bais), result);
+            Document document = (Document)result.getNode();
 
-        System.out.println("Result after transformation:");
-        System.out.println("============================");
-        OutputFormat format = new OutputFormat();
-        format.setIndenting(true);
-        new XMLSerializer(System.out, format).serialize(document);
-        System.out.println();
-        checkNodeNS8162598(document.getElementsByTagName("test1").item(0), "ns2", "ns2", null);
-        checkNodeNS8162598(document.getElementsByTagName("test2").item(0), "ns1", "ns2", null);
-        checkNodeNS8162598(document.getElementsByTagName("test3").item(0), null, null, null);
-        checkNodeNS8162598(document.getElementsByTagName("test4").item(0), null, null, null);
-        checkNodeNS8162598(document.getElementsByTagName("test5").item(0), "ns1", "ns1", null);
-        Assert.assertNull(document.getElementsByTagName("test6").item(0).getNamespaceURI(), "unexpected namespace for test6");
+            System.out.println("Result after transformation:");
+            System.out.println("============================");
+            OutputFormat format = new OutputFormat();
+            format.setIndenting(true);
+            new XMLSerializer(System.out, format).serialize(document);
+            System.out.println();
+
+            checkNodeNS(document.getElementsByTagName("test1").item(0), "ns2", "ns2", null);
+            checkNodeNS(document.getElementsByTagName("test2").item(0), "ns1", "ns2", null);
+            checkNodeNS(document.getElementsByTagName("test3").item(0), null, null, null);
+            checkNodeNS(document.getElementsByTagName("test4").item(0), null, null, null);
+            checkNodeNS(document.getElementsByTagName("test5").item(0), "ns1", "ns1", null);
+            Assert.assertNull(document.getElementsByTagName("test6").item(0).getNamespaceURI(),
+                "unexpected namespace for test6");
+        }
+    }
+
+    /*
+     * @bug 8162598
+     * @summary Test XSLTC handling of namespaces, especially empty namespace
+     *          definitions to reset the default namespace
+     */
+    @Test
+    public final void testBug8162598() throws IOException,
+        TransformerException
+    {
+        new Test8162598().run();
     }
 
     /**