nokogiri 1.7.2-java → 1.8.0-java

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of nokogiri might be problematic. Click here for more details.

Files changed (101) hide show
  1. checksums.yaml +4 -4
  2. data/.cross_rubies +4 -4
  3. data/.travis.yml +43 -24
  4. data/CHANGELOG.md +54 -6
  5. data/Gemfile +8 -7
  6. data/Gemfile-libxml-ruby +3 -0
  7. data/LICENSE-DEPENDENCIES.md +1612 -0
  8. data/{LICENSE.txt → LICENSE.md} +1 -1
  9. data/Manifest.txt +5 -8
  10. data/README.md +8 -5
  11. data/Rakefile +15 -31
  12. data/appveyor.yml +2 -0
  13. data/dependencies.yml +12 -7
  14. data/ext/java/nokogiri/HtmlDocument.java +2 -2
  15. data/ext/java/nokogiri/HtmlSaxParserContext.java +20 -21
  16. data/ext/java/nokogiri/HtmlSaxPushParser.java +6 -10
  17. data/ext/java/nokogiri/NokogiriService.java +10 -31
  18. data/ext/java/nokogiri/XmlAttr.java +1 -26
  19. data/ext/java/nokogiri/XmlCdata.java +0 -1
  20. data/ext/java/nokogiri/XmlComment.java +1 -1
  21. data/ext/java/nokogiri/XmlDocument.java +4 -5
  22. data/ext/java/nokogiri/XmlDocumentFragment.java +29 -21
  23. data/ext/java/nokogiri/XmlDtd.java +1 -1
  24. data/ext/java/nokogiri/XmlElement.java +9 -10
  25. data/ext/java/nokogiri/XmlEntityDecl.java +4 -5
  26. data/ext/java/nokogiri/XmlNode.java +105 -103
  27. data/ext/java/nokogiri/XmlNodeSet.java +64 -76
  28. data/ext/java/nokogiri/XmlReader.java +48 -48
  29. data/ext/java/nokogiri/XmlRelaxng.java +1 -1
  30. data/ext/java/nokogiri/XmlSaxPushParser.java +37 -17
  31. data/ext/java/nokogiri/XmlSchema.java +7 -5
  32. data/ext/java/nokogiri/XmlSyntaxError.java +47 -35
  33. data/ext/java/nokogiri/XmlXpathContext.java +160 -132
  34. data/ext/java/nokogiri/XsltStylesheet.java +15 -24
  35. data/ext/java/nokogiri/internals/HtmlDomParserContext.java +19 -23
  36. data/ext/java/nokogiri/internals/NokogiriDomParser.java +1 -1
  37. data/ext/java/nokogiri/internals/NokogiriEncodingReaderWrapper.java +1 -1
  38. data/ext/java/nokogiri/internals/NokogiriEntityResolver.java +11 -13
  39. data/ext/java/nokogiri/internals/NokogiriErrorHandler.java +5 -21
  40. data/ext/java/nokogiri/internals/NokogiriHandler.java +1 -1
  41. data/ext/java/nokogiri/internals/NokogiriHelpers.java +105 -142
  42. data/ext/java/nokogiri/internals/NokogiriNamespaceContext.java +16 -26
  43. data/ext/java/nokogiri/internals/NokogiriXPathFunction.java +32 -50
  44. data/ext/java/nokogiri/internals/NokogiriXPathFunctionResolver.java +10 -13
  45. data/ext/java/nokogiri/internals/NokogiriXPathVariableResolver.java +3 -10
  46. data/ext/java/nokogiri/internals/ParserContext.java +4 -8
  47. data/ext/java/nokogiri/internals/ReaderNode.java +53 -93
  48. data/ext/java/nokogiri/internals/SaveContextVisitor.java +77 -89
  49. data/ext/java/nokogiri/internals/SchemaErrorHandler.java +6 -9
  50. data/ext/java/nokogiri/internals/XalanDTMManagerPatch.java +167 -0
  51. data/ext/java/nokogiri/internals/XmlDomParserContext.java +17 -6
  52. data/ext/java/nokogiri/internals/c14n/Canonicalizer.java +1 -1
  53. data/ext/java/nokogiri/internals/c14n/Canonicalizer11.java +28 -28
  54. data/ext/java/nokogiri/internals/c14n/Canonicalizer20010315.java +3 -4
  55. data/ext/java/nokogiri/internals/c14n/Canonicalizer20010315Excl.java +2 -2
  56. data/ext/java/nokogiri/internals/c14n/CanonicalizerBase.java +10 -10
  57. data/ext/java/nokogiri/internals/c14n/ElementProxy.java +5 -5
  58. data/ext/java/nokogiri/internals/c14n/InclusiveNamespaces.java +2 -2
  59. data/ext/java/nokogiri/internals/c14n/NameSpaceSymbTable.java +1 -1
  60. data/ext/java/nokogiri/internals/c14n/XMLUtils.java +2 -2
  61. data/ext/java/org/apache/xml/dtm/ref/dom2dtm/DOM2DTMExt.java +1749 -0
  62. data/ext/nokogiri/extconf.rb +12 -17
  63. data/ext/nokogiri/nokogiri.h +0 -10
  64. data/ext/nokogiri/xml_attr.c +12 -8
  65. data/ext/nokogiri/xml_node.c +17 -14
  66. data/ext/nokogiri/xml_sax_push_parser.c +56 -12
  67. data/lib/nokogiri/html/sax/parser.rb +10 -0
  68. data/lib/nokogiri/nokogiri.jar +0 -0
  69. data/lib/nokogiri/version.rb +5 -4
  70. data/lib/nokogiri/xml/document.rb +9 -9
  71. data/lib/nokogiri/xml/node.rb +7 -7
  72. data/lib/nokogiri/xml/node_set.rb +12 -7
  73. data/lib/nokogiri/xml/sax/parser.rb +6 -7
  74. data/lib/nokogiri/xml/searchable.rb +34 -25
  75. data/lib/nokogiri/xml/syntax_error.rb +24 -1
  76. data/test/decorators/test_slop.rb +4 -1
  77. data/test/helper.rb +10 -0
  78. data/test/html/sax/test_parser.rb +27 -0
  79. data/test/html/test_document.rb +12 -1
  80. data/test/html/test_document_encoding.rb +1 -3
  81. data/test/html/test_document_fragment.rb +3 -0
  82. data/test/xml/sax/test_push_parser.rb +48 -0
  83. data/test/xml/test_attr.rb +7 -0
  84. data/test/xml/test_document.rb +1 -1
  85. data/test/xml/test_document_fragment.rb +27 -0
  86. data/test/xml/test_entity_reference.rb +2 -2
  87. data/test/xml/test_node.rb +12 -15
  88. data/test/xml/test_node_reparenting.rb +14 -0
  89. data/test/xml/test_node_set.rb +8 -6
  90. data/test/xml/test_reader.rb +19 -0
  91. data/test/xml/test_syntax_error.rb +21 -15
  92. data/test/xml/test_unparented_node.rb +54 -11
  93. data/test/xml/test_xpath.rb +23 -6
  94. metadata +32 -20
  95. data/ext/java/nokogiri/internals/NokogiriDocumentCache.java +0 -73
  96. data/ext/java/nokogiri/internals/XsltExtensionFunction.java +0 -72
  97. data/suppressions/nokogiri_ree-1.8.7.358.supp +0 -61
  98. data/suppressions/nokogiri_ruby-1.8.7.370.supp +0 -0
  99. data/suppressions/nokogiri_ruby-1.9.2.320.supp +0 -28
  100. data/suppressions/nokogiri_ruby-1.9.3.327.supp +0 -28
  101. data/test_all +0 -105
@@ -167,21 +167,32 @@ public class XmlDomParserContext extends ParserContext {
167
167
  }
168
168
 
169
169
  public void addErrorsIfNecessary(ThreadContext context, XmlDocument doc) {
170
- Ruby ruby = context.getRuntime();
171
- RubyArray errors = ruby.newArray(errorHandler.getErrorsReadyForRuby(context));
172
- doc.setInstanceVariable("@errors", errors);
170
+ doc.setInstanceVariable("@errors", mapErrors(context, errorHandler));
171
+ }
172
+
173
+
174
+ public static RubyArray mapErrors(ThreadContext context, NokogiriErrorHandler errorHandler) {
175
+ final Ruby runtime = context.runtime;
176
+ final List<Exception> errors = errorHandler.getErrors();
177
+ final IRubyObject[] errorsAry = new IRubyObject[errors.size()];
178
+ for (int i = 0; i < errors.size(); i++) {
179
+ XmlSyntaxError xmlSyntaxError = XmlSyntaxError.createXMLSyntaxError(runtime);
180
+ xmlSyntaxError.setException(errors.get(i));
181
+ errorsAry[i] = xmlSyntaxError;
182
+ }
183
+ return runtime.newArrayNoCopy(errorsAry);
173
184
  }
174
185
 
175
186
  public XmlDocument getDocumentWithErrorsOrRaiseException(ThreadContext context, RubyClass klazz, Exception ex) {
176
187
  if (options.recover) {
177
188
  XmlDocument xmlDocument = getInterruptedOrNewXmlDocument(context, klazz);
178
189
  this.addErrorsIfNecessary(context, xmlDocument);
179
- XmlSyntaxError xmlSyntaxError = (XmlSyntaxError) NokogiriService.XML_SYNTAXERROR_ALLOCATOR.allocate(context.getRuntime(), getNokogiriClass(context.getRuntime(), "Nokogiri::XML::SyntaxError"));
190
+ XmlSyntaxError xmlSyntaxError = XmlSyntaxError.createXMLSyntaxError(context.runtime);
180
191
  xmlSyntaxError.setException(ex);
181
192
  ((RubyArray) xmlDocument.getInstanceVariable("@errors")).append(xmlSyntaxError);
182
193
  return xmlDocument;
183
194
  } else {
184
- XmlSyntaxError xmlSyntaxError = (XmlSyntaxError) NokogiriService.XML_SYNTAXERROR_ALLOCATOR.allocate(context.getRuntime(), getNokogiriClass(context.getRuntime(), "Nokogiri::XML::SyntaxError"));
195
+ XmlSyntaxError xmlSyntaxError = XmlSyntaxError.createXMLSyntaxError(context.runtime);
185
196
  xmlSyntaxError.setException(ex);
186
197
  throw new RaiseException(xmlSyntaxError);
187
198
  }
@@ -262,7 +273,7 @@ public class XmlDomParserContext extends ParserContext {
262
273
  return parser.getDocument();
263
274
  }
264
275
 
265
- private void findEmptyTexts(Node node, List<Node> emptyNodes) {
276
+ private static void findEmptyTexts(Node node, List<Node> emptyNodes) {
266
277
  if (node.getNodeType() == Node.TEXT_NODE && "".equals(node.getTextContent().trim())) {
267
278
  emptyNodes.add(node);
268
279
  } else {
@@ -149,7 +149,7 @@ public class Canonicalizer {
149
149
  * @throws CanonicalizationException
150
150
  */
151
151
  public static void register(String algorithmURI, Class<? extends CanonicalizerSpi> implementingClass)
152
- throws CanonicalizationException, ClassNotFoundException {
152
+ throws CanonicalizationException {
153
153
  // check whether URI is already registered
154
154
  Class<? extends CanonicalizerSpi> registeredClass = canonicalizerHash.get(algorithmURI);
155
155
 
@@ -56,7 +56,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
56
56
  int level;
57
57
  boolean rendered = false;
58
58
  List<Attr> nodes = new ArrayList<Attr>();
59
- };
59
+ }
60
60
 
61
61
  int currentLevel = 0;
62
62
  int lastlevel = 0;
@@ -99,11 +99,10 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
99
99
  levels.add(cur);
100
100
  }
101
101
  boolean parentRendered = false;
102
- XmlsStackElement e = null;
103
102
  if (size == -1) {
104
103
  parentRendered = true;
105
104
  } else {
106
- e = levels.get(size);
105
+ XmlsStackElement e = levels.get(size);
107
106
  if (e.rendered && e.level + 1 == currentLevel) {
108
107
  parentRendered = true;
109
108
  }
@@ -118,7 +117,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
118
117
  List<Attr> baseAttrs = new ArrayList<Attr>();
119
118
  boolean successiveOmitted = true;
120
119
  for (; size >= 0; size--) {
121
- e = levels.get(size);
120
+ XmlsStackElement e = levels.get(size);
122
121
  if (e.rendered) {
123
122
  successiveOmitted = false;
124
123
  }
@@ -167,7 +166,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
167
166
  cur.rendered = true;
168
167
  col.addAll(loa.values());
169
168
  }
170
- };
169
+ }
171
170
 
172
171
  private final XmlAttrStack xmlattrStack = new XmlAttrStack();
173
172
 
@@ -490,11 +489,11 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
490
489
  // If the input buffer starts with a root slash "/" then move this
491
490
  // character to the output buffer.
492
491
  if (input.charAt(0) == '/') {
493
- output.append("/");
492
+ output.append('/');
494
493
  input = input.substring(1);
495
494
  }
496
495
 
497
- printStep("1 ", output.toString(), input);
496
+ printStep("1 ", output, input);
498
497
 
499
498
  // While the input buffer is not empty, loop as follows
500
499
  while (input.length() != 0) {
@@ -506,23 +505,23 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
506
505
  // remove that prefix
507
506
  if (input.startsWith("./")) {
508
507
  input = input.substring(2);
509
- printStep("2A", output.toString(), input);
508
+ printStep("2A", output, input);
510
509
  } else if (input.startsWith("../")) {
511
510
  input = input.substring(3);
512
511
  if (!output.toString().equals("/")) {
513
512
  output.append("../");
514
513
  }
515
- printStep("2A", output.toString(), input);
514
+ printStep("2A", output, input);
516
515
  // 2B. if the input buffer begins with a prefix of "/./" or "/.",
517
516
  // where "." is a complete path segment, then replace that prefix
518
517
  // with "/" in the input buffer; otherwise,
519
518
  } else if (input.startsWith("/./")) {
520
519
  input = input.substring(2);
521
- printStep("2B", output.toString(), input);
520
+ printStep("2B", output, input);
522
521
  } else if (input.equals("/.")) {
523
522
  // FIXME: what is complete path segment?
524
523
  input = input.replaceFirst("/.", "/");
525
- printStep("2B", output.toString(), input);
524
+ printStep("2B", output, input);
526
525
  // 2C. if the input buffer begins with a prefix of "/../" or "/..",
527
526
  // where ".." is a complete path segment, then replace that prefix
528
527
  // with "/" in the input buffer and if also the output buffer is
@@ -552,7 +551,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
552
551
  output = output.delete(index, output.length());
553
552
  }
554
553
  }
555
- printStep("2C", output.toString(), input);
554
+ printStep("2C", output, input);
556
555
  } else if (input.equals("/..")) {
557
556
  // FIXME: what is complete path segment?
558
557
  input = input.replaceFirst("/..", "/");
@@ -573,7 +572,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
573
572
  output = output.delete(index, output.length());
574
573
  }
575
574
  }
576
- printStep("2C", output.toString(), input);
575
+ printStep("2C", output, input);
577
576
  // 2D. if the input buffer consists only of ".", then remove
578
577
  // that from the input buffer else if the input buffer consists
579
578
  // only of ".." and if the output buffer does not contain only
@@ -581,19 +580,19 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
581
580
  // else delte it.; otherwise,
582
581
  } else if (input.equals(".")) {
583
582
  input = "";
584
- printStep("2D", output.toString(), input);
583
+ printStep("2D", output, input);
585
584
  } else if (input.equals("..")) {
586
585
  if (!output.toString().equals("/")) {
587
586
  output.append("..");
588
587
  }
589
588
  input = "";
590
- printStep("2D", output.toString(), input);
589
+ printStep("2D", output, input);
591
590
  // 2E. move the first path segment (if any) in the input buffer
592
591
  // to the end of the output buffer, including the initial "/"
593
592
  // character (if any) and any subsequent characters up to, but not
594
593
  // including, the next "/" character or the end of the input buffer.
595
594
  } else {
596
- int end = -1;
595
+ int end;
597
596
  int begin = input.indexOf('/');
598
597
  if (begin == 0) {
599
598
  end = input.indexOf('/', 1);
@@ -610,7 +609,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
610
609
  input = input.substring(end);
611
610
  }
612
611
  output.append(segment);
613
- printStep("2E", output.toString(), input);
612
+ printStep("2E", output, input);
614
613
  }
615
614
  }
616
615
 
@@ -619,21 +618,22 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
619
618
  // then append a slash "/". The output buffer is returned as the result
620
619
  // of remove_dot_segments
621
620
  if (output.toString().endsWith("..")) {
622
- output.append("/");
623
- printStep("3 ", output.toString(), input);
621
+ output.append('/');
622
+ printStep("3 ", output, input);
624
623
  }
625
624
 
626
625
  return output.toString();
627
626
  }
628
627
 
629
- private static void printStep(String step, String output, String input) {
630
- if (System.getProperty("nokogiri.c14.debug") == "on") {
631
- System.out.println(" " + step + ": " + output);
632
- if (output.length() == 0) {
633
- System.out.println("\t\t\t\t" + input);
634
- } else {
635
- System.out.println("\t\t\t" + input);
636
- }
637
- }
628
+ private static void printStep(String step, StringBuilder output, String input) {
629
+ //if (System.getProperty("nokogiri.c14.debug") == "on") { //
630
+ // System.out.println(" " + step + ": " + output);
631
+ // if (output.length() == 0) {
632
+ // System.out.println("\t\t\t\t" + input);
633
+ // } else {
634
+ // System.out.println("\t\t\t" + input);
635
+ // }
636
+ //}
638
637
  }
638
+
639
639
  }
@@ -52,7 +52,7 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
52
52
  int level;
53
53
  boolean rendered = false;
54
54
  List<Attr> nodes = new ArrayList<Attr>();
55
- };
55
+ }
56
56
 
57
57
  int currentLevel = 0;
58
58
  int lastlevel = 0;
@@ -95,11 +95,10 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
95
95
  levels.add(cur);
96
96
  }
97
97
  boolean parentRendered = false;
98
- XmlsStackElement e = null;
99
98
  if (size == -1) {
100
99
  parentRendered = true;
101
100
  } else {
102
- e = levels.get(size);
101
+ XmlsStackElement e = levels.get(size);
103
102
  if (e.rendered && e.level + 1 == currentLevel) {
104
103
  parentRendered = true;
105
104
  }
@@ -112,7 +111,7 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
112
111
 
113
112
  Map<String, Attr> loa = new HashMap<String, Attr>();
114
113
  for (; size >= 0; size--) {
115
- e = levels.get(size);
114
+ XmlsStackElement e = levels.get(size);
116
115
  Iterator<Attr> it = e.nodes.iterator();
117
116
  while (it.hasNext()) {
118
117
  Attr n = it.next();
@@ -154,7 +154,7 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
154
154
  }
155
155
  }
156
156
  }
157
- String prefix = null;
157
+ String prefix;
158
158
  if (element.getNamespaceURI() != null
159
159
  && !(element.getPrefix() == null || element.getPrefix().length() == 0)) {
160
160
  prefix = element.getPrefix();
@@ -256,7 +256,7 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
256
256
  ns.addMapping(XMLNS, "", nullNode);
257
257
  }
258
258
 
259
- String prefix = null;
259
+ String prefix;
260
260
  if (element.getNamespaceURI() != null
261
261
  && !(element.getPrefix() == null || element.getPrefix().length() == 0)) {
262
262
  prefix = element.getPrefix();
@@ -85,7 +85,7 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi {
85
85
  private List<NodeFilter> nodeFilter;
86
86
 
87
87
  private final boolean includeComments;
88
- private Set<Node> xpathNodeSet;
88
+ //private Set<Node> xpathNodeSet;
89
89
  /**
90
90
  * The node to be skipped/excluded from the DOM tree
91
91
  * in subtree canonicalizations.
@@ -294,9 +294,9 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi {
294
294
  }
295
295
  }
296
296
  }
297
- if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
298
- return 0;
299
- }
297
+ //if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
298
+ // return 0;
299
+ //}
300
300
  return 1;
301
301
  }
302
302
 
@@ -310,9 +310,9 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi {
310
310
  }
311
311
  }
312
312
  }
313
- if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
314
- return 0;
315
- }
313
+ //if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
314
+ // return 0;
315
+ //}
316
316
  return 1;
317
317
  }
318
318
 
@@ -325,9 +325,9 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi {
325
325
  }
326
326
  }
327
327
  }
328
- if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
329
- return false;
330
- }
328
+ //if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
329
+ // return false;
330
+ //}
331
331
  return true;
332
332
  }
333
333
 
@@ -80,9 +80,9 @@ public abstract class ElementProxy {
80
80
  throw new CanonicalizationException("ElementProxy.nullElement");
81
81
  }
82
82
 
83
- if (System.getProperty("nokogiri.c14.debug") == "on") {
84
- System.out.println("setElement(\"" + element.getTagName() + "\", \"" + BaseURI + "\")");
85
- }
83
+ //if (System.getProperty("nokogiri.c14.debug") == "on") {
84
+ // System.out.println("setElement(\"" + element.getTagName() + "\", \"" + BaseURI + "\")");
85
+ //}
86
86
 
87
87
  this.doc = element.getOwnerDocument();
88
88
  this.constructionElement = element;
@@ -109,7 +109,7 @@ public abstract class ElementProxy {
109
109
  protected Element createElementForFamilyLocal(
110
110
  Document doc, String namespace, String localName
111
111
  ) {
112
- Element result = null;
112
+ Element result;
113
113
  if (namespace == null) {
114
114
  result = doc.createElementNS(null, localName);
115
115
  } else {
@@ -140,7 +140,7 @@ public abstract class ElementProxy {
140
140
  * @return The element created.
141
141
  */
142
142
  public static Element createElementForFamily(Document doc, String namespace, String localName) {
143
- Element result = null;
143
+ Element result;
144
144
  String prefix = ElementProxy.getDefaultPrefix(namespace);
145
145
 
146
146
  if (namespace == null) {
@@ -68,7 +68,7 @@ public class InclusiveNamespaces extends ElementProxy {
68
68
  public InclusiveNamespaces(Document doc, Set<String> prefixes) {
69
69
  super(doc);
70
70
 
71
- SortedSet<String> prefixList = null;
71
+ SortedSet<String> prefixList;
72
72
  if (prefixes instanceof SortedSet<?>) {
73
73
  prefixList = (SortedSet<String>)prefixes;
74
74
  } else {
@@ -80,7 +80,7 @@ public class InclusiveNamespaces extends ElementProxy {
80
80
  if (prefix.equals("xmlns")) {
81
81
  sb.append("#default ");
82
82
  } else {
83
- sb.append(prefix + " ");
83
+ sb.append(prefix).append(' ');
84
84
  }
85
85
  }
86
86
 
@@ -306,7 +306,7 @@ class NameSpaceSymbEntry implements Cloneable {
306
306
  return null;
307
307
  }
308
308
  }
309
- };
309
+ }
310
310
 
311
311
  class SymbMap implements Cloneable {
312
312
  int free = 23;
@@ -397,7 +397,7 @@ public class XMLUtils {
397
397
  */
398
398
  public static boolean protectAgainstWrappingAttack(Node startNode, String value) {
399
399
  Node startParent = startNode.getParentNode();
400
- Node processedNode = null;
400
+ Node processedNode;
401
401
  Element foundElement = null;
402
402
 
403
403
  String id = value.trim();
@@ -458,7 +458,7 @@ public class XMLUtils {
458
458
  Node startNode, Element knownElement, String value
459
459
  ) {
460
460
  Node startParent = startNode.getParentNode();
461
- Node processedNode = null;
461
+ Node processedNode;
462
462
 
463
463
  String id = value.trim();
464
464
  if (id.charAt(0) == '#') {
@@ -0,0 +1,1749 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ /*
19
+ * $Id: DOM2DTM.java 478671 2006-11-23 21:00:31Z minchau $
20
+ */
21
+ package org.apache.xml.dtm.ref.dom2dtm;
22
+
23
+ import javax.xml.transform.SourceLocator;
24
+ import javax.xml.transform.dom.DOMSource;
25
+
26
+ import org.apache.xml.dtm.DTM;
27
+ import org.apache.xml.dtm.DTMManager;
28
+ import org.apache.xml.dtm.DTMWSFilter;
29
+ import org.apache.xml.dtm.ref.DTMDefaultBaseIterators;
30
+ import org.apache.xml.dtm.ref.DTMManagerDefault;
31
+ import org.apache.xml.dtm.ref.ExpandedNameTable;
32
+ import org.apache.xml.dtm.ref.IncrementalSAXSource;
33
+ //import org.apache.xml.dtm.ref.dom2dtm.DOM2DTMdefaultNamespaceDeclarationNode;
34
+ import org.apache.xml.res.XMLErrorResources;
35
+ import org.apache.xml.res.XMLMessages;
36
+ import org.apache.xml.utils.FastStringBuffer;
37
+ import org.apache.xml.utils.QName;
38
+ import org.apache.xml.utils.StringBufferPool;
39
+ import org.apache.xml.utils.TreeWalker;
40
+ import org.apache.xml.utils.XMLCharacterRecognizer;
41
+ import org.apache.xml.utils.XMLString;
42
+ import org.apache.xml.utils.XMLStringFactory;
43
+ import org.w3c.dom.Attr;
44
+ import org.w3c.dom.Document;
45
+ import org.w3c.dom.DocumentType;
46
+ import org.w3c.dom.Element;
47
+ import org.w3c.dom.Entity;
48
+ import org.w3c.dom.NamedNodeMap;
49
+ import org.w3c.dom.Node;
50
+ import org.xml.sax.ContentHandler;
51
+
52
+ /** The <code>DOM2DTM</code> class serves up a DOM's contents via the
53
+ * DTM API.
54
+ *
55
+ * Note that it doesn't necessarily represent a full Document
56
+ * tree. You can wrap a DOM2DTM around a specific node and its subtree
57
+ * and the right things should happen. (I don't _think_ we currently
58
+ * support DocumentFrgment nodes as roots, though that might be worth
59
+ * considering.)
60
+ *
61
+ * Note too that we do not currently attempt to track document
62
+ * mutation. If you alter the DOM after wrapping DOM2DTM around it,
63
+ * all bets are off.
64
+ * */
65
+ public class DOM2DTMExt extends DTMDefaultBaseIterators
66
+ {
67
+ // static final boolean JJK_DEBUG=false;
68
+ // static final boolean JJK_NEWCODE=true;
69
+
70
+ /** Manefest constant
71
+ */
72
+ static final String NAMESPACE_DECL_NS="http://www.w3.org/XML/1998/namespace";
73
+
74
+ /** The current position in the DOM tree. Last node examined for
75
+ * possible copying to DTM. */
76
+ transient private Node m_pos;
77
+ /** The current position in the DTM tree. Who children get appended to. */
78
+ private int m_last_parent=0;
79
+ /** The current position in the DTM tree. Who children reference as their
80
+ * previous sib. */
81
+ private int m_last_kid=NULL;
82
+
83
+ /** The top of the subtree.
84
+ * %REVIEW%: 'may not be the same as m_context if "//foo" pattern.'
85
+ * */
86
+ transient private Node m_root;
87
+
88
+ /** True iff the first element has been processed. This is used to control
89
+ synthesis of the implied xml: namespace declaration node. */
90
+ boolean m_processedFirstElement=false;
91
+
92
+ /** true if ALL the nodes in the m_root subtree have been processed;
93
+ * false if our incremental build has not yet finished scanning the
94
+ * DOM tree. */
95
+ transient private boolean m_nodesAreProcessed;
96
+
97
+ /** The node objects. The instance part of the handle indexes
98
+ * directly into this vector. Each DTM node may actually be
99
+ * composed of several DOM nodes (for example, if logically-adjacent
100
+ * Text/CDATASection nodes in the DOM have been coalesced into a
101
+ * single DTM Text node); this table points only to the first in
102
+ * that sequence. */
103
+ protected final java.util.List<Node> m_nodes = new java.util.ArrayList<Node>(12);
104
+
105
+ /**
106
+ * Construct a DOM2DTM object from a DOM node.
107
+ *
108
+ * @param mgr The DTMManager who owns this DTM.
109
+ * @param domSource the DOM source that this DTM will wrap.
110
+ * @param dtmIdentity The DTM identity ID for this DTM.
111
+ * @param whiteSpaceFilter The white space filter for this DTM, which may
112
+ * be null.
113
+ * @param xstringfactory XMLString factory for creating character content.
114
+ * @param doIndexing true if the caller considers it worth it to use
115
+ * indexing schemes.
116
+ */
117
+ public DOM2DTMExt(DTMManager mgr, DOMSource domSource,
118
+ int dtmIdentity, DTMWSFilter whiteSpaceFilter,
119
+ XMLStringFactory xstringfactory,
120
+ boolean doIndexing)
121
+ {
122
+ super(mgr, domSource, dtmIdentity, whiteSpaceFilter,
123
+ xstringfactory, doIndexing);
124
+
125
+ // Initialize DOM navigation
126
+ m_pos=m_root = domSource.getNode();
127
+ // Initialize DTM navigation
128
+ m_last_parent=m_last_kid=NULL;
129
+ m_last_kid=addNode(m_root, m_last_parent,m_last_kid, NULL);
130
+
131
+ // Apparently the domSource root may not actually be the
132
+ // Document node. If it's an Element node, we need to immediately
133
+ // add its attributes. Adapted from nextNode().
134
+ // %REVIEW% Move this logic into addNode and recurse? Cleaner!
135
+ //
136
+ // (If it's an EntityReference node, we're probably in
137
+ // seriously bad trouble. For now
138
+ // I'm just hoping nobody is ever quite that foolish... %REVIEW%)
139
+ //
140
+ // %ISSUE% What about inherited namespaces in this case?
141
+ // Do we need to special-case initialize them into the DTM model?
142
+ if(ELEMENT_NODE == m_root.getNodeType())
143
+ {
144
+ NamedNodeMap attrs=m_root.getAttributes();
145
+ int attrsize=(attrs==null) ? 0 : attrs.getLength();
146
+ if(attrsize>0)
147
+ {
148
+ int attrIndex=NULL; // start with no previous sib
149
+ for(int i=0;i<attrsize;++i)
150
+ {
151
+ // No need to force nodetype in this case;
152
+ // addNode() will take care of switching it from
153
+ // Attr to Namespace if necessary.
154
+ attrIndex=addNode(attrs.item(i),0,attrIndex,NULL);
155
+ m_firstch.setElementAt(DTM.NULL,attrIndex);
156
+ }
157
+ // Terminate list of attrs, and make sure they aren't
158
+ // considered children of the element
159
+ m_nextsib.setElementAt(DTM.NULL,attrIndex);
160
+
161
+ // IMPORTANT: This does NOT change m_last_parent or m_last_kid!
162
+ } // if attrs exist
163
+ } //if(ELEMENT_NODE)
164
+
165
+ // Initialize DTM-completed status
166
+ m_nodesAreProcessed = false;
167
+ }
168
+
169
+ /**
170
+ * Construct the node map from the node.
171
+ *
172
+ * @param node The node that is to be added to the DTM.
173
+ * @param parentIndex The current parent index.
174
+ * @param previousSibling The previous sibling index.
175
+ * @param forceNodeType If not DTM.NULL, overrides the DOM node type.
176
+ * Used to force nodes to Text rather than CDATASection when their
177
+ * coalesced value includes ordinary Text nodes (current DTM behavior).
178
+ *
179
+ * @return The index identity of the node that was added.
180
+ */
181
+ protected int addNode(Node node, int parentIndex,
182
+ int previousSibling, int forceNodeType)
183
+ {
184
+ int nodeIndex = m_nodes.size();
185
+
186
+ // Have we overflowed a DTM Identity's addressing range?
187
+ if(m_dtmIdent.size() == (nodeIndex>>>DTMManager.IDENT_DTM_NODE_BITS))
188
+ {
189
+ try
190
+ {
191
+ if(m_mgr==null)
192
+ throw new ClassCastException();
193
+
194
+ // Handle as Extended Addressing
195
+ DTMManagerDefault mgrD=(DTMManagerDefault)m_mgr;
196
+ int id=mgrD.getFirstFreeDTMID();
197
+ mgrD.addDTM(this,id,nodeIndex);
198
+ m_dtmIdent.addElement(id<<DTMManager.IDENT_DTM_NODE_BITS);
199
+ }
200
+ catch(ClassCastException e)
201
+ {
202
+ // %REVIEW% Wrong error message, but I've been told we're trying
203
+ // not to add messages right not for I18N reasons.
204
+ // %REVIEW% Should this be a Fatal Error?
205
+ error(XMLMessages.createXMLMessage(XMLErrorResources.ER_NO_DTMIDS_AVAIL, null));//"No more DTM IDs are available";
206
+ }
207
+ }
208
+
209
+ m_size++;
210
+ // ensureSize(nodeIndex);
211
+
212
+ int type;
213
+ if(NULL==forceNodeType)
214
+ type = node.getNodeType();
215
+ else
216
+ type=forceNodeType;
217
+
218
+ // %REVIEW% The Namespace Spec currently says that Namespaces are
219
+ // processed in a non-namespace-aware manner, by matching the
220
+ // QName, even though there is in fact a namespace assigned to
221
+ // these nodes in the DOM. If and when that changes, we will have
222
+ // to consider whether we check the namespace-for-namespaces
223
+ // rather than the node name.
224
+ //
225
+ // %TBD% Note that the DOM does not necessarily explicitly declare
226
+ // all the namespaces it uses. DOM Level 3 will introduce a
227
+ // namespace-normalization operation which reconciles that, and we
228
+ // can request that users invoke it or otherwise ensure that the
229
+ // tree is namespace-well-formed before passing the DOM to Xalan.
230
+ // But if they don't, what should we do about it? We probably
231
+ // don't want to alter the source DOM (and may not be able to do
232
+ // so if it's read-only). The best available answer might be to
233
+ // synthesize additional DTM Namespace Nodes that don't correspond
234
+ // to DOM Attr Nodes.
235
+ if (Node.ATTRIBUTE_NODE == type)
236
+ {
237
+ String name = node.getNodeName();
238
+
239
+ if (name.startsWith("xmlns:") || name.equals("xmlns"))
240
+ {
241
+ type = DTM.NAMESPACE_NODE;
242
+ }
243
+ }
244
+
245
+ m_nodes.add(node);
246
+
247
+ m_firstch.setElementAt(NOTPROCESSED,nodeIndex);
248
+ m_nextsib.setElementAt(NOTPROCESSED,nodeIndex);
249
+ m_prevsib.setElementAt(previousSibling,nodeIndex);
250
+ m_parent.setElementAt(parentIndex,nodeIndex);
251
+
252
+ if(DTM.NULL != parentIndex &&
253
+ type != DTM.ATTRIBUTE_NODE &&
254
+ type != DTM.NAMESPACE_NODE)
255
+ {
256
+ // If the DTM parent had no children, this becomes its first child.
257
+ if(NOTPROCESSED == m_firstch.elementAt(parentIndex))
258
+ m_firstch.setElementAt(nodeIndex,parentIndex);
259
+ }
260
+
261
+ String nsURI = node.getNamespaceURI();
262
+
263
+ // Deal with the difference between Namespace spec and XSLT
264
+ // definitions of local name. (The former says PIs don't have
265
+ // localnames; the latter says they do.)
266
+ String localName = (type == Node.PROCESSING_INSTRUCTION_NODE) ?
267
+ node.getNodeName() :
268
+ node.getLocalName();
269
+
270
+ // Hack to make DOM1 sort of work...
271
+ if(((type == Node.ELEMENT_NODE) || (type == Node.ATTRIBUTE_NODE))
272
+ && null == localName)
273
+ localName = node.getNodeName(); // -sb
274
+
275
+ ExpandedNameTable exnt = m_expandedNameTable;
276
+
277
+ // %TBD% Nodes created with the old non-namespace-aware DOM
278
+ // calls createElement() and createAttribute() will never have a
279
+ // localname. That will cause their expandedNameID to be just the
280
+ // nodeType... which will keep them from being matched
281
+ // successfully by name. Since the DOM makes no promise that
282
+ // those will participate in namespace processing, this is
283
+ // officially accepted as Not Our Fault. But it might be nice to
284
+ // issue a diagnostic message!
285
+ if(node.getLocalName()==null &&
286
+ (type==Node.ELEMENT_NODE || type==Node.ATTRIBUTE_NODE))
287
+ {
288
+ // warning("DOM 'level 1' node "+node.getNodeName()+" won't be mapped properly in DOM2DTM.");
289
+ }
290
+
291
+ int expandedNameID = (null != localName)
292
+ ? exnt.getExpandedTypeID(nsURI, localName, type) :
293
+ exnt.getExpandedTypeID(type);
294
+
295
+ m_exptype.setElementAt(expandedNameID,nodeIndex);
296
+
297
+ indexNode(expandedNameID, nodeIndex);
298
+
299
+ if (DTM.NULL != previousSibling)
300
+ m_nextsib.setElementAt(nodeIndex,previousSibling);
301
+
302
+ // This should be done after m_exptype has been set, and probably should
303
+ // always be the last thing we do
304
+ if (type == DTM.NAMESPACE_NODE)
305
+ declareNamespaceInContext(parentIndex,nodeIndex);
306
+
307
+ return nodeIndex;
308
+ }
309
+
310
+ /**
311
+ * Get the number of nodes that have been added.
312
+ */
313
+ public int getNumberOfNodes()
314
+ {
315
+ return m_nodes.size();
316
+ }
317
+
318
+ /**
319
+ * This method iterates to the next node that will be added to the table.
320
+ * Each call to this method adds a new node to the table, unless the end
321
+ * is reached, in which case it returns null.
322
+ *
323
+ * @return The true if a next node is found or false if
324
+ * there are no more nodes.
325
+ */
326
+ protected boolean nextNode()
327
+ {
328
+ // Non-recursive one-fetch-at-a-time depth-first traversal with
329
+ // attribute/namespace nodes and white-space stripping.
330
+ // Navigating the DOM is simple, navigating the DTM is simple;
331
+ // keeping track of both at once is a trifle baroque but at least
332
+ // we've avoided most of the special cases.
333
+ if (m_nodesAreProcessed)
334
+ return false;
335
+
336
+ // %REVIEW% Is this local copy Really Useful from a performance
337
+ // point of view? Or is this a false microoptimization?
338
+ Node pos=m_pos;
339
+ Node next=null;
340
+ int nexttype=NULL;
341
+
342
+ // Navigate DOM tree
343
+ do
344
+ {
345
+ // Look down to first child.
346
+ if (pos.hasChildNodes())
347
+ {
348
+ next = pos.getFirstChild();
349
+
350
+ // %REVIEW% There's probably a more elegant way to skip
351
+ // the doctype. (Just let it go and Suppress it?
352
+ if(next!=null && DOCUMENT_TYPE_NODE==next.getNodeType())
353
+ next=next.getNextSibling();
354
+
355
+ // Push DTM context -- except for children of Entity References,
356
+ // which have no DTM equivalent and cause no DTM navigation.
357
+ if(ENTITY_REFERENCE_NODE!=pos.getNodeType())
358
+ {
359
+ m_last_parent=m_last_kid;
360
+ m_last_kid=NULL;
361
+ // Whitespace-handler context stacking
362
+ if(null != m_wsfilter)
363
+ {
364
+ short wsv =
365
+ m_wsfilter.getShouldStripSpace(makeNodeHandle(m_last_parent),this);
366
+ boolean shouldStrip = (DTMWSFilter.INHERIT == wsv)
367
+ ? getShouldStripWhitespace()
368
+ : (DTMWSFilter.STRIP == wsv);
369
+ pushShouldStripWhitespace(shouldStrip);
370
+ } // if(m_wsfilter)
371
+ }
372
+ }
373
+
374
+ // If that fails, look up and right (but not past root!)
375
+ else
376
+ {
377
+ if(m_last_kid!=NULL)
378
+ {
379
+ // Last node posted at this level had no more children
380
+ // If it has _no_ children, we need to record that.
381
+ if(m_firstch.elementAt(m_last_kid)==NOTPROCESSED)
382
+ m_firstch.setElementAt(NULL,m_last_kid);
383
+ }
384
+
385
+ while(m_last_parent != NULL)
386
+ {
387
+ // %REVIEW% There's probably a more elegant way to
388
+ // skip the doctype. (Just let it go and Suppress it?
389
+ next = pos.getNextSibling();
390
+ if(next!=null && DOCUMENT_TYPE_NODE==next.getNodeType())
391
+ next=next.getNextSibling();
392
+
393
+ if(next!=null)
394
+ break; // Found it!
395
+
396
+ // No next-sibling found. Pop the DOM.
397
+ pos=pos.getParentNode();
398
+ // if(pos==null)
399
+ // {
400
+ // // %TBD% Should never arise, but I want to be sure of that...
401
+ // if(JJK_DEBUG)
402
+ // {
403
+ // System.out.println("***** DOM2DTM Pop Control Flow problem");
404
+ // for(;;); // Freeze right here!
405
+ // }
406
+ // }
407
+
408
+ // The only parents in the DTM are Elements. However,
409
+ // the DOM could contain EntityReferences. If we
410
+ // encounter one, pop it _without_ popping DTM.
411
+ if(pos!=null && ENTITY_REFERENCE_NODE == pos.getNodeType())
412
+ {
413
+ // // Nothing needs doing
414
+ // if(JJK_DEBUG) System.out.println("***** DOM2DTM popping EntRef");
415
+ }
416
+ else
417
+ {
418
+ popShouldStripWhitespace();
419
+ // Fix and pop DTM
420
+ if(m_last_kid==NULL)
421
+ m_firstch.setElementAt(NULL,m_last_parent); // Popping from an element
422
+ else
423
+ m_nextsib.setElementAt(NULL,m_last_kid); // Popping from anything else
424
+ m_last_parent=m_parent.elementAt(m_last_kid=m_last_parent);
425
+ }
426
+ }
427
+ if(m_last_parent==NULL) next=null;
428
+ }
429
+
430
+ if(next!=null) nexttype=next.getNodeType();
431
+
432
+ // If it's an entity ref, advance past it.
433
+ //
434
+ // %REVIEW% Should we let this out the door and just suppress it?
435
+ // More work, but simpler code, more likely to be correct, and
436
+ // it doesn't happen very often. We'd get rid of the loop too.
437
+ if (ENTITY_REFERENCE_NODE == nexttype) pos=next;
438
+ }
439
+ while (ENTITY_REFERENCE_NODE == nexttype);
440
+
441
+ // Did we run out of the tree?
442
+ if(next==null)
443
+ {
444
+ m_nextsib.setElementAt(NULL,0);
445
+ m_nodesAreProcessed = true;
446
+ m_pos=null;
447
+
448
+ // if(JJK_DEBUG)
449
+ // {
450
+ // System.out.println("***** DOM2DTM Crosscheck:");
451
+ // for(int i=0;i<m_nodes.size();++i)
452
+ // System.out.println(i+":\t"+m_firstch.elementAt(i)+"\t"+m_nextsib.elementAt(i));
453
+ // }
454
+
455
+ return false;
456
+ }
457
+
458
+ // Text needs some special handling:
459
+ //
460
+ // DTM may skip whitespace. This is handled by the suppressNode flag, which
461
+ // when true will keep the DTM node from being created.
462
+ //
463
+ // DTM only directly records the first DOM node of any logically-contiguous
464
+ // sequence. The lastTextNode value will be set to the last node in the
465
+ // contiguous sequence, and -- AFTER the DTM addNode -- can be used to
466
+ // advance next over this whole block. Should be simpler than special-casing
467
+ // the above loop for "Was the logically-preceeding sibling a text node".
468
+ //
469
+ // Finally, a DTM node should be considered a CDATASection only if all the
470
+ // contiguous text it covers is CDATASections. The first Text should
471
+ // force DTM to Text.
472
+
473
+ boolean suppressNode=false;
474
+ Node lastTextNode=null;
475
+
476
+ nexttype=next.getNodeType();
477
+
478
+ // nexttype=pos.getNodeType();
479
+ if(TEXT_NODE == nexttype || CDATA_SECTION_NODE == nexttype)
480
+ {
481
+ // If filtering, initially assume we're going to suppress the node
482
+ suppressNode=((null != m_wsfilter) && getShouldStripWhitespace());
483
+
484
+ // Scan logically contiguous text (siblings, plus "flattening"
485
+ // of entity reference boundaries).
486
+ if (suppressNode) {
487
+ Node n = next;
488
+ while (n != null) {
489
+ lastTextNode=n;
490
+ // Any Text node means DTM considers it all Text
491
+ if (TEXT_NODE == n.getNodeType()) nexttype = TEXT_NODE;
492
+ // Any non-whitespace in this sequence blocks whitespace
493
+ // suppression
494
+ suppressNode &= XMLCharacterRecognizer.isWhiteSpace(n.getNodeValue());
495
+
496
+ n = logicalNextDOMTextNode(n);
497
+ }
498
+ }
499
+ }
500
+
501
+ // Special handling for PIs: Some DOMs represent the XML
502
+ // Declaration as a PI. This is officially incorrect, per the DOM
503
+ // spec, but is considered a "wrong but tolerable" temporary
504
+ // workaround pending proper handling of these fields in DOM Level
505
+ // 3. We want to recognize and reject that case.
506
+ else if(PROCESSING_INSTRUCTION_NODE==nexttype)
507
+ {
508
+ suppressNode = (pos.getNodeName().toLowerCase().equals("xml"));
509
+ }
510
+
511
+
512
+ if(!suppressNode)
513
+ {
514
+ // Inserting next. NOTE that we force the node type; for
515
+ // coalesced Text, this records CDATASections adjacent to
516
+ // ordinary Text as Text.
517
+ int nextindex=addNode(next, m_last_parent, m_last_kid, nexttype);
518
+
519
+ m_last_kid=nextindex;
520
+
521
+ if(ELEMENT_NODE == nexttype)
522
+ {
523
+ int attrIndex=NULL; // start with no previous sib
524
+ // Process attributes _now_, rather than waiting.
525
+ // Simpler control flow, makes NS cache available immediately.
526
+ NamedNodeMap attrs=next.getAttributes();
527
+ int attrsize=(attrs==null) ? 0 : attrs.getLength();
528
+ if(attrsize>0)
529
+ {
530
+ for(int i=0;i<attrsize;++i)
531
+ {
532
+ // No need to force nodetype in this case;
533
+ // addNode() will take care of switching it from
534
+ // Attr to Namespace if necessary.
535
+ attrIndex=addNode(attrs.item(i), nextindex, attrIndex, NULL);
536
+ m_firstch.setElementAt(DTM.NULL,attrIndex);
537
+
538
+ // If the xml: prefix is explicitly declared
539
+ // we don't need to synthesize one.
540
+ //
541
+ // NOTE that XML Namespaces were not originally
542
+ // defined as being namespace-aware (grrr), and
543
+ // while the W3C is planning to fix this it's
544
+ // safer for now to test the QName and trust the
545
+ // parsers to prevent anyone from redefining the
546
+ // reserved xmlns: prefix
547
+ if(!m_processedFirstElement
548
+ && "xmlns:xml".equals(attrs.item(i).getNodeName()))
549
+ m_processedFirstElement=true;
550
+ }
551
+ // Terminate list of attrs, and make sure they aren't
552
+ // considered children of the element
553
+ } // if attrs exist
554
+ if(!m_processedFirstElement)
555
+ {
556
+ // The DOM might not have an explicit declaration for the
557
+ // implicit "xml:" prefix, but the XPath data model
558
+ // requires that this appear as a Namespace Node so we
559
+ // have to synthesize one. You can think of this as
560
+ // being a default attribute defined by the XML
561
+ // Namespaces spec rather than by the DTD.
562
+ attrIndex=addNode(new DOM2DTMdefaultNamespaceDeclarationNode(
563
+ (Element)next,"xml",NAMESPACE_DECL_NS,
564
+ makeNodeHandle(((attrIndex==NULL)?nextindex:attrIndex)+1)
565
+ ),
566
+ nextindex,attrIndex,NULL);
567
+ m_firstch.setElementAt(DTM.NULL,attrIndex);
568
+ m_processedFirstElement=true;
569
+ }
570
+ if(attrIndex!=NULL) m_nextsib.setElementAt(DTM.NULL,attrIndex);
571
+ } //if(ELEMENT_NODE)
572
+ } // (if !suppressNode)
573
+
574
+ // Text postprocessing: Act on values stored above
575
+ //if(TEXT_NODE == nexttype || CDATA_SECTION_NODE == nexttype)
576
+ //{
577
+ // %TBD% If nexttype was forced to TEXT, patch the DTM node
578
+ if (lastTextNode != null) next=lastTextNode; // Advance the DOM cursor over contiguous text
579
+ //}
580
+
581
+ // Remember where we left off.
582
+ m_pos=next;
583
+ return true;
584
+ }
585
+
586
+
587
+ /**
588
+ * Return an DOM node for the given node.
589
+ *
590
+ * @param nodeHandle The node ID.
591
+ *
592
+ * @return A node representation of the DTM node.
593
+ */
594
+ public Node getNode(int nodeHandle)
595
+ {
596
+
597
+ int identity = makeNodeIdentity(nodeHandle);
598
+
599
+ return (Node) m_nodes.get(identity);
600
+ }
601
+
602
+ /**
603
+ * Get a Node from an identity index.
604
+ *
605
+ * NEEDSDOC @param nodeIdentity
606
+ *
607
+ * NEEDSDOC ($objectName$) @return
608
+ */
609
+ protected Node lookupNode(int nodeIdentity)
610
+ {
611
+ return (Node) m_nodes.get(nodeIdentity);
612
+ }
613
+
614
+ /**
615
+ * Get the next node identity value in the list, and call the iterator
616
+ * if it hasn't been added yet.
617
+ *
618
+ * @param identity The node identity (index).
619
+ * @return identity+1, or DTM.NULL.
620
+ */
621
+ protected int getNextNodeIdentity(int identity)
622
+ {
623
+
624
+ identity += 1;
625
+
626
+ if (identity >= m_nodes.size())
627
+ {
628
+ if (!nextNode())
629
+ identity = DTM.NULL;
630
+ }
631
+
632
+ return identity;
633
+ }
634
+
635
+ /**
636
+ * Get the handle from a Node.
637
+ * <p>%OPT% This will be pretty slow.</p>
638
+ *
639
+ * <p>%OPT% An XPath-like search (walk up DOM to root, tracking path;
640
+ * walk down DTM reconstructing path) might be considerably faster
641
+ * on later nodes in large documents. That might also imply improving
642
+ * this call to handle nodes which would be in this DTM but
643
+ * have not yet been built, which might or might not be a Good Thing.</p>
644
+ *
645
+ * %REVIEW% This relies on being able to test node-identity via
646
+ * object-identity. DTM2DOM proxying is a great example of a case where
647
+ * that doesn't work. DOM Level 3 will provide the isSameNode() method
648
+ * to fix that, but until then this is going to be flaky.
649
+ *
650
+ * @param node A node, which may be null.
651
+ *
652
+ * @return The node handle or <code>DTM.NULL</code>.
653
+ */
654
+ public int getHandleFromNode(Node node)
655
+ {
656
+ if (null != node)
657
+ {
658
+ int len = m_nodes.size();
659
+ boolean isMore;
660
+ int i = 0;
661
+ do
662
+ {
663
+ for (; i < len; i++)
664
+ {
665
+ if (m_nodes.get(i) == node)
666
+ return makeNodeHandle(i);
667
+ }
668
+
669
+ isMore = nextNode();
670
+
671
+ len = m_nodes.size();
672
+
673
+ }
674
+ while(isMore || i < len);
675
+ }
676
+
677
+ return DTM.NULL;
678
+ }
679
+
680
+ /** Get the handle from a Node. This is a more robust version of
681
+ * getHandleFromNode, intended to be usable by the public.
682
+ *
683
+ * <p>%OPT% This will be pretty slow.</p>
684
+ *
685
+ * %REVIEW% This relies on being able to test node-identity via
686
+ * object-identity. DTM2DOM proxying is a great example of a case where
687
+ * that doesn't work. DOM Level 3 will provide the isSameNode() method
688
+ * to fix that, but until then this is going to be flaky.
689
+ *
690
+ * @param node A node, which may be null.
691
+ *
692
+ * @return The node handle or <code>DTM.NULL</code>. */
693
+ public int getHandleOfNode(Node node)
694
+ {
695
+ if (null != node)
696
+ {
697
+ // Is Node actually within the same document? If not, don't search!
698
+ // This would be easier if m_root was always the Document node, but
699
+ // we decided to allow wrapping a DTM around a subtree.
700
+ if((m_root==node) ||
701
+ (m_root.getNodeType()==DOCUMENT_NODE &&
702
+ m_root==node.getOwnerDocument()) ||
703
+ (m_root.getNodeType()!=DOCUMENT_NODE &&
704
+ m_root.getOwnerDocument()==node.getOwnerDocument())
705
+ )
706
+ {
707
+ // If node _is_ in m_root's tree, find its handle
708
+ //
709
+ // %OPT% This check may be improved significantly when DOM
710
+ // Level 3 nodeKey and relative-order tests become
711
+ // available!
712
+ for(Node cursor=node;
713
+ cursor!=null;
714
+ cursor=
715
+ (cursor.getNodeType()!=ATTRIBUTE_NODE)
716
+ ? cursor.getParentNode()
717
+ : ((org.w3c.dom.Attr)cursor).getOwnerElement())
718
+ {
719
+ if(cursor==m_root)
720
+ // We know this node; find its handle.
721
+ return getHandleFromNode(node);
722
+ } // for ancestors of node
723
+ } // if node and m_root in same Document
724
+ } // if node!=null
725
+
726
+ return DTM.NULL;
727
+ }
728
+
729
+ /**
730
+ * Retrieves an attribute node by by qualified name and namespace URI.
731
+ *
732
+ * @param nodeHandle int Handle of the node upon which to look up this attribute..
733
+ * @param namespaceURI The namespace URI of the attribute to
734
+ * retrieve, or null.
735
+ * @param name The local name of the attribute to
736
+ * retrieve.
737
+ * @return The attribute node handle with the specified name (
738
+ * <code>nodeName</code>) or <code>DTM.NULL</code> if there is no such
739
+ * attribute.
740
+ */
741
+ public int getAttributeNode(int nodeHandle, String namespaceURI,
742
+ String name)
743
+ {
744
+
745
+ // %OPT% This is probably slower than it needs to be.
746
+ if (null == namespaceURI)
747
+ namespaceURI = "";
748
+
749
+ int type = getNodeType(nodeHandle);
750
+
751
+ if (DTM.ELEMENT_NODE == type)
752
+ {
753
+
754
+ // Assume that attributes immediately follow the element.
755
+ int identity = makeNodeIdentity(nodeHandle);
756
+
757
+ while (DTM.NULL != (identity = getNextNodeIdentity(identity)))
758
+ {
759
+ // Assume this can not be null.
760
+ type = _type(identity);
761
+
762
+ // %REVIEW%
763
+ // Should namespace nodes be retrievable DOM-style as attrs?
764
+ // If not we need a separate function... which may be desirable
765
+ // architecturally, but which is ugly from a code point of view.
766
+ // (If we REALLY insist on it, this code should become a subroutine
767
+ // of both -- retrieve the node, then test if the type matches
768
+ // what you're looking for.)
769
+ if (type == DTM.ATTRIBUTE_NODE || type==DTM.NAMESPACE_NODE)
770
+ {
771
+ Node node = lookupNode(identity);
772
+ String nodeuri = node.getNamespaceURI();
773
+
774
+ if (null == nodeuri)
775
+ nodeuri = "";
776
+
777
+ String nodelocalname = node.getLocalName();
778
+
779
+ if (nodeuri.equals(namespaceURI) && name.equals(nodelocalname))
780
+ return makeNodeHandle(identity);
781
+ }
782
+
783
+ else // if (DTM.NAMESPACE_NODE != type)
784
+ {
785
+ break;
786
+ }
787
+ }
788
+ }
789
+
790
+ return DTM.NULL;
791
+ }
792
+
793
+ /**
794
+ * Get the string-value of a node as a String object
795
+ * (see http://www.w3.org/TR/xpath#data-model
796
+ * for the definition of a node's string-value).
797
+ *
798
+ * @param nodeHandle The node ID.
799
+ *
800
+ * @return A string object that represents the string-value of the given node.
801
+ */
802
+ public XMLString getStringValue(int nodeHandle)
803
+ {
804
+
805
+ int type = getNodeType(nodeHandle);
806
+ Node node = getNode(nodeHandle);
807
+ // %TBD% If an element only has one text node, we should just use it
808
+ // directly.
809
+ if(DTM.ELEMENT_NODE == type || DTM.DOCUMENT_NODE == type
810
+ || DTM.DOCUMENT_FRAGMENT_NODE == type)
811
+ {
812
+ FastStringBuffer buf = StringBufferPool.get();
813
+ String s;
814
+
815
+ try
816
+ {
817
+ getNodeData(node, buf);
818
+
819
+ s = (buf.length() > 0) ? buf.toString() : "";
820
+ }
821
+ finally
822
+ {
823
+ StringBufferPool.free(buf);
824
+ }
825
+
826
+ return m_xstrf.newstr( s );
827
+ }
828
+ else if(TEXT_NODE == type || CDATA_SECTION_NODE == type)
829
+ {
830
+ // If this is a DTM text node, it may be made of multiple DOM text
831
+ // nodes -- including navigating into Entity References. DOM2DTM
832
+ // records the first node in the sequence and requires that we
833
+ // pick up the others when we retrieve the DTM node's value.
834
+ //
835
+ // %REVIEW% DOM Level 3 is expected to add a "whole text"
836
+ // retrieval method which performs this function for us.
837
+ FastStringBuffer buf = StringBufferPool.get();
838
+ while(node!=null)
839
+ {
840
+ buf.append(node.getNodeValue());
841
+ node=logicalNextDOMTextNode(node);
842
+ }
843
+ String s=(buf.length() > 0) ? buf.toString() : "";
844
+ StringBufferPool.free(buf);
845
+ return m_xstrf.newstr( s );
846
+ }
847
+ else
848
+ return m_xstrf.newstr( node.getNodeValue() );
849
+ }
850
+
851
+ /**
852
+ * Determine if the string-value of a node is whitespace
853
+ *
854
+ * @param nodeHandle The node Handle.
855
+ *
856
+ * @return Return true if the given node is whitespace.
857
+ */
858
+ public boolean isWhitespace(int nodeHandle)
859
+ {
860
+ int type = getNodeType(nodeHandle);
861
+ Node node = getNode(nodeHandle);
862
+ if(TEXT_NODE == type || CDATA_SECTION_NODE == type)
863
+ {
864
+ // If this is a DTM text node, it may be made of multiple DOM text
865
+ // nodes -- including navigating into Entity References. DOM2DTM
866
+ // records the first node in the sequence and requires that we
867
+ // pick up the others when we retrieve the DTM node's value.
868
+ //
869
+ // %REVIEW% DOM Level 3 is expected to add a "whole text"
870
+ // retrieval method which performs this function for us.
871
+ FastStringBuffer buf = StringBufferPool.get();
872
+ while(node!=null)
873
+ {
874
+ buf.append(node.getNodeValue());
875
+ node=logicalNextDOMTextNode(node);
876
+ }
877
+ boolean b = buf.isWhitespace(0, buf.length());
878
+ StringBufferPool.free(buf);
879
+ return b;
880
+ }
881
+ return false;
882
+ }
883
+
884
+ /**
885
+ * Retrieve the text content of a DOM subtree, appending it into a
886
+ * user-supplied FastStringBuffer object. Note that attributes are
887
+ * not considered part of the content of an element.
888
+ * <p>
889
+ * There are open questions regarding whitespace stripping.
890
+ * Currently we make no special effort in that regard, since the standard
891
+ * DOM doesn't yet provide DTD-based information to distinguish
892
+ * whitespace-in-element-context from genuine #PCDATA. Note that we
893
+ * should probably also consider xml:space if/when we address this.
894
+ * DOM Level 3 may solve the problem for us.
895
+ * <p>
896
+ * %REVIEW% Actually, since this method operates on the DOM side of the
897
+ * fence rather than the DTM side, it SHOULDN'T do
898
+ * any special handling. The DOM does what the DOM does; if you want
899
+ * DTM-level abstractions, use DTM-level methods.
900
+ *
901
+ * @param node Node whose subtree is to be walked, gathering the
902
+ * contents of all Text or CDATASection nodes.
903
+ * @param buf FastStringBuffer into which the contents of the text
904
+ * nodes are to be concatenated.
905
+ */
906
+ protected static void getNodeData(Node node, FastStringBuffer buf)
907
+ {
908
+
909
+ switch (node.getNodeType())
910
+ {
911
+ case Node.DOCUMENT_FRAGMENT_NODE :
912
+ case Node.DOCUMENT_NODE :
913
+ case Node.ELEMENT_NODE :
914
+ {
915
+ for (Node child = node.getFirstChild(); null != child;
916
+ child = child.getNextSibling())
917
+ {
918
+ getNodeData(child, buf);
919
+ }
920
+ }
921
+ break;
922
+ case Node.TEXT_NODE :
923
+ case Node.CDATA_SECTION_NODE :
924
+ case Node.ATTRIBUTE_NODE : // Never a child but might be our starting node
925
+ buf.append(node.getNodeValue());
926
+ break;
927
+ case Node.PROCESSING_INSTRUCTION_NODE :
928
+ // warning(XPATHErrorResources.WG_PARSING_AND_PREPARING);
929
+ break;
930
+ default :
931
+ // ignore
932
+ break;
933
+ }
934
+ }
935
+
936
+ /**
937
+ * Given a node handle, return its DOM-style node name. This will
938
+ * include names such as #text or #document.
939
+ *
940
+ * @param nodeHandle the id of the node.
941
+ * @return String Name of this node, which may be an empty string.
942
+ * %REVIEW% Document when empty string is possible...
943
+ * %REVIEW-COMMENT% It should never be empty, should it?
944
+ */
945
+ public String getNodeName(int nodeHandle)
946
+ {
947
+
948
+ Node node = getNode(nodeHandle);
949
+
950
+ // Assume non-null.
951
+ return node.getNodeName();
952
+ }
953
+
954
+ /**
955
+ * Given a node handle, return the XPath node name. This should be
956
+ * the name as described by the XPath data model, NOT the DOM-style
957
+ * name.
958
+ *
959
+ * @param nodeHandle the id of the node.
960
+ * @return String Name of this node, which may be an empty string.
961
+ */
962
+ public String getNodeNameX(int nodeHandle)
963
+ {
964
+
965
+ String name;
966
+ short type = getNodeType(nodeHandle);
967
+
968
+ switch (type)
969
+ {
970
+ case DTM.NAMESPACE_NODE :
971
+ {
972
+ Node node = getNode(nodeHandle);
973
+
974
+ // assume not null.
975
+ name = node.getNodeName();
976
+ if(name.startsWith("xmlns:"))
977
+ {
978
+ name = QName.getLocalPart(name);
979
+ }
980
+ else if(name.equals("xmlns"))
981
+ {
982
+ name = "";
983
+ }
984
+ }
985
+ break;
986
+ case DTM.ATTRIBUTE_NODE :
987
+ case DTM.ELEMENT_NODE :
988
+ case DTM.ENTITY_REFERENCE_NODE :
989
+ case DTM.PROCESSING_INSTRUCTION_NODE :
990
+ {
991
+ Node node = getNode(nodeHandle);
992
+
993
+ // assume not null.
994
+ name = node.getNodeName();
995
+ }
996
+ break;
997
+ default :
998
+ name = "";
999
+ }
1000
+
1001
+ return name;
1002
+ }
1003
+
1004
+ /**
1005
+ * Given a node handle, return its XPath-style localname.
1006
+ * (As defined in Namespaces, this is the portion of the name after any
1007
+ * colon character).
1008
+ *
1009
+ * @param nodeHandle the id of the node.
1010
+ * @return String Local name of this node.
1011
+ */
1012
+ public String getLocalName(int nodeHandle)
1013
+ {
1014
+ // if(JJK_NEWCODE)
1015
+ // {
1016
+ int id=makeNodeIdentity(nodeHandle);
1017
+ if(NULL==id) return null;
1018
+ Node newnode=(Node)m_nodes.get(id);
1019
+ String newname=newnode.getLocalName();
1020
+ if (null == newname)
1021
+ {
1022
+ // XSLT treats PIs, and possibly other things, as having QNames.
1023
+ String qname = newnode.getNodeName();
1024
+ if('#'==qname.charAt(0))
1025
+ {
1026
+ // Match old default for this function
1027
+ // This conversion may or may not be necessary
1028
+ newname="";
1029
+ }
1030
+ else
1031
+ {
1032
+ int index = qname.indexOf(':');
1033
+ newname = (index < 0) ? qname : qname.substring(index + 1);
1034
+ }
1035
+ }
1036
+ return newname;
1037
+ // }
1038
+ // else
1039
+ // {
1040
+ // String name;
1041
+ // short type = getNodeType(nodeHandle);
1042
+ // switch (type)
1043
+ // {
1044
+ // case DTM.ATTRIBUTE_NODE :
1045
+ // case DTM.ELEMENT_NODE :
1046
+ // case DTM.ENTITY_REFERENCE_NODE :
1047
+ // case DTM.NAMESPACE_NODE :
1048
+ // case DTM.PROCESSING_INSTRUCTION_NODE :
1049
+ // {
1050
+ // Node node = getNode(nodeHandle);
1051
+ //
1052
+ // // assume not null.
1053
+ // name = node.getLocalName();
1054
+ //
1055
+ // if (null == name)
1056
+ // {
1057
+ // String qname = node.getNodeName();
1058
+ // int index = qname.indexOf(':');
1059
+ //
1060
+ // name = (index < 0) ? qname : qname.substring(index + 1);
1061
+ // }
1062
+ // }
1063
+ // break;
1064
+ // default :
1065
+ // name = "";
1066
+ // }
1067
+ // return name;
1068
+ // }
1069
+ }
1070
+
1071
+ /**
1072
+ * Given a namespace handle, return the prefix that the namespace decl is
1073
+ * mapping.
1074
+ * Given a node handle, return the prefix used to map to the namespace.
1075
+ *
1076
+ * <p> %REVIEW% Are you sure you want "" for no prefix? </p>
1077
+ * <p> %REVIEW-COMMENT% I think so... not totally sure. -sb </p>
1078
+ *
1079
+ * @param nodeHandle the id of the node.
1080
+ * @return String prefix of this node's name, or "" if no explicit
1081
+ * namespace prefix was given.
1082
+ */
1083
+ public String getPrefix(int nodeHandle)
1084
+ {
1085
+
1086
+ String prefix;
1087
+ short type = getNodeType(nodeHandle);
1088
+
1089
+ switch (type)
1090
+ {
1091
+ case DTM.NAMESPACE_NODE :
1092
+ {
1093
+ Node node = getNode(nodeHandle);
1094
+
1095
+ // assume not null.
1096
+ String qname = node.getNodeName();
1097
+ int index = qname.indexOf(':');
1098
+
1099
+ prefix = (index < 0) ? "" : qname.substring(index + 1);
1100
+ }
1101
+ break;
1102
+ case DTM.ATTRIBUTE_NODE :
1103
+ case DTM.ELEMENT_NODE :
1104
+ {
1105
+ Node node = getNode(nodeHandle);
1106
+
1107
+ // assume not null.
1108
+ String qname = node.getNodeName();
1109
+ int index = qname.indexOf(':');
1110
+
1111
+ prefix = (index < 0) ? "" : qname.substring(0, index);
1112
+ }
1113
+ break;
1114
+ default :
1115
+ prefix = "";
1116
+ }
1117
+
1118
+ return prefix;
1119
+ }
1120
+
1121
+ /**
1122
+ * Given a node handle, return its DOM-style namespace URI
1123
+ * (As defined in Namespaces, this is the declared URI which this node's
1124
+ * prefix -- or default in lieu thereof -- was mapped to.)
1125
+ *
1126
+ * <p>%REVIEW% Null or ""? -sb</p>
1127
+ *
1128
+ * @param nodeHandle the id of the node.
1129
+ * @return String URI value of this node's namespace, or null if no
1130
+ * namespace was resolved.
1131
+ */
1132
+ public String getNamespaceURI(int nodeHandle)
1133
+ {
1134
+ // if(JJK_NEWCODE)
1135
+ // {
1136
+ int id=makeNodeIdentity(nodeHandle);
1137
+ if(id==NULL) return null;
1138
+ Node node=(Node)m_nodes.get(id);
1139
+ return node.getNamespaceURI();
1140
+ // }
1141
+ // else
1142
+ // {
1143
+ // String nsuri;
1144
+ // short type = getNodeType(nodeHandle);
1145
+ //
1146
+ // switch (type)
1147
+ // {
1148
+ // case DTM.ATTRIBUTE_NODE :
1149
+ // case DTM.ELEMENT_NODE :
1150
+ // case DTM.ENTITY_REFERENCE_NODE :
1151
+ // case DTM.NAMESPACE_NODE :
1152
+ // case DTM.PROCESSING_INSTRUCTION_NODE :
1153
+ // {
1154
+ // Node node = getNode(nodeHandle);
1155
+ //
1156
+ // // assume not null.
1157
+ // nsuri = node.getNamespaceURI();
1158
+ //
1159
+ // // %TBD% Handle DOM1?
1160
+ // }
1161
+ // break;
1162
+ // default :
1163
+ // nsuri = null;
1164
+ // }
1165
+ //
1166
+ // return nsuri;
1167
+ // }
1168
+ }
1169
+
1170
+ /** Utility function: Given a DOM Text node, determine whether it is
1171
+ * logically followed by another Text or CDATASection node. This may
1172
+ * involve traversing into Entity References.
1173
+ *
1174
+ * %REVIEW% DOM Level 3 is expected to add functionality which may
1175
+ * allow us to retire this.
1176
+ */
1177
+ private Node logicalNextDOMTextNode(Node n)
1178
+ {
1179
+ Node p=n.getNextSibling();
1180
+ if(p==null)
1181
+ {
1182
+ // Walk out of any EntityReferenceNodes that ended with text
1183
+ for(n=n.getParentNode();
1184
+ n!=null && ENTITY_REFERENCE_NODE == n.getNodeType();
1185
+ n=n.getParentNode())
1186
+ {
1187
+ p=n.getNextSibling();
1188
+ if(p!=null)
1189
+ break;
1190
+ }
1191
+ }
1192
+ n=p;
1193
+ while(n!=null && ENTITY_REFERENCE_NODE == n.getNodeType())
1194
+ {
1195
+ // Walk into any EntityReferenceNodes that start with text
1196
+ if(n.hasChildNodes())
1197
+ n=n.getFirstChild();
1198
+ else
1199
+ n=n.getNextSibling();
1200
+ }
1201
+ if(n!=null)
1202
+ {
1203
+ // Found a logical next sibling. Is it text?
1204
+ int ntype=n.getNodeType();
1205
+ if(TEXT_NODE != ntype && CDATA_SECTION_NODE != ntype)
1206
+ n=null;
1207
+ }
1208
+ return n;
1209
+ }
1210
+
1211
+ /**
1212
+ * Given a node handle, return its node value. This is mostly
1213
+ * as defined by the DOM, but may ignore some conveniences.
1214
+ * <p>
1215
+ *
1216
+ * @param nodeHandle The node id.
1217
+ * @return String Value of this node, or null if not
1218
+ * meaningful for this node type.
1219
+ */
1220
+ public String getNodeValue(int nodeHandle)
1221
+ {
1222
+ // The _type(nodeHandle) call was taking the lion's share of our
1223
+ // time, and was wrong anyway since it wasn't coverting handle to
1224
+ // identity. Inlined it.
1225
+ int type = _exptype(makeNodeIdentity(nodeHandle));
1226
+ type=(NULL != type) ? getNodeType(nodeHandle) : NULL;
1227
+
1228
+ if(TEXT_NODE!=type && CDATA_SECTION_NODE!=type)
1229
+ return getNode(nodeHandle).getNodeValue();
1230
+
1231
+ // If this is a DTM text node, it may be made of multiple DOM text
1232
+ // nodes -- including navigating into Entity References. DOM2DTM
1233
+ // records the first node in the sequence and requires that we
1234
+ // pick up the others when we retrieve the DTM node's value.
1235
+ //
1236
+ // %REVIEW% DOM Level 3 is expected to add a "whole text"
1237
+ // retrieval method which performs this function for us.
1238
+ Node node = getNode(nodeHandle);
1239
+ Node n=logicalNextDOMTextNode(node);
1240
+ if(n==null)
1241
+ return node.getNodeValue();
1242
+
1243
+ FastStringBuffer buf = StringBufferPool.get();
1244
+ buf.append(node.getNodeValue());
1245
+ while(n!=null)
1246
+ {
1247
+ buf.append(n.getNodeValue());
1248
+ n=logicalNextDOMTextNode(n);
1249
+ }
1250
+ String s = (buf.length() > 0) ? buf.toString() : "";
1251
+ StringBufferPool.free(buf);
1252
+ return s;
1253
+ }
1254
+
1255
+ /**
1256
+ * A document type declaration information item has the following properties:
1257
+ *
1258
+ * 1. [system identifier] The system identifier of the external subset, if
1259
+ * it exists. Otherwise this property has no value.
1260
+ *
1261
+ * @return the system identifier String object, or null if there is none.
1262
+ */
1263
+ public String getDocumentTypeDeclarationSystemIdentifier()
1264
+ {
1265
+
1266
+ Document doc;
1267
+
1268
+ if (m_root.getNodeType() == Node.DOCUMENT_NODE)
1269
+ doc = (Document) m_root;
1270
+ else
1271
+ doc = m_root.getOwnerDocument();
1272
+
1273
+ if (null != doc)
1274
+ {
1275
+ DocumentType dtd = doc.getDoctype();
1276
+
1277
+ if (null != dtd)
1278
+ {
1279
+ return dtd.getSystemId();
1280
+ }
1281
+ }
1282
+
1283
+ return null;
1284
+ }
1285
+
1286
+ /**
1287
+ * Return the public identifier of the external subset,
1288
+ * normalized as described in 4.2.2 External Entities [XML]. If there is
1289
+ * no external subset or if it has no public identifier, this property
1290
+ * has no value.
1291
+ *
1292
+ * @return the public identifier String object, or null if there is none.
1293
+ */
1294
+ public String getDocumentTypeDeclarationPublicIdentifier()
1295
+ {
1296
+
1297
+ Document doc;
1298
+
1299
+ if (m_root.getNodeType() == Node.DOCUMENT_NODE)
1300
+ doc = (Document) m_root;
1301
+ else
1302
+ doc = m_root.getOwnerDocument();
1303
+
1304
+ if (null != doc)
1305
+ {
1306
+ DocumentType dtd = doc.getDoctype();
1307
+
1308
+ if (null != dtd)
1309
+ {
1310
+ return dtd.getPublicId();
1311
+ }
1312
+ }
1313
+
1314
+ return null;
1315
+ }
1316
+
1317
+ /**
1318
+ * Returns the <code>Element</code> whose <code>ID</code> is given by
1319
+ * <code>elementId</code>. If no such element exists, returns
1320
+ * <code>DTM.NULL</code>. Behavior is not defined if more than one element
1321
+ * has this <code>ID</code>. Attributes (including those
1322
+ * with the name "ID") are not of type ID unless so defined by DTD/Schema
1323
+ * information available to the DTM implementation.
1324
+ * Implementations that do not know whether attributes are of type ID or
1325
+ * not are expected to return <code>DTM.NULL</code>.
1326
+ *
1327
+ * <p>%REVIEW% Presumably IDs are still scoped to a single document,
1328
+ * and this operation searches only within a single document, right?
1329
+ * Wouldn't want collisions between DTMs in the same process.</p>
1330
+ *
1331
+ * @param elementId The unique <code>id</code> value for an element.
1332
+ * @return The handle of the matching element.
1333
+ */
1334
+ public int getElementById(String elementId)
1335
+ {
1336
+
1337
+ Document doc = (m_root.getNodeType() == Node.DOCUMENT_NODE)
1338
+ ? (Document) m_root : m_root.getOwnerDocument();
1339
+
1340
+ if(null != doc)
1341
+ {
1342
+ Node elem = doc.getElementById(elementId);
1343
+ if(null != elem)
1344
+ {
1345
+ int elemHandle = getHandleFromNode(elem);
1346
+
1347
+ if(DTM.NULL == elemHandle)
1348
+ {
1349
+ int identity = m_nodes.size()-1;
1350
+ while (DTM.NULL != (identity = getNextNodeIdentity(identity)))
1351
+ {
1352
+ Node node = getNode(identity);
1353
+ if(node == elem)
1354
+ {
1355
+ elemHandle = getHandleFromNode(elem);
1356
+ break;
1357
+ }
1358
+ }
1359
+ }
1360
+
1361
+ return elemHandle;
1362
+ }
1363
+
1364
+ }
1365
+ return DTM.NULL;
1366
+ }
1367
+
1368
+ /**
1369
+ * The getUnparsedEntityURI function returns the URI of the unparsed
1370
+ * entity with the specified name in the same document as the context
1371
+ * node (see [3.3 Unparsed Entities]). It returns the empty string if
1372
+ * there is no such entity.
1373
+ * <p>
1374
+ * XML processors may choose to use the System Identifier (if one
1375
+ * is provided) to resolve the entity, rather than the URI in the
1376
+ * Public Identifier. The details are dependent on the processor, and
1377
+ * we would have to support some form of plug-in resolver to handle
1378
+ * this properly. Currently, we simply return the System Identifier if
1379
+ * present, and hope that it a usable URI or that our caller can
1380
+ * map it to one.
1381
+ * TODO: Resolve Public Identifiers... or consider changing function name.
1382
+ * <p>
1383
+ * If we find a relative URI
1384
+ * reference, XML expects it to be resolved in terms of the base URI
1385
+ * of the document. The DOM doesn't do that for us, and it isn't
1386
+ * entirely clear whether that should be done here; currently that's
1387
+ * pushed up to a higher level of our application. (Note that DOM Level
1388
+ * 1 didn't store the document's base URI.)
1389
+ * TODO: Consider resolving Relative URIs.
1390
+ * <p>
1391
+ * (The DOM's statement that "An XML processor may choose to
1392
+ * completely expand entities before the structure model is passed
1393
+ * to the DOM" refers only to parsed entities, not unparsed, and hence
1394
+ * doesn't affect this function.)
1395
+ *
1396
+ * @param name A string containing the Entity Name of the unparsed
1397
+ * entity.
1398
+ *
1399
+ * @return String containing the URI of the Unparsed Entity, or an
1400
+ * empty string if no such entity exists.
1401
+ */
1402
+ public String getUnparsedEntityURI(String name)
1403
+ {
1404
+
1405
+ String url = "";
1406
+ Document doc = (m_root.getNodeType() == Node.DOCUMENT_NODE)
1407
+ ? (Document) m_root : m_root.getOwnerDocument();
1408
+
1409
+ if (null != doc)
1410
+ {
1411
+ DocumentType doctype = doc.getDoctype();
1412
+
1413
+ if (null != doctype)
1414
+ {
1415
+ NamedNodeMap entities = doctype.getEntities();
1416
+ if(null == entities)
1417
+ return url;
1418
+ Entity entity = (Entity) entities.getNamedItem(name);
1419
+ if(null == entity)
1420
+ return url;
1421
+
1422
+ String notationName = entity.getNotationName();
1423
+
1424
+ if (null != notationName) // then it's unparsed
1425
+ {
1426
+ // The draft says: "The XSLT processor may use the public
1427
+ // identifier to generate a URI for the entity instead of the URI
1428
+ // specified in the system identifier. If the XSLT processor does
1429
+ // not use the public identifier to generate the URI, it must use
1430
+ // the system identifier; if the system identifier is a relative
1431
+ // URI, it must be resolved into an absolute URI using the URI of
1432
+ // the resource containing the entity declaration as the base
1433
+ // URI [RFC2396]."
1434
+ // So I'm falling a bit short here.
1435
+ url = entity.getSystemId();
1436
+
1437
+ if (null == url)
1438
+ {
1439
+ url = entity.getPublicId();
1440
+ }
1441
+ else
1442
+ {
1443
+ // This should be resolved to an absolute URL, but that's hard
1444
+ // to do from here.
1445
+ }
1446
+ }
1447
+ }
1448
+ }
1449
+
1450
+ return url;
1451
+ }
1452
+
1453
+ /**
1454
+ * 5. [specified] A flag indicating whether this attribute was actually
1455
+ * specified in the start-tag of its element, or was defaulted from the
1456
+ * DTD.
1457
+ *
1458
+ * @param attributeHandle the attribute handle
1459
+ * @return <code>true</code> if the attribute was specified;
1460
+ * <code>false</code> if it was defaulted.
1461
+ */
1462
+ public boolean isAttributeSpecified(int attributeHandle)
1463
+ {
1464
+ int type = getNodeType(attributeHandle);
1465
+
1466
+ if (DTM.ATTRIBUTE_NODE == type)
1467
+ {
1468
+ Attr attr = (Attr)getNode(attributeHandle);
1469
+ return attr.getSpecified();
1470
+ }
1471
+ return false;
1472
+ }
1473
+
1474
+ /** Bind an IncrementalSAXSource to this DTM. NOT RELEVANT for DOM2DTM, since
1475
+ * we're wrapped around an existing DOM.
1476
+ *
1477
+ * @param source The IncrementalSAXSource that we want to recieve events from
1478
+ * on demand.
1479
+ */
1480
+ public void setIncrementalSAXSource(IncrementalSAXSource source)
1481
+ {
1482
+ }
1483
+
1484
+ /** getContentHandler returns "our SAX builder" -- the thing that
1485
+ * someone else should send SAX events to in order to extend this
1486
+ * DTM model.
1487
+ *
1488
+ * @return null if this model doesn't respond to SAX events,
1489
+ * "this" if the DTM object has a built-in SAX ContentHandler,
1490
+ * the IncrmentalSAXSource if we're bound to one and should receive
1491
+ * the SAX stream via it for incremental build purposes...
1492
+ * */
1493
+ public org.xml.sax.ContentHandler getContentHandler()
1494
+ {
1495
+ return null;
1496
+ }
1497
+
1498
+ /**
1499
+ * Return this DTM's lexical handler.
1500
+ *
1501
+ * %REVIEW% Should this return null if constrution already done/begun?
1502
+ *
1503
+ * @return null if this model doesn't respond to lexical SAX events,
1504
+ * "this" if the DTM object has a built-in SAX ContentHandler,
1505
+ * the IncrementalSAXSource if we're bound to one and should receive
1506
+ * the SAX stream via it for incremental build purposes...
1507
+ */
1508
+ public org.xml.sax.ext.LexicalHandler getLexicalHandler()
1509
+ {
1510
+
1511
+ return null;
1512
+ }
1513
+
1514
+
1515
+ /**
1516
+ * Return this DTM's EntityResolver.
1517
+ *
1518
+ * @return null if this model doesn't respond to SAX entity ref events.
1519
+ */
1520
+ public org.xml.sax.EntityResolver getEntityResolver()
1521
+ {
1522
+
1523
+ return null;
1524
+ }
1525
+
1526
+ /**
1527
+ * Return this DTM's DTDHandler.
1528
+ *
1529
+ * @return null if this model doesn't respond to SAX dtd events.
1530
+ */
1531
+ public org.xml.sax.DTDHandler getDTDHandler()
1532
+ {
1533
+
1534
+ return null;
1535
+ }
1536
+
1537
+ /**
1538
+ * Return this DTM's ErrorHandler.
1539
+ *
1540
+ * @return null if this model doesn't respond to SAX error events.
1541
+ */
1542
+ public org.xml.sax.ErrorHandler getErrorHandler()
1543
+ {
1544
+
1545
+ return null;
1546
+ }
1547
+
1548
+ /**
1549
+ * Return this DTM's DeclHandler.
1550
+ *
1551
+ * @return null if this model doesn't respond to SAX Decl events.
1552
+ */
1553
+ public org.xml.sax.ext.DeclHandler getDeclHandler()
1554
+ {
1555
+
1556
+ return null;
1557
+ }
1558
+
1559
+ /** @return true iff we're building this model incrementally (eg
1560
+ * we're partnered with a IncrementalSAXSource) and thus require that the
1561
+ * transformation and the parse run simultaneously. Guidance to the
1562
+ * DTMManager.
1563
+ * */
1564
+ public boolean needsTwoThreads()
1565
+ {
1566
+ return false;
1567
+ }
1568
+
1569
+ // ========== Direct SAX Dispatch, for optimization purposes ========
1570
+
1571
+ /**
1572
+ * Returns whether the specified <var>ch</var> conforms to the XML 1.0 definition
1573
+ * of whitespace. Refer to <A href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S">
1574
+ * the definition of <CODE>S</CODE></A> for details.
1575
+ * @param ch Character to check as XML whitespace.
1576
+ * @return =true if <var>ch</var> is XML whitespace; otherwise =false.
1577
+ */
1578
+ private static boolean isSpace(char ch)
1579
+ {
1580
+ return XMLCharacterRecognizer.isWhiteSpace(ch); // Take the easy way out for now.
1581
+ }
1582
+
1583
+ /**
1584
+ * Directly call the
1585
+ * characters method on the passed ContentHandler for the
1586
+ * string-value of the given node (see http://www.w3.org/TR/xpath#data-model
1587
+ * for the definition of a node's string-value). Multiple calls to the
1588
+ * ContentHandler's characters methods may well occur for a single call to
1589
+ * this method.
1590
+ *
1591
+ * @param nodeHandle The node ID.
1592
+ * @param ch A non-null reference to a ContentHandler.
1593
+ *
1594
+ * @throws org.xml.sax.SAXException
1595
+ */
1596
+ public void dispatchCharactersEvents(
1597
+ int nodeHandle, org.xml.sax.ContentHandler ch,
1598
+ boolean normalize)
1599
+ throws org.xml.sax.SAXException
1600
+ {
1601
+ if(normalize)
1602
+ {
1603
+ XMLString str = getStringValue(nodeHandle);
1604
+ str = str.fixWhiteSpace(true, true, false);
1605
+ str.dispatchCharactersEvents(ch);
1606
+ }
1607
+ else
1608
+ {
1609
+ int type = getNodeType(nodeHandle);
1610
+ Node node = getNode(nodeHandle);
1611
+ dispatchNodeData(node, ch, 0);
1612
+ // Text coalition -- a DTM text node may represent multiple
1613
+ // DOM nodes.
1614
+ if(TEXT_NODE == type || CDATA_SECTION_NODE == type)
1615
+ {
1616
+ while( null != (node=logicalNextDOMTextNode(node)) )
1617
+ {
1618
+ dispatchNodeData(node, ch, 0);
1619
+ }
1620
+ }
1621
+ }
1622
+ }
1623
+
1624
+ /**
1625
+ * Retrieve the text content of a DOM subtree, appending it into a
1626
+ * user-supplied FastStringBuffer object. Note that attributes are
1627
+ * not considered part of the content of an element.
1628
+ * <p>
1629
+ * There are open questions regarding whitespace stripping.
1630
+ * Currently we make no special effort in that regard, since the standard
1631
+ * DOM doesn't yet provide DTD-based information to distinguish
1632
+ * whitespace-in-element-context from genuine #PCDATA. Note that we
1633
+ * should probably also consider xml:space if/when we address this.
1634
+ * DOM Level 3 may solve the problem for us.
1635
+ * <p>
1636
+ * %REVIEW% Note that as a DOM-level operation, it can be argued that this
1637
+ * routine _shouldn't_ perform any processing beyond what the DOM already
1638
+ * does, and that whitespace stripping and so on belong at the DTM level.
1639
+ * If you want a stripped DOM view, wrap DTM2DOM around DOM2DTM.
1640
+ *
1641
+ * @param node Node whose subtree is to be walked, gathering the
1642
+ * contents of all Text or CDATASection nodes.
1643
+ */
1644
+ protected static void dispatchNodeData(Node node,
1645
+ org.xml.sax.ContentHandler ch,
1646
+ int depth)
1647
+ throws org.xml.sax.SAXException
1648
+ {
1649
+
1650
+ switch (node.getNodeType())
1651
+ {
1652
+ case Node.DOCUMENT_FRAGMENT_NODE :
1653
+ case Node.DOCUMENT_NODE :
1654
+ case Node.ELEMENT_NODE :
1655
+ {
1656
+ for (Node child = node.getFirstChild(); null != child;
1657
+ child = child.getNextSibling())
1658
+ {
1659
+ dispatchNodeData(child, ch, depth+1);
1660
+ }
1661
+ }
1662
+ break;
1663
+ case Node.PROCESSING_INSTRUCTION_NODE : // %REVIEW%
1664
+ case Node.COMMENT_NODE :
1665
+ if(0 != depth)
1666
+ break;
1667
+ // NOTE: Because this operation works in the DOM space, it does _not_ attempt
1668
+ // to perform Text Coalition. That should only be done in DTM space.
1669
+ case Node.TEXT_NODE :
1670
+ case Node.CDATA_SECTION_NODE :
1671
+ case Node.ATTRIBUTE_NODE :
1672
+ String str = node.getNodeValue();
1673
+ if(ch instanceof org.apache.xml.dtm.ref.dom2dtm.DOM2DTM.CharacterNodeHandler)
1674
+ {
1675
+ ((org.apache.xml.dtm.ref.dom2dtm.DOM2DTM.CharacterNodeHandler)ch).characters(node);
1676
+ }
1677
+ else
1678
+ {
1679
+ ch.characters(str.toCharArray(), 0, str.length());
1680
+ }
1681
+ break;
1682
+ // /* case Node.PROCESSING_INSTRUCTION_NODE :
1683
+ // // warning(XPATHErrorResources.WG_PARSING_AND_PREPARING);
1684
+ // break; */
1685
+ default :
1686
+ // ignore
1687
+ break;
1688
+ }
1689
+ }
1690
+
1691
+ TreeWalker m_walker = new TreeWalker(null);
1692
+
1693
+ /**
1694
+ * Directly create SAX parser events from a subtree.
1695
+ *
1696
+ * @param nodeHandle The node ID.
1697
+ * @param ch A non-null reference to a ContentHandler.
1698
+ *
1699
+ * @throws org.xml.sax.SAXException
1700
+ */
1701
+ public void dispatchToEvents(int nodeHandle, org.xml.sax.ContentHandler ch)
1702
+ throws org.xml.sax.SAXException
1703
+ {
1704
+ TreeWalker treeWalker = m_walker;
1705
+ ContentHandler prevCH = treeWalker.getContentHandler();
1706
+
1707
+ if(null != prevCH)
1708
+ {
1709
+ treeWalker = new TreeWalker(null);
1710
+ }
1711
+ treeWalker.setContentHandler(ch);
1712
+
1713
+ try
1714
+ {
1715
+ Node node = getNode(nodeHandle);
1716
+ treeWalker.traverseFragment(node);
1717
+ }
1718
+ finally
1719
+ {
1720
+ treeWalker.setContentHandler(null);
1721
+ }
1722
+ }
1723
+
1724
+ /**
1725
+ * For the moment all the run time properties are ignored by this
1726
+ * class.
1727
+ *
1728
+ * @param property a <code>String</code> value
1729
+ * @param value an <code>Object</code> value
1730
+ */
1731
+ public void setProperty(String property, Object value)
1732
+ {
1733
+ }
1734
+
1735
+ /**
1736
+ * No source information is available for DOM2DTM, so return
1737
+ * <code>null</code> here.
1738
+ *
1739
+ * @param node an <code>int</code> value
1740
+ * @return null
1741
+ */
1742
+ public SourceLocator getSourceLocatorFor(int node)
1743
+ {
1744
+ return null;
1745
+ }
1746
+
1747
+ }
1748
+
1749
+