/
XmlNode.java
1758 lines (1530 loc) · 65 KB
/
XmlNode.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* (The MIT License)
*
* Copyright (c) 2008 - 2014:
*
* * {Aaron Patterson}[http://tenderlovemaking.com]
* * {Mike Dalessio}[http://mike.daless.io]
* * {Charles Nutter}[http://blog.headius.com]
* * {Sergio Arbeo}[http://www.serabe.com]
* * {Patrick Mahoney}[http://polycrystal.org]
* * {Yoko Harada}[http://yokolet.blogspot.com]
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package nokogiri;
import static java.lang.Math.max;
import static nokogiri.internals.NokogiriHelpers.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import nokogiri.internals.HtmlDomParserContext;
import nokogiri.internals.NokogiriHelpers;
import nokogiri.internals.NokogiriNamespaceCache;
import nokogiri.internals.SaveContextVisitor;
import nokogiri.internals.XmlDomParserContext;
import org.apache.xerces.dom.CoreDocumentImpl;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyInteger;
import org.jruby.RubyFixnum;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* Class for Nokogiri::XML::Node
*
* @author sergio
* @author Patrick Mahoney <pat@polycrystal.org>
* @author Yoko Harada <yokolet@gmail.com>
* @author John Shahid <jvshahid@gmail.com>
*/
@JRubyClass(name="Nokogiri::XML::Node")
public class XmlNode extends RubyObject {
protected static final String TEXT_WRAPPER_NAME = "nokogiri_text_wrapper";
/** The underlying Node object. */
protected Node node;
/* Cached objects */
protected IRubyObject content = null;
protected IRubyObject doc = null;
protected IRubyObject name = null;
/*
* Taken from http://ejohn.org/blog/comparing-document-position/
* Used for compareDocumentPosition.
* <ironic>Thanks to both java api and w3 doc for its helpful documentation</ironic>
*/
protected static final int IDENTICAL_ELEMENTS = 0;
protected static final int IN_DIFFERENT_DOCUMENTS = 1;
protected static final int SECOND_PRECEDES_FIRST = 2;
protected static final int FIRST_PRECEDES_SECOND = 4;
protected static final int SECOND_CONTAINS_FIRST = 8;
protected static final int FIRST_CONTAINS_SECOND = 16;
/**
* Cast <code>node</code> to an XmlNode or raise a type error
* in <code>context</code>.
*/
protected static XmlNode asXmlNode(ThreadContext context, IRubyObject node) {
if ( !(node instanceof XmlNode) ) {
final Ruby runtime = context.getRuntime();
throw runtime.newTypeError(node == null ? runtime.getNil() : node, getNokogiriClass(runtime, "Nokogiri::XML::Node"));
}
return (XmlNode) node;
}
/**
* Cast <code>node</code> to an XmlNode, or null if RubyNil, or
* raise a type error in <code>context</code>.
*/
protected static XmlNode asXmlNodeOrNull(ThreadContext context, IRubyObject node) {
if (node == null || node.isNil()) return null;
return asXmlNode(context, node);
}
/**
* Coalesce to adjacent TextNodes.
* @param context
* @param prev Previous node to cur.
* @param cur Next node to prev.
*/
public static void coalesceTextNodes(ThreadContext context, IRubyObject prev, IRubyObject cur) {
XmlNode p = asXmlNode(context, prev);
XmlNode c = asXmlNode(context, cur);
Node pNode = p.node;
Node cNode = c.node;
pNode.setNodeValue(pNode.getNodeValue()+cNode.getNodeValue());
p.content = null; // clear cached content
c.assimilateXmlNode(context, p);
}
/**
* Coalesce text nodes around <code>anchorNode</code>. If
* <code>anchorNode</code> has siblings (previous or next) that
* are text nodes, the content will be merged into
* <code>anchorNode</code> and the redundant nodes will be removed
* from the DOM.
*
* To match libxml behavior (?) the final content of
* <code>anchorNode</code> and any removed nodes will be
* identical.
*
* @param context
* @param anchorNode
*/
protected static void coalesceTextNodes(ThreadContext context,
IRubyObject anchorNode,
AdoptScheme scheme) {
XmlNode xa = asXmlNode(context, anchorNode);
XmlNode xp = asXmlNodeOrNull(context, xa.previous_sibling(context));
XmlNode xn = asXmlNodeOrNull(context, xa.next_sibling(context));
Node p = xp == null ? null : xp.node;
Node a = xa.node;
Node n = xn == null ? null : xn.node;
Node parent = a.getParentNode();
boolean shouldMergeP = scheme == AdoptScheme.NEXT_SIBLING || scheme == AdoptScheme.CHILD || scheme == AdoptScheme.REPLACEMENT;
boolean shouldMergeN = scheme == AdoptScheme.PREV_SIBLING || scheme == AdoptScheme.REPLACEMENT;
// apply the merge right to left
if (shouldMergeN && n != null && n.getNodeType() == Node.TEXT_NODE) {
xa.setContent(a.getNodeValue() + n.getNodeValue());
parent.removeChild(n);
xn.assimilateXmlNode(context, xa);
}
if (shouldMergeP && p != null && p.getNodeType() == Node.TEXT_NODE) {
xp.setContent(p.getNodeValue() + a.getNodeValue());
parent.removeChild(a);
xa.assimilateXmlNode(context, xp);
}
}
/**
* This is the allocator for XmlNode class. It should only be
* called from Ruby code.
*/
public XmlNode(Ruby ruby, RubyClass cls) {
super(ruby, cls);
}
/**
* This is a constructor to create an XmlNode from an already
* existing node. It may be called by Java code.
*/
public XmlNode(Ruby ruby, RubyClass cls, Node node) {
super(ruby, cls);
setNode(ruby.getCurrentContext(), node);
}
protected void decorate(final ThreadContext context) {
if (node != null) {
resetCache();
if (node.getNodeType() != Node.DOCUMENT_NODE) {
doc = document(context.runtime);
if (doc != null && ! doc.isNil()) {
RuntimeHelpers.invoke(context, doc, "decorate", this);
}
}
}
}
/**
* Create and return a copy of this object.
*
* @return a clone of this object
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
protected void resetCache() {
node.setUserData(NokogiriHelpers.CACHED_NODE, this, null);
}
/**
* Allocate a new object, perform initialization, call that
* object's initialize method, and call any block passing the
* object as the only argument. If <code>cls</code> is
* Nokogiri::XML::Node, creates a new Nokogiri::XML::Element
* instead.
*
* This static method seems to be inherited, strangely enough.
* E.g. creating a new XmlAttr from Ruby code calls this method if
* XmlAttr does not define its own 'new' method.
*
* Since there is some Java bookkeeping that always needs to
* happen, we don't define the 'initialize' method in Java because
* we'd have to count on subclasses calling 'super'.
*
* The main consequence of this is that every subclass needs to
* define its own 'new' method.
*
* As a convenience, this method does the following:
*
* <ul>
*
* <li>allocates a new object using the allocator assigned to
* <code>cls</code></li>
*
* <li>calls the Java method init(); subclasses can override this,
* otherwise they should implement a specific 'new' method</li>
*
* <li>invokes the Ruby initializer</li>
*
* <li>if a block is given, calls the block with the new node as
* the argument</li>
*
* </ul>
*
* -pmahoney
*/
@JRubyMethod(name = "new", meta = true, rest = true)
public static IRubyObject rbNew(ThreadContext context, IRubyObject cls,
IRubyObject[] args, Block block) {
Ruby ruby = context.getRuntime();
RubyClass klazz = (RubyClass) cls;
if ("Nokogiri::XML::Node".equals(klazz.getName())) {
klazz = getNokogiriClass(ruby, "Nokogiri::XML::Element");
}
XmlNode xmlNode = (XmlNode) klazz.allocate();
xmlNode.init(context, args);
xmlNode.callInit(args, block);
assert xmlNode.node != null;
if (block.isGiven()) block.call(context, xmlNode);
return xmlNode;
}
/**
* Initialize the object from Ruby arguments. Should be
* overridden by subclasses. Should check for a minimum number of
* args but not for an exact number. Any extra args will then be
* passed to 'initialize'. The way 'new' and this 'init' function
* interact means that subclasses cannot arbitrarily change the
* require aruments by defining an 'initialize' method. This is
* how the C libxml wrapper works also.
*
* As written it performs initialization for a new Element with
* the given <code>name</code> within the document
* <code>doc</code>. So XmlElement need not override this. This
* implementation cannot be moved to XmlElement however, because
* subclassing XmlNode must result in something that behaves much
* like XmlElement.
*/
protected void init(ThreadContext context, IRubyObject[] args) {
if (args.length < 2)
throw context.getRuntime().newArgumentError(args.length, 2);
IRubyObject name = args[0];
IRubyObject doc = args[1];
Document document = asXmlNode(context, doc).getOwnerDocument();
if (document == null) {
throw getRuntime().newArgumentError("node must have owner document");
}
Element element;
String node_name = rubyStringToString(name);
String prefix = NokogiriHelpers.getPrefix(node_name);
String namespace_uri = null;
if (document.getDocumentElement() != null) {
namespace_uri = document.getDocumentElement().lookupNamespaceURI(prefix);
}
element = document.createElementNS(namespace_uri, node_name);
setNode(context, element);
}
/**
* Set the underlying node of this node to the underlying node of
* <code>otherNode</code>.
*
* FIXME: also update the cached node?
*/
protected void assimilateXmlNode(ThreadContext context, IRubyObject otherNode) {
XmlNode toAssimilate = asXmlNode(context, otherNode);
this.node = toAssimilate.node;
content = null; // clear cache
}
/**
* See org.w3.dom.Node#normalize.
*/
public void normalize() {
node.normalize();
}
public Node getNode() {
return node;
}
public static Node getNodeFromXmlNode(ThreadContext context, IRubyObject xmlNode) {
return asXmlNode(context, xmlNode).node;
}
protected String indentString(IRubyObject indentStringObject, String xml) {
String[] lines = xml.split("\n");
if(lines.length <= 1) return xml;
String[] resultLines = new String[lines.length];
String curLine;
boolean closingTag = false;
String indentString = rubyStringToString(indentStringObject);
int lengthInd = indentString.length();
StringBuilder curInd = new StringBuilder();
resultLines[0] = lines[0];
for(int i = 1; i < lines.length; i++) {
curLine = lines[i].trim();
if(curLine.length() == 0) continue;
if(curLine.startsWith("</")) {
closingTag = true;
curInd.setLength(max(0,curInd.length() - lengthInd));
}
resultLines[i] = curInd.toString() + curLine;
if(!curLine.endsWith("/>") && !closingTag) {
curInd.append(indentString);
}
closingTag = false;
}
StringBuilder result = new StringBuilder();
for(int i = 0; i < resultLines.length; i++) {
result.append(resultLines[i]).append('\n');
}
return result.toString();
}
public boolean isComment() { return false; }
public boolean isElement() {
if (node instanceof Element) return true; // in case of subclassing
else return false;
}
public boolean isProcessingInstruction() { return false; }
/**
* Return the string value of the attribute <code>key</code> or
* nil.
*
* Only applies where the underlying Node is an Element node, but
* implemented here in XmlNode because not all nodes with
* underlying Element nodes subclass XmlElement, such as the DTD
* declarations like XmlElementDecl.
*/
protected IRubyObject getAttribute(ThreadContext context, String key) {
return getAttribute(context.getRuntime(), key);
}
protected IRubyObject getAttribute(Ruby runtime, String key) {
String value = getAttribute(key);
return nonEmptyStringOrNil(runtime, value);
}
protected String getAttribute(String key) {
if (node.getNodeType() != Node.ELEMENT_NODE) return null;
String value = ((Element)node).getAttribute(key);
return value.length() == 0 ? null : value;
}
/**
* This method should be called after a node has been adopted in a new
* document. This method will ensure that the node is renamed with the
* appriopriate NS uri. First the prefix of the node is extracted, then is
* used to lookup the namespace uri in the new document starting at the
* current node and traversing the ancestors. If the namespace uri wasn't
* empty (or null) all children and the node has attributes and/or children
* then the algorithm is recursively applied to the children.
*/
public void relink_namespace(ThreadContext context) {
if (!(node instanceof Element)) {
return;
}
Element e = (Element) node;
// disable error checking to prevent lines like the following
// from throwing a `NAMESPACE_ERR' exception:
// Nokogiri::XML::DocumentFragment.parse("<o:div>a</o:div>")
// since the `o' prefix isn't defined anywhere.
e.getOwnerDocument().setStrictErrorChecking(false);
String prefix = e.getPrefix();
String nsURI = e.lookupNamespaceURI(prefix);
this.node = NokogiriHelpers.renameNode(e, nsURI, e.getNodeName());
if (nsURI == null || nsURI.isEmpty()) {
return;
}
if (e.hasAttributes()) {
NamedNodeMap attrs = e.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr) attrs.item(i);
String attrPrefix = attr.getPrefix();
if (attrPrefix == null) {
attrPrefix = NokogiriHelpers.getPrefix(attr.getNodeName());
}
String nodeName = attr.getNodeName();
String nsUri;
if ("xml".equals(attrPrefix)) {
nsUri = "http://www.w3.org/XML/1998/namespace";
} else if ("xmlns".equals(attrPrefix) || nodeName.equals("xmlns")) {
nsUri = "http://www.w3.org/2000/xmlns/";
} else {
nsUri = attr.lookupNamespaceURI(attrPrefix);
}
if (nsUri == e.getNamespaceURI()) {
nsUri = null;
}
if (!(nsUri == null || "".equals(nsUri) || "http://www.w3.org/XML/1998/namespace".equals(nsUri))) {
// Create a new namespace object and add it to the document
// namespace cache.
// TODO: why do we need the namespace cache ?
XmlNamespace.createFromAttr(context.getRuntime(), attr);
}
NokogiriHelpers.renameNode(attr, nsUri, nodeName);
}
}
if (this.node.hasChildNodes()) {
XmlNodeSet nodeSet = (XmlNodeSet)(children(context));
nodeSet.relink_namespace(context);
}
}
// Users might extend XmlNode. This method works for such a case.
public void accept(ThreadContext context, SaveContextVisitor visitor) {
visitor.enter(node);
XmlNodeSet xmlNodeSet = (XmlNodeSet) children(context);
if (xmlNodeSet.length() > 0) {
RubyArray array = (RubyArray) xmlNodeSet.to_a(context);
for(int i = 0; i < array.getLength(); i++) {
Object item = array.get(i);
if (item instanceof XmlNode) {
XmlNode cur = (XmlNode) item;
cur.accept(context, visitor);
} else if (item instanceof XmlNamespace) {
XmlNamespace cur = (XmlNamespace)item;
cur.accept(context, visitor);
}
}
}
visitor.leave(node);
}
public void setName(IRubyObject name) {
this.name = name;
}
public void setDocument(ThreadContext context, IRubyObject doc) {
this.doc = doc;
setDocumentAndDecorate(context, this, doc);
}
// shared logic with XmlNodeSet
static void setDocumentAndDecorate(ThreadContext context, RubyObject self, IRubyObject doc) {
self.setInstanceVariable("@document", doc);
if (doc != null) {
RuntimeHelpers.invoke(context, doc, "decorate", self);
}
}
public void setNode(ThreadContext context, Node node) {
this.node = node;
decorate(context);
if (this instanceof XmlAttr) {
((XmlAttr)this).setNamespaceIfNecessary(context.getRuntime());
}
}
public void updateNodeNamespaceIfNecessary(ThreadContext context, XmlNamespace ns) {
String oldPrefix = this.node.getPrefix();
String uri = rubyStringToString(ns.href(context));
/*
* Update if both prefixes are null or equal
*/
boolean update = (oldPrefix == null && ns.prefix(context).isNil()) ||
(oldPrefix != null && !ns.prefix(context).isNil()
&& oldPrefix.equals(rubyStringToString(ns.prefix(context))));
if(update) {
this.node = NokogiriHelpers.renameNode(this.node, uri, this.node.getNodeName());
}
}
protected IRubyObject getNodeName(ThreadContext context) {
if (name != null) return name;
String str = null;
if (node != null) {
str = node.getNodeName();
str = NokogiriHelpers.getLocalPart(str);
}
if (str == null) str = "";
if (str.startsWith("#")) str = str.substring(1); // eliminates '#'
return name = NokogiriHelpers.stringOrBlank(context.getRuntime(), str);
}
/**
* Add a namespace definition to this node. To the underlying
* node, add an attribute of the form
* <code>xmlns:prefix="uri"</code>.
*/
@JRubyMethod(name = {"add_namespace_definition", "add_namespace"})
public IRubyObject add_namespace_definition(ThreadContext context,
IRubyObject prefix,
IRubyObject href) {
String prefixString = rubyStringToString(prefix);
String hrefString ;
// try to search the namespace first
if (href.isNil()) {
hrefString = this.findNamespaceHref(context, rubyStringToString(prefix));
if (hrefString == null) {
return context.nil;
}
href = context.getRuntime().newString(hrefString);
} else {
hrefString = rubyStringToString(href);
}
NokogiriNamespaceCache nsCache = NokogiriHelpers.getNamespaceCacheFormNode(node);
XmlNamespace cachedNamespace = nsCache.get(prefixString, hrefString);
if (cachedNamespace != null) return cachedNamespace;
Node namespaceOwner;
if (node.getNodeType() == Node.ELEMENT_NODE) {
namespaceOwner = node;
Element element = (Element) node;
// adds namespace as node's attribute
final String uri = "http://www.w3.org/2000/xmlns/";
String qName =
prefix.isNil() ? "xmlns" : "xmlns:" + prefixString;
element.setAttributeNS(uri, qName, hrefString);
}
else if (node.getNodeType() == Node.ATTRIBUTE_NODE) namespaceOwner = ((Attr)node).getOwnerElement();
else namespaceOwner = node.getParentNode();
XmlNamespace ns = XmlNamespace.createFromPrefixAndHref(namespaceOwner, prefix, href);
if (node != namespaceOwner) {
this.node = NokogiriHelpers.renameNode(node, ns.getHref(), ns.getPrefix() + ":" + node.getLocalName());
}
updateNodeNamespaceIfNecessary(context, ns);
return ns;
}
@JRubyMethod(name = {"attribute", "attr"})
public IRubyObject attribute(ThreadContext context, IRubyObject name){
NamedNodeMap attrs = this.node.getAttributes();
Node attr = attrs.getNamedItem(rubyStringToString(name));
if(attr == null) {
return context.getRuntime().getNil();
}
return getCachedNodeOrCreate(context.getRuntime(), attr);
}
@JRubyMethod
public IRubyObject attribute_nodes(ThreadContext context) {
NamedNodeMap nodeMap = this.node.getAttributes();
Ruby ruby = context.getRuntime();
if(nodeMap == null){
return ruby.newEmptyArray();
}
RubyArray attr = ruby.newArray();
for(int i = 0; i < nodeMap.getLength(); i++) {
if ((doc instanceof HtmlDocument) || !NokogiriHelpers.isNamespace(nodeMap.item(i))) {
attr.append(getCachedNodeOrCreate(context.getRuntime(), nodeMap.item(i)));
}
}
return attr;
}
@JRubyMethod
public IRubyObject attribute_with_ns(ThreadContext context, IRubyObject name, IRubyObject namespace) {
String namej = rubyStringToString(name);
String nsj = (namespace.isNil()) ? null : rubyStringToString(namespace);
Node el = this.node.getAttributes().getNamedItemNS(nsj, namej);
if(el == null) {
return context.getRuntime().getNil();
}
return NokogiriHelpers.getCachedNodeOrCreate(context.getRuntime(), el);
}
@JRubyMethod(name = "blank?")
public IRubyObject blank_p(ThreadContext context) {
// according to libxml doc,
// a node is blank if if it is a Text or CDATA node consisting of whitespace only
if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) {
String data = node.getTextContent();
return context.runtime.newBoolean(data == null || isBlank(data));
}
return context.runtime.getFalse();
}
@JRubyMethod
public IRubyObject child(ThreadContext context) {
return getCachedNodeOrCreate(context.getRuntime(), node.getFirstChild());
}
@JRubyMethod
public IRubyObject children(ThreadContext context) {
XmlNodeSet xmlNodeSet = XmlNodeSet.create(context.runtime);
NodeList nodeList = node.getChildNodes();
if (nodeList.getLength() > 0) {
xmlNodeSet.setNodeList(nodeList); // initializes @document from first node
}
else { // TODO this is very ripe for refactoring
setDocumentAndDecorate(context, xmlNodeSet, doc);
}
return xmlNodeSet;
}
@JRubyMethod
public IRubyObject first_element_child(ThreadContext context) {
List<Node> elementNodes = new ArrayList<Node>();
addElements(node, elementNodes, true);
if (elementNodes.size() == 0) return context.getRuntime().getNil();
return getCachedNodeOrCreate(context.getRuntime(), elementNodes.get(0));
}
@JRubyMethod
public IRubyObject last_element_child(ThreadContext context) {
List<Node> elementNodes = new ArrayList<Node>();
addElements(node, elementNodes, false);
if (elementNodes.size() == 0) return context.getRuntime().getNil();
return getCachedNodeOrCreate(context.getRuntime(), elementNodes.get(elementNodes.size()-1));
}
@JRubyMethod(name = {"element_children", "elements"})
public IRubyObject element_children(ThreadContext context) {
List<Node> elementNodes = new ArrayList<Node>();
addElements(node, elementNodes, false);
if (elementNodes.size() == 0) return XmlNodeSet.newEmptyNodeSet(context);
RubyArray array = NokogiriHelpers.nodeArrayToRubyArray(context.getRuntime(), elementNodes.toArray(new Node[0]));
XmlNodeSet xmlNodeSet = XmlNodeSet.newXmlNodeSet(context, array);
return xmlNodeSet;
}
private void addElements(Node n, List<Node> nodes, boolean isFirstOnly) {
NodeList children = n.getChildNodes();
if (children.getLength() == 0) return;
for (int i=0; i< children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
nodes.add(child);
if (isFirstOnly) return;
}
}
}
/**
* call-seq:
* compare(other)
*
* Compare this Node to +other+ with respect to their Document
*/
@JRubyMethod(visibility=Visibility.PRIVATE)
public IRubyObject compare(ThreadContext context, IRubyObject other) {
if (!(other instanceof XmlNode)) {
return context.getRuntime().newFixnum(-2);
}
Node otherNode = asXmlNode(context, other).node;
// Do not touch this if, if it's not for a good reason.
if (node.getNodeType() == Node.DOCUMENT_NODE ||
otherNode.getNodeType() == Node.DOCUMENT_NODE) {
return context.getRuntime().newFixnum(-1);
}
try{
int res = node.compareDocumentPosition(otherNode);
if ((res & FIRST_PRECEDES_SECOND) == FIRST_PRECEDES_SECOND) {
return context.getRuntime().newFixnum(-1);
} else if ((res & SECOND_PRECEDES_FIRST) == SECOND_PRECEDES_FIRST) {
return context.getRuntime().newFixnum(1);
} else if (res == IDENTICAL_ELEMENTS) {
return context.getRuntime().newFixnum(0);
}
return context.getRuntime().newFixnum(-2);
} catch (Exception ex) {
return context.getRuntime().newFixnum(-2);
}
}
/**
* TODO: this is a stub implementation. It's not clear what
* 'in_context' is supposed to do. Also should take
* <code>options</code> into account.
*/
@JRubyMethod(required = 2, visibility = Visibility.PRIVATE)
public IRubyObject in_context(ThreadContext context,
IRubyObject str,
IRubyObject options) {
RubyModule klass;
XmlDomParserContext ctx;
InputStream istream;
XmlDocument document;
IRubyObject d = document(context);
Ruby runtime = context.getRuntime();
if (d != null && d instanceof XmlDocument) {
document = (XmlDocument)d;
} else {
return runtime.getNil();
}
if (document instanceof HtmlDocument) {
klass = getNokogiriClass(runtime, "Nokogiri::HTML::Document");
ctx = new HtmlDomParserContext(runtime, options);
((HtmlDomParserContext)ctx).enableDocumentFragment();
istream = new ByteArrayInputStream((rubyStringToString(str)).getBytes());
} else {
klass = getNokogiriClass(runtime, "Nokogiri::XML::Document");
ctx = new XmlDomParserContext(runtime, options);
String input = rubyStringToString(str);
istream = new ByteArrayInputStream(input.getBytes());
}
ctx.setInputSource(istream);
// TODO: for some reason, document.getEncoding() can be null or nil (don't know why)
// run `test_parse_with_unparented_html_text_context_node' few times to see this happen
if (document instanceof HtmlDocument && !(document.getEncoding() == null || document.getEncoding().isNil())) {
HtmlDomParserContext htmlCtx= (HtmlDomParserContext) ctx;
htmlCtx.setEncoding(document.getEncoding().asJavaString());
}
XmlDocument doc = ctx.parse(context, klass, runtime.getNil());
RubyArray documentErrors = getErrorArray(document);
RubyArray docErrors = getErrorArray(doc);
if (isErrorIncreased(documentErrors, docErrors)) {
for (int i = 0; i < docErrors.getLength(); i++) {
documentErrors.add(docErrors.get(i));
}
document.setInstanceVariable("@errors", documentErrors);
XmlNodeSet xmlNodeSet = XmlNodeSet.newXmlNodeSet(context, RubyArray.newArray(runtime));
return xmlNodeSet;
}
// The first child might be document type node (dtd declaration).
// XmlNodeSet to be return should not have dtd decl in its list.
Node first;
if (doc.node.getFirstChild().getNodeType() == Node.DOCUMENT_TYPE_NODE) {
first = doc.node.getFirstChild().getNextSibling();
} else {
first = doc.node.getFirstChild();
}
RubyArray nodeArray = RubyArray.newArray(runtime);
nodeArray.add(NokogiriHelpers.getCachedNodeOrCreate(runtime, first));
XmlNodeSet xmlNodeSet = XmlNodeSet.newXmlNodeSet(context, nodeArray);
return xmlNodeSet;
}
private RubyArray getErrorArray(XmlDocument document) {
IRubyObject obj = document.getInstanceVariable("@errors");
if (obj != null && obj instanceof RubyArray) {
return (RubyArray)obj;
}
return RubyArray.newArray(document.getRuntime());
}
private boolean isErrorIncreased(RubyArray baseErrors, RubyArray createdErrors) {
int length = ((RubyArray) createdErrors.op_diff(baseErrors)).size();
return length > 0;
}
@JRubyMethod(name = {"content", "text", "inner_text"})
public IRubyObject content(ThreadContext context) {
return stringOrNil(context.getRuntime(), getContentImpl());
}
public CharSequence getContentImpl() {
if (!node.hasChildNodes() && node.getNodeValue() == null &&
(node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE)) {
return null;
}
CharSequence textContent;
if (this instanceof XmlDocument) {
Node node = ((Document)this.node).getDocumentElement();
if (node == null) {
textContent = "";
} else {
Node documentElement = ((Document) this.node).getDocumentElement();
textContent = getTextContentRecursively(new StringBuilder(), documentElement);
}
} else {
textContent = getTextContentRecursively(new StringBuilder(), node);
}
// textContent = NokogiriHelpers.convertEncodingByNKFIfNecessary(context, (XmlDocument) document(context), textContent);
return textContent;
}
private StringBuilder getTextContentRecursively(StringBuilder buffer, Node currentNode) {
CharSequence textContent = currentNode.getNodeValue();
if (textContent != null && NokogiriHelpers.shouldDecode(currentNode)) {
textContent = NokogiriHelpers.decodeJavaString(textContent);
}
if (textContent != null) buffer.append(textContent);
NodeList children = currentNode.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (hasTextContent(child)) getTextContentRecursively(buffer, child);
}
return buffer;
}
private boolean hasTextContent(Node child) {
return child.getNodeType() != Node.COMMENT_NODE && child.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE;
}
@JRubyMethod
public final IRubyObject document(ThreadContext context) {
return document(context.runtime);
}
IRubyObject document(final Ruby runtime) {
if (doc == null) {
doc = (XmlDocument) node.getOwnerDocument().getUserData(NokogiriHelpers.CACHED_NODE);
}
if (doc == null) {
doc = getCachedNodeOrCreate(runtime, node.getOwnerDocument());
node.getOwnerDocument().setUserData(NokogiriHelpers.CACHED_NODE, doc, null);
}
return doc;
}
public IRubyObject dup() {
return dup_implementation(getMetaClass().getClassRuntime(), true);
}
@JRubyMethod
public IRubyObject dup(ThreadContext context) {
return dup_implementation(context, true);
}
@JRubyMethod
public IRubyObject dup(ThreadContext context, IRubyObject depth) {
boolean deep = depth instanceof RubyInteger && RubyFixnum.fix2int(depth) != 0;
return dup_implementation(context, deep);
}
protected final IRubyObject dup_implementation(ThreadContext context, boolean deep) {
return dup_implementation(context.getRuntime(), deep);
}
protected IRubyObject dup_implementation(Ruby runtime, boolean deep) {
XmlNode clone;
try {
clone = (XmlNode) clone();
} catch (CloneNotSupportedException e) {
throw runtime.newRuntimeError(e.toString());
}
Node newNode = node.cloneNode(deep);
clone.node = newNode;
return clone;
}
public static RubyString encode_special_chars(ThreadContext context, IRubyObject string) {
CharSequence str = NokogiriHelpers.encodeJavaString( rubyStringToString(string) );
return RubyString.newString(context.getRuntime(), str);
}
/**
* Instance method version of the above static method.
*/
@JRubyMethod(name="encode_special_chars")
public IRubyObject i_encode_special_chars(ThreadContext context,
IRubyObject string) {
return encode_special_chars(context, string);
}
/**
* Get the attribute at the given key, <code>key</code>.
* Assumes that this node has attributes (i.e. that key? returned
* true).
*/
@JRubyMethod(visibility = Visibility.PRIVATE)
public IRubyObject get(ThreadContext context, IRubyObject rbkey) {
if (node instanceof Element) {
if (rbkey == null || rbkey.isNil()) context.getRuntime().getNil();
String key = rubyStringToString(rbkey);
Element element = (Element) node;
if (!element.hasAttribute(key)) return context.getRuntime().getNil();
String value = element.getAttribute(key);
return stringOrNil(context.getRuntime(), value);
}
return context.getRuntime().getNil();
}
/**
* Returns the owner document, checking if this node is the
* document, or returns null if there is no owner.
*/
protected Document getOwnerDocument() {
if (node.getNodeType() == Node.DOCUMENT_NODE) {
return (Document) node;
} else {
return node.getOwnerDocument();
}