-
-
Notifications
You must be signed in to change notification settings - Fork 897
/
XmlNode.java
1907 lines (1684 loc) · 57.1 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
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.*;
import org.apache.xerces.dom.CoreDocumentImpl;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyFixnum;
import org.jruby.RubyInteger;
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.runtime.Block;
import org.jruby.runtime.Helpers;
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;
import nokogiri.internals.HtmlDomParserContext;
import nokogiri.internals.NokogiriHelpers;
import nokogiri.internals.NokogiriNamespaceCache;
import nokogiri.internals.SaveContextVisitor;
import nokogiri.internals.XmlDomParserContext;
/**
* 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;
private transient XmlDocument doc;
protected transient RubyString name;
/*
* 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.runtime;
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 runtime, RubyClass klass)
{
super(runtime, klass);
}
/**
* This is a constructor to create an XmlNode from an already
* existing node. It may be called by Java code.
*/
public
XmlNode(Ruby runtime, RubyClass klass, Node node)
{
super(runtime, klass);
setNode(runtime, node);
}
protected void
decorate(final Ruby runtime)
{
if (node != null) {
resetCache();
if (node.getNodeType() != Node.DOCUMENT_NODE) {
setDocumentAndDecorate(runtime.getCurrentContext(), this, document(runtime));
}
}
}
/**
* 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.runtime;
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.runtime.newArgumentError(args.length, 2);
}
IRubyObject name = args[0];
IRubyObject doc = args[1];
Document document = asXmlNode(context, doc).getOwnerDocument();
if (document == null) {
throw context.runtime.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.runtime, 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 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.runtime, 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; }
String currentPrefix = e.getParentNode().lookupPrefix(nsURI);
String currentURI = e.getParentNode().lookupNamespaceURI(prefix);
boolean isDefault = e.getParentNode().isDefaultNamespace(nsURI);
// add xmlns attribute if this is a new root node or if the node's
// namespace isn't a default namespace in the new document
if (e.getParentNode().getNodeType() == Node.DOCUMENT_NODE) {
// this is the root node, so we must set the namespaces attributes anyway
e.setAttribute(prefix == null ? "xmlns" : "xmlns:" + prefix, nsURI);
} else if (prefix == null) {
// this is a default namespace but isn't the default where this node is being added
if (!isDefault) { e.setAttribute("xmlns", nsURI); }
} else if (!prefix.equals(currentPrefix) || nsURI.equals(currentURI)) {
// this is a prefixed namespace
// but doesn't have the same prefix or the prefix is set to a different URI
e.setAttribute("xmlns:" + prefix, nsURI);
}
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 != null && nsUri.equals(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.runtime, attr);
}
NokogiriHelpers.renameNode(attr, nsUri, nodeName);
}
}
if (this.node.hasChildNodes()) {
relink_namespace(context, getChildren());
}
}
static void
relink_namespace(ThreadContext context, IRubyObject[] nodes)
{
for (int i = 0; i < nodes.length; i++) {
if (nodes[i] instanceof XmlNode) {
((XmlNode) nodes[i]).relink_namespace(context);
}
}
}
// Users might extend XmlNode. This method works for such a case.
public void
accept(ThreadContext context, SaveContextVisitor visitor)
{
visitor.enter(node);
acceptChildren(context, getChildren(), visitor);
visitor.leave(node);
}
void
acceptChildren(ThreadContext context, IRubyObject[] nodes, SaveContextVisitor visitor)
{
if (nodes.length > 0) {
for (int i = 0; i < nodes.length; i++) {
Object item = nodes[i];
if (item instanceof XmlNode) {
((XmlNode) item).accept(context, visitor);
} else if (item instanceof XmlNamespace) {
((XmlNamespace) item).accept(context, visitor);
}
}
}
}
RubyString
doSetName(IRubyObject name)
{
if (name.isNil()) { return this.name = null; }
return this.name = name.convertToString();
}
public void
setDocument(ThreadContext context, XmlDocument doc)
{
this.doc = doc;
setDocumentAndDecorate(context, this, doc);
}
// shared logic with XmlNodeSet
static void
setDocumentAndDecorate(ThreadContext context, RubyObject self, XmlDocument doc)
{
self.setInstanceVariable("@document", doc == null ? context.nil : doc);
if (doc != null) { Helpers.invoke(context, doc, "decorate", self); }
}
public void
setNode(Ruby runtime, Node node)
{
this.node = node;
decorate(runtime);
if (this instanceof XmlAttr) {
((XmlAttr) this).setNamespaceIfNecessary(runtime);
}
}
protected IRubyObject
getNodeName(ThreadContext context)
{
if (name != null) { return name; }
String str = null;
if (node != null) {
str = NokogiriHelpers.getLocalPart(node.getNodeName());
}
if (str == null) { str = ""; }
if (str.startsWith("#")) { str = str.substring(1); } // eliminates '#'
return name = context.runtime.newString(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 hrefStr, prefixStr = prefix.isNil() ? null : prefix.convertToString().decodeString();
// try to search the namespace first
if (href.isNil()) {
hrefStr = findNamespaceHref(context, prefixStr);
if (hrefStr == null) { return context.nil; }
href = context.runtime.newString(hrefStr);
} else {
hrefStr = rubyStringToString(href.convertToString());
}
NokogiriNamespaceCache nsCache = NokogiriHelpers.getNamespaceCache(node);
XmlNamespace cachedNamespace = nsCache.get(prefixStr, hrefStr);
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
String qName = prefix.isNil() ? "xmlns" : "xmlns:" + prefixStr;
element.setAttributeNS("http://www.w3.org/2000/xmlns/", qName, hrefStr);
} else if (node.getNodeType() == Node.ATTRIBUTE_NODE) { namespaceOwner = ((Attr) node).getOwnerElement(); }
else { namespaceOwner = node.getParentNode(); }
XmlNamespace ns = XmlNamespace.createImpl(namespaceOwner, prefix, prefixStr, href, hrefStr);
if (node != namespaceOwner) {
node = NokogiriHelpers.renameNode(node, ns.getHref(), ns.getPrefix() + ':' + node.getLocalName());
}
updateNodeNamespaceIfNecessary(ns);
return ns;
}
private void
updateNodeNamespaceIfNecessary(XmlNamespace ns)
{
String oldPrefix = this.node.getPrefix();
/*
* Update if both prefixes are null or equal
*/
boolean update =
(oldPrefix == null && ns.getPrefix() == null) ||
(oldPrefix != null && oldPrefix.equals(ns.getPrefix()));
if (update) {
this.node = NokogiriHelpers.renameNode(this.node, ns.getHref(), this.node.getNodeName());
}
}
@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.nil; }
return getCachedNodeOrCreate(context.runtime, attr);
}
@JRubyMethod
public IRubyObject
attribute_nodes(ThreadContext context)
{
final Ruby runtime = context.runtime;
NamedNodeMap nodeMap = this.node.getAttributes();
if (nodeMap == null) { return runtime.newEmptyArray(); }
RubyArray attr = runtime.newArray(nodeMap.getLength());
final XmlDocument doc = document(context.runtime);
for (int i = 0; i < nodeMap.getLength(); i++) {
if ((doc instanceof HtmlDocument) || !NokogiriHelpers.isNamespace(nodeMap.item(i))) {
attr.append(getCachedNodeOrCreate(runtime, 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.nil; }
return NokogiriHelpers.getCachedNodeOrCreate(context.runtime, 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)
{
final IRubyObject[] nodes = getChildren();
if (nodes.length == 0) {
return XmlNodeSet.newEmptyNodeSet(context, this);
}
return XmlNodeSet.newNodeSet(context.runtime, nodes);
}
IRubyObject[]
getChildren()
{
NodeList nodeList = node.getChildNodes();
if (nodeList.getLength() > 0) {
return nodeListToRubyArray(getRuntime(), nodeList);
}
return IRubyObject.NULL_ARRAY;
}
@JRubyMethod
public IRubyObject
first_element_child(ThreadContext context)
{
List<Node> elementNodes = getElements(node, true);
if (elementNodes.size() == 0) { return context.nil; }
return getCachedNodeOrCreate(context.runtime, elementNodes.get(0));
}
@JRubyMethod
public IRubyObject
last_element_child(ThreadContext context)
{
List<Node> elementNodes = getElements(node, false);
if (elementNodes.size() == 0) { return context.nil; }
return getCachedNodeOrCreate(context.runtime, elementNodes.get(elementNodes.size() - 1));
}
@JRubyMethod(name = {"element_children", "elements"})
public IRubyObject
element_children(ThreadContext context)
{
List<Node> elementNodes = getElements(node, false);
IRubyObject[] array = NokogiriHelpers.nodeListToArray(context.runtime, elementNodes);
return XmlNodeSet.newNodeSet(context.runtime, array, this);
}
private static List<Node>
getElements(Node node, final boolean firstOnly)
{
NodeList children = node.getChildNodes();
if (children.getLength() == 0) {
return Collections.emptyList();
}
ArrayList<Node> elements = firstOnly ? null : new ArrayList<Node>(children.getLength());
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
if (firstOnly) {
return Collections.singletonList(child);
}
elements.add(child);
}
}
return elements;
}
/**
* 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.runtime.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.runtime.newFixnum(1);
}
try {
int res = node.compareDocumentPosition(otherNode);
if ((res & FIRST_PRECEDES_SECOND) == FIRST_PRECEDES_SECOND) {
return context.runtime.newFixnum(-1);
} else if ((res & SECOND_PRECEDES_FIRST) == SECOND_PRECEDES_FIRST) {
return context.runtime.newFixnum(1);
} else if (res == IDENTICAL_ELEMENTS) {
return context.runtime.newFixnum(0);
}
return context.runtime.newFixnum(-2);
} catch (Exception ex) {
return context.runtime.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)
{
RubyClass klass;
XmlDomParserContext ctx;
InputStream istream;
final Ruby runtime = context.runtime;
XmlDocument document = document(runtime);
if (document == null) { return context.nil; }
if (document instanceof HtmlDocument) {
klass = getNokogiriClass(runtime, "Nokogiri::HTML::Document");
ctx = new HtmlDomParserContext(runtime, options);
((HtmlDomParserContext) ctx).enableDocumentFragment();
ctx.setStringInputSource(context, str, context.nil);
} else {
klass = getNokogiriClass(runtime, "Nokogiri::XML::Document");
ctx = new XmlDomParserContext(runtime, options);
ctx.setStringInputSource(context, str, context.nil);
}
// 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, context.nil);
RubyArray documentErrors = getErrors(document);
RubyArray docErrors = getErrors(doc);
if (checkNewErrors(documentErrors, docErrors)) {
for (int i = 0; i < docErrors.getLength(); i++) {
documentErrors.append(docErrors.entry(i));
}
document.setInstanceVariable("@errors", documentErrors);
return XmlNodeSet.newNodeSet(context.runtime, IRubyObject.NULL_ARRAY, this);
}
// 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();
}
IRubyObject[] nodes = new IRubyObject[] { NokogiriHelpers.getCachedNodeOrCreate(runtime, first) };
return XmlNodeSet.newNodeSet(context.runtime, nodes, this);
}
private static RubyArray
getErrors(XmlDocument document)
{
IRubyObject obj = document.getInstanceVariable("@errors");
if (obj instanceof RubyArray) { return (RubyArray) obj; }
return RubyArray.newEmptyArray(document.getRuntime());
}
private static boolean
checkNewErrors(RubyArray baseErrors, RubyArray newErrors)
{
int length = ((RubyArray) newErrors.op_diff(baseErrors)).size();
return length > 0;
}
@JRubyMethod(name = {"content", "text", "inner_text"})
public IRubyObject
content(ThreadContext context)
{
return stringOrNil(context.runtime, 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 static 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 static 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);
}
XmlDocument
document(final Ruby runtime)
{
return document(runtime, true);
}
XmlDocument
document(final Ruby runtime, boolean create)
{
if (doc == null) {
doc = (XmlDocument) node.getOwnerDocument().getUserData(NokogiriHelpers.CACHED_NODE);
if (doc == null && create) {
doc = (XmlDocument) 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.runtime, 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.runtime, str);
}
/**
* Instance method version of the above static method.
*/