nokogiri 1.5.0.beta.4 → 1.5.0

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 (107) hide show
  1. data/.gemtest +0 -0
  2. data/CHANGELOG.ja.rdoc +34 -0
  3. data/CHANGELOG.rdoc +40 -1
  4. data/Manifest.txt +11 -2
  5. data/README.rdoc +1 -1
  6. data/Rakefile +100 -104
  7. data/bin/nokogiri +1 -2
  8. data/ext/nokogiri/nokogiri.c +24 -1
  9. data/ext/nokogiri/xml_io.c +32 -7
  10. data/ext/nokogiri/xml_node.c +14 -13
  11. data/ext/nokogiri/xml_sax_parser.c +9 -4
  12. data/ext/nokogiri/xslt_stylesheet.c +7 -1
  13. data/lib/nokogiri.rb +3 -22
  14. data/lib/nokogiri/css.rb +4 -0
  15. data/lib/nokogiri/html/document.rb +10 -14
  16. data/lib/nokogiri/version.rb +76 -23
  17. data/lib/nokogiri/xml/builder.rb +7 -0
  18. data/lib/nokogiri/xml/document.rb +17 -1
  19. data/lib/nokogiri/xml/document_fragment.rb +14 -0
  20. data/lib/nokogiri/xml/node.rb +36 -28
  21. data/lib/nokogiri/xml/node/save_options.rb +17 -1
  22. data/lib/nokogiri/xml/node_set.rb +7 -0
  23. data/lib/nokogiri/xml/parse_options.rb +8 -0
  24. data/lib/nokogiri/xml/reader.rb +6 -6
  25. data/lib/nokogiri/xml/schema.rb +7 -1
  26. data/nokogiri_help_responses.md +40 -0
  27. data/tasks/cross_compile.rb +134 -159
  28. data/tasks/nokogiri.org.rb +18 -0
  29. data/tasks/test.rb +1 -1
  30. data/test/files/encoding.html +82 -0
  31. data/test/files/encoding.xhtml +84 -0
  32. data/test/files/metacharset.html +10 -0
  33. data/test/files/noencoding.html +47 -0
  34. data/test/helper.rb +2 -0
  35. data/test/html/test_document.rb +15 -0
  36. data/test/html/test_document_encoding.rb +13 -0
  37. data/test/test_memory_leak.rb +20 -0
  38. data/test/test_reader.rb +22 -0
  39. data/test/test_xslt_transforms.rb +6 -2
  40. data/test/xml/node/test_save_options.rb +10 -2
  41. data/test/xml/test_builder.rb +17 -0
  42. data/test/xml/test_document.rb +22 -0
  43. data/test/xml/test_node.rb +19 -1
  44. data/test/xml/test_node_reparenting.rb +16 -3
  45. data/test/xml/test_node_set.rb +34 -0
  46. data/test/xml/test_schema.rb +5 -0
  47. data/test/xslt/test_exception_handling.rb +37 -0
  48. metadata +185 -157
  49. data/deps.rip +0 -5
  50. data/ext/java/nokogiri/EncodingHandler.java +0 -124
  51. data/ext/java/nokogiri/HtmlDocument.java +0 -149
  52. data/ext/java/nokogiri/HtmlElementDescription.java +0 -145
  53. data/ext/java/nokogiri/HtmlEntityLookup.java +0 -79
  54. data/ext/java/nokogiri/HtmlSaxParserContext.java +0 -259
  55. data/ext/java/nokogiri/NokogiriService.java +0 -535
  56. data/ext/java/nokogiri/XmlAttr.java +0 -191
  57. data/ext/java/nokogiri/XmlAttributeDecl.java +0 -130
  58. data/ext/java/nokogiri/XmlCdata.java +0 -91
  59. data/ext/java/nokogiri/XmlComment.java +0 -86
  60. data/ext/java/nokogiri/XmlDocument.java +0 -529
  61. data/ext/java/nokogiri/XmlDocumentFragment.java +0 -217
  62. data/ext/java/nokogiri/XmlDtd.java +0 -467
  63. data/ext/java/nokogiri/XmlElement.java +0 -222
  64. data/ext/java/nokogiri/XmlElementContent.java +0 -382
  65. data/ext/java/nokogiri/XmlElementDecl.java +0 -148
  66. data/ext/java/nokogiri/XmlEntityDecl.java +0 -162
  67. data/ext/java/nokogiri/XmlEntityReference.java +0 -75
  68. data/ext/java/nokogiri/XmlNamespace.java +0 -128
  69. data/ext/java/nokogiri/XmlNode.java +0 -1399
  70. data/ext/java/nokogiri/XmlNodeSet.java +0 -311
  71. data/ext/java/nokogiri/XmlProcessingInstruction.java +0 -103
  72. data/ext/java/nokogiri/XmlReader.java +0 -411
  73. data/ext/java/nokogiri/XmlRelaxng.java +0 -144
  74. data/ext/java/nokogiri/XmlSaxParserContext.java +0 -367
  75. data/ext/java/nokogiri/XmlSaxPushParser.java +0 -184
  76. data/ext/java/nokogiri/XmlSchema.java +0 -319
  77. data/ext/java/nokogiri/XmlSyntaxError.java +0 -119
  78. data/ext/java/nokogiri/XmlText.java +0 -136
  79. data/ext/java/nokogiri/XmlXpathContext.java +0 -179
  80. data/ext/java/nokogiri/XsltStylesheet.java +0 -183
  81. data/ext/java/nokogiri/internals/HtmlDomParserContext.java +0 -206
  82. data/ext/java/nokogiri/internals/NokogiriDocumentCache.java +0 -73
  83. data/ext/java/nokogiri/internals/NokogiriErrorHandler.java +0 -86
  84. data/ext/java/nokogiri/internals/NokogiriHandler.java +0 -327
  85. data/ext/java/nokogiri/internals/NokogiriHelpers.java +0 -582
  86. data/ext/java/nokogiri/internals/NokogiriNamespaceCache.java +0 -171
  87. data/ext/java/nokogiri/internals/NokogiriNamespaceContext.java +0 -118
  88. data/ext/java/nokogiri/internals/NokogiriNonStrictErrorHandler.java +0 -74
  89. data/ext/java/nokogiri/internals/NokogiriNonStrictErrorHandler4NekoHtml.java +0 -121
  90. data/ext/java/nokogiri/internals/NokogiriStrictErrorHandler.java +0 -79
  91. data/ext/java/nokogiri/internals/NokogiriXPathFunction.java +0 -126
  92. data/ext/java/nokogiri/internals/NokogiriXPathFunctionResolver.java +0 -56
  93. data/ext/java/nokogiri/internals/ParserContext.java +0 -278
  94. data/ext/java/nokogiri/internals/PushInputStream.java +0 -411
  95. data/ext/java/nokogiri/internals/ReaderNode.java +0 -474
  96. data/ext/java/nokogiri/internals/SaveContext.java +0 -288
  97. data/ext/java/nokogiri/internals/SchemaErrorHandler.java +0 -76
  98. data/ext/java/nokogiri/internals/XmlDeclHandler.java +0 -42
  99. data/ext/java/nokogiri/internals/XmlDomParser.java +0 -77
  100. data/ext/java/nokogiri/internals/XmlDomParserContext.java +0 -238
  101. data/ext/java/nokogiri/internals/XmlSaxParser.java +0 -65
  102. data/ext/java/nokogiri/internals/XsltExtensionFunction.java +0 -72
  103. data/lib/isorelax.jar +0 -0
  104. data/lib/jing.jar +0 -0
  105. data/lib/nekodtd.jar +0 -0
  106. data/lib/nekohtml.jar +0 -0
  107. data/lib/xercesImpl.jar +0 -0
@@ -1,1399 +0,0 @@
1
- /**
2
- * (The MIT License)
3
- *
4
- * Copyright (c) 2008 - 2011:
5
- *
6
- * * {Aaron Patterson}[http://tenderlovemaking.com]
7
- * * {Mike Dalessio}[http://mike.daless.io]
8
- * * {Charles Nutter}[http://blog.headius.com]
9
- * * {Sergio Arbeo}[http://www.serabe.com]
10
- * * {Patrick Mahoney}[http://polycrystal.org]
11
- * * {Yoko Harada}[http://yokolet.blogspot.com]
12
- *
13
- * Permission is hereby granted, free of charge, to any person obtaining
14
- * a copy of this software and associated documentation files (the
15
- * 'Software'), to deal in the Software without restriction, including
16
- * without limitation the rights to use, copy, modify, merge, publish,
17
- * distribute, sublicense, and/or sell copies of the Software, and to
18
- * permit persons to whom the Software is furnished to do so, subject to
19
- * the following conditions:
20
- *
21
- * The above copyright notice and this permission notice shall be
22
- * included in all copies or substantial portions of the Software.
23
- *
24
- * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
25
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
27
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
28
- * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
29
- * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
30
- * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31
- */
32
-
33
- package nokogiri;
34
-
35
- import static java.lang.Math.max;
36
- import static nokogiri.internals.NokogiriHelpers.getCachedNodeOrCreate;
37
- import static nokogiri.internals.NokogiriHelpers.getNokogiriClass;
38
- import static nokogiri.internals.NokogiriHelpers.nodeArrayToRubyArray;
39
- import static nokogiri.internals.NokogiriHelpers.nonEmptyStringOrNil;
40
- import static nokogiri.internals.NokogiriHelpers.rubyStringToString;
41
- import static nokogiri.internals.NokogiriHelpers.stringOrNil;
42
-
43
- import java.io.ByteArrayInputStream;
44
- import java.io.InputStream;
45
- import java.util.ArrayList;
46
- import java.util.List;
47
-
48
- import nokogiri.internals.HtmlDomParserContext;
49
- import nokogiri.internals.NokogiriHelpers;
50
- import nokogiri.internals.NokogiriNamespaceCache;
51
- import nokogiri.internals.SaveContext;
52
- import nokogiri.internals.XmlDomParserContext;
53
-
54
- import org.jruby.Ruby;
55
- import org.jruby.RubyArray;
56
- import org.jruby.RubyBoolean;
57
- import org.jruby.RubyClass;
58
- import org.jruby.RubyFixnum;
59
- import org.jruby.RubyModule;
60
- import org.jruby.RubyObject;
61
- import org.jruby.RubyString;
62
- import org.jruby.anno.JRubyClass;
63
- import org.jruby.anno.JRubyMethod;
64
- import org.jruby.javasupport.util.RuntimeHelpers;
65
- import org.jruby.runtime.Block;
66
- import org.jruby.runtime.ThreadContext;
67
- import org.jruby.runtime.Visibility;
68
- import org.jruby.runtime.builtin.IRubyObject;
69
- import org.w3c.dom.Attr;
70
- import org.w3c.dom.Document;
71
- import org.w3c.dom.Element;
72
- import org.w3c.dom.NamedNodeMap;
73
- import org.w3c.dom.Node;
74
- import org.w3c.dom.NodeList;
75
- import org.w3c.dom.Text;
76
-
77
- /**
78
- * Class for Nokogiri::XML::Node
79
- *
80
- * @author sergio
81
- * @author Patrick Mahoney <pat@polycrystal.org>
82
- * @author Yoko Harada <yokolet@gmail.com>
83
- */
84
- @JRubyClass(name="Nokogiri::XML::Node")
85
- public class XmlNode extends RubyObject {
86
-
87
- /** The underlying Node object. */
88
- protected Node node;
89
-
90
- /* Cached objects */
91
- protected IRubyObject content = null;
92
- protected IRubyObject doc = null;
93
- protected IRubyObject name = null;
94
-
95
- /*
96
- * Taken from http://ejohn.org/blog/comparing-document-position/
97
- * Used for compareDocumentPosition.
98
- * <ironic>Thanks to both java api and w3 doc for its helpful documentation</ironic>
99
- */
100
-
101
- protected static final int IDENTICAL_ELEMENTS = 0;
102
- protected static final int IN_DIFFERENT_DOCUMENTS = 1;
103
- protected static final int SECOND_PRECEDES_FIRST = 2;
104
- protected static final int FIRST_PRECEDES_SECOND = 4;
105
- protected static final int SECOND_CONTAINS_FIRST = 8;
106
- protected static final int FIRST_CONTAINS_SECOND = 16;
107
-
108
- /**
109
- * Cast <code>node</code> to an XmlNode or raise a type error
110
- * in <code>context</code>.
111
- */
112
- protected static XmlNode asXmlNode(ThreadContext context, IRubyObject node) {
113
- if (node == null || !(node instanceof XmlNode)) {
114
- Ruby ruby = context.getRuntime();
115
- throw ruby.newTypeError(node, getNokogiriClass(ruby, "Nokogiri::XML::Node"));
116
- } else {
117
- return (XmlNode) node;
118
- }
119
- }
120
-
121
- /**
122
- * Cast <code>node</code> to an XmlNode, or null if RubyNil, or
123
- * raise a type error in <code>context</code>.
124
- */
125
- protected static XmlNode asXmlNodeOrNull(ThreadContext context, IRubyObject node) {
126
- if (node == null || node.isNil()) {
127
- return null;
128
- } else {
129
- return asXmlNode(context, node);
130
- }
131
- }
132
-
133
- /**
134
- * Coalesce to adjacent TextNodes.
135
- * @param context
136
- * @param prev Previous node to cur.
137
- * @param cur Next node to prev.
138
- */
139
- public static void coalesceTextNodes(ThreadContext context, IRubyObject prev, IRubyObject cur) {
140
- XmlNode p = asXmlNode(context, prev);
141
- XmlNode c = asXmlNode(context, cur);
142
-
143
- Node pNode = p.node;
144
- Node cNode = c.node;
145
-
146
- pNode.setNodeValue(pNode.getNodeValue()+cNode.getNodeValue());
147
- p.content = null; // clear cached content
148
-
149
- c.assimilateXmlNode(context, p);
150
- }
151
-
152
- /**
153
- * Coalesce text nodes around <code>anchorNode</code>. If
154
- * <code>anchorNode</code> has siblings (previous or next) that
155
- * are text nodes, the content will be merged into
156
- * <code>anchorNode</code> and the redundant nodes will be removed
157
- * from the DOM.
158
- *
159
- * To match libxml behavior (?) the final content of
160
- * <code>anchorNode</code> and any removed nodes will be
161
- * identical.
162
- *
163
- * @param context
164
- * @param anchorNode
165
- */
166
- protected static void coalesceTextNodes(ThreadContext context,
167
- IRubyObject anchorNode) {
168
- XmlNode xa = asXmlNode(context, anchorNode);
169
-
170
- XmlNode xp = asXmlNodeOrNull(context, xa.previous_sibling(context));
171
- XmlNode xn = asXmlNodeOrNull(context, xa.next_sibling(context));
172
-
173
- Node p = xp == null ? null : xp.node;
174
- Node a = xa.node;
175
- Node n = xn == null ? null : xn.node;
176
-
177
- Node parent = a.getParentNode();
178
-
179
- if (p != null && p.getNodeType() == Node.TEXT_NODE) {
180
- xa.setContent(p.getNodeValue() + a.getNodeValue());
181
- parent.removeChild(p);
182
- xp.assimilateXmlNode(context, xa);
183
- }
184
- if (n != null && n.getNodeType() == Node.TEXT_NODE) {
185
- xa.setContent(a.getNodeValue() + n.getNodeValue());
186
- parent.removeChild(n);
187
- xn.assimilateXmlNode(context, xa);
188
- }
189
- }
190
-
191
- /**
192
- * This is the allocator for XmlNode class. It should only be
193
- * called from Ruby code.
194
- */
195
- public XmlNode(Ruby ruby, RubyClass cls) {
196
- super(ruby, cls);
197
- }
198
-
199
- /**
200
- * This is a constructor to create an XmlNode from an already
201
- * existing node. It may be called by Java code.
202
- */
203
- public XmlNode(Ruby ruby, RubyClass cls, Node node) {
204
- super(ruby, cls);
205
- this.node = node;
206
-
207
- if (node != null) {
208
- resetCache();
209
-
210
- if (node.getNodeType() != Node.DOCUMENT_NODE) {
211
- doc = document(ruby.getCurrentContext());
212
-
213
- if (doc != null) {
214
- RuntimeHelpers.invoke(ruby.getCurrentContext(), doc, "decorate", this);
215
- }
216
- }
217
- }
218
-
219
- }
220
-
221
- /**
222
- * Create and return a copy of this object.
223
- *
224
- * @return a clone of this object
225
- */
226
- @Override
227
- public Object clone() throws CloneNotSupportedException {
228
- return super.clone();
229
- }
230
-
231
- protected void resetCache() {
232
- node.setUserData(NokogiriHelpers.CACHED_NODE, this, null);
233
- }
234
-
235
- /**
236
- * Allocate a new object, perform initialization, call that
237
- * object's initialize method, and call any block passing the
238
- * object as the only argument. If <code>cls</code> is
239
- * Nokogiri::XML::Node, creates a new Nokogiri::XML::Element
240
- * instead.
241
- *
242
- * This static method seems to be inherited, strangely enough.
243
- * E.g. creating a new XmlAttr from Ruby code calls this method if
244
- * XmlAttr does not define its own 'new' method.
245
- *
246
- * Since there is some Java bookkeeping that always needs to
247
- * happen, we don't define the 'initialize' method in Java because
248
- * we'd have to count on subclasses calling 'super'.
249
- *
250
- * The main consequence of this is that every subclass needs to
251
- * define its own 'new' method.
252
- *
253
- * As a convenience, this method does the following:
254
- *
255
- * <ul>
256
- *
257
- * <li>allocates a new object using the allocator assigned to
258
- * <code>cls</code></li>
259
- *
260
- * <li>calls the Java method init(); subclasses can override this,
261
- * otherwise they should implement a specific 'new' method</li>
262
- *
263
- * <li>invokes the Ruby initializer</li>
264
- *
265
- * <li>if a block is given, calls the block with the new node as
266
- * the argument</li>
267
- *
268
- * </ul>
269
- *
270
- * -pmahoney
271
- */
272
- @JRubyMethod(name = "new", meta = true, rest = true)
273
- public static IRubyObject rbNew(ThreadContext context, IRubyObject cls,
274
- IRubyObject[] args, Block block) {
275
- Ruby ruby = context.getRuntime();
276
- RubyClass klazz = (RubyClass) cls;
277
-
278
- if (cls.equals(getNokogiriClass(ruby, "Nokogiri::XML::Node"))) {
279
- klazz = getNokogiriClass(ruby, "Nokogiri::XML::Element");
280
- }
281
-
282
- XmlNode xmlNode = (XmlNode) klazz.allocate();
283
- xmlNode.init(context, args);
284
- xmlNode.callInit(args, block);
285
- if (xmlNode.node == null) context.getRuntime().newRuntimeError("NODE IS NULL");
286
- if (block.isGiven()) block.call(context, xmlNode);
287
- return xmlNode;
288
- }
289
-
290
- /**
291
- * Initialize the object from Ruby arguments. Should be
292
- * overridden by subclasses. Should check for a minimum number of
293
- * args but not for an exact number. Any extra args will then be
294
- * passed to 'initialize'. The way 'new' and this 'init' function
295
- * interact means that subclasses cannot arbitrarily change the
296
- * require aruments by defining an 'initialize' method. This is
297
- * how the C libxml wrapper works also.
298
- *
299
- * As written it performs initialization for a new Element with
300
- * the given <code>name</code> within the document
301
- * <code>doc</code>. So XmlElement need not override this. This
302
- * implementation cannot be moved to XmlElement however, because
303
- * subclassing XmlNode must result in something that behaves much
304
- * like XmlElement.
305
- */
306
- protected void init(ThreadContext context, IRubyObject[] args) {
307
- if (args.length < 2)
308
- throw context.getRuntime().newArgumentError(args.length, 2);
309
-
310
- IRubyObject name = args[0];
311
- IRubyObject doc = args[1];
312
-
313
- Document document = asXmlNode(context, doc).getOwnerDocument();
314
- if (document == null) {
315
- throw getRuntime().newArgumentError("node must have owner document");
316
- }
317
-
318
- Element element = document.createElementNS(null, rubyStringToString(name));
319
- setNode(context, element);
320
- }
321
-
322
- /**
323
- * Set the underlying node of this node to the underlying node of
324
- * <code>otherNode</code>.
325
- *
326
- * FIXME: also update the cached node?
327
- */
328
- protected void assimilateXmlNode(ThreadContext context, IRubyObject otherNode) {
329
- XmlNode toAssimilate = asXmlNode(context, otherNode);
330
-
331
- this.node = toAssimilate.node;
332
- content = null; // clear cache
333
- }
334
-
335
- /**
336
- * See org.w3.dom.Node#normalize.
337
- */
338
- public void normalize() {
339
- node.normalize();
340
- }
341
-
342
- public Node getNode() {
343
- return node;
344
- }
345
-
346
- public static Node getNodeFromXmlNode(ThreadContext context, IRubyObject xmlNode) {
347
- return asXmlNode(context, xmlNode).node;
348
- }
349
-
350
- protected String indentString(IRubyObject indentStringObject, String xml) {
351
- String[] lines = xml.split("\n");
352
-
353
- if(lines.length <= 1) return xml;
354
-
355
- String[] resultLines = new String[lines.length];
356
-
357
- String curLine;
358
- boolean closingTag = false;
359
- String indentString = rubyStringToString(indentStringObject);
360
- int lengthInd = indentString.length();
361
- StringBuffer curInd = new StringBuffer();
362
-
363
- resultLines[0] = lines[0];
364
-
365
- for(int i = 1; i < lines.length; i++) {
366
-
367
- curLine = lines[i].trim();
368
-
369
- if(curLine.length() == 0) continue;
370
-
371
- if(curLine.startsWith("</")) {
372
- closingTag = true;
373
- curInd.setLength(max(0,curInd.length() - lengthInd));
374
- }
375
-
376
- resultLines[i] = curInd.toString() + curLine;
377
-
378
- if(!curLine.endsWith("/>") && !closingTag) {
379
- curInd.append(indentString);
380
- }
381
-
382
- closingTag = false;
383
- }
384
-
385
- StringBuffer result = new StringBuffer();
386
- for(int i = 0; i < resultLines.length; i++) {
387
- result.append(resultLines[i]);
388
- result.append("\n");
389
- }
390
-
391
- return result.toString();
392
- }
393
-
394
- public boolean isComment() { return false; }
395
-
396
- public boolean isElement() { return false; }
397
-
398
- public boolean isProcessingInstruction() { return false; }
399
-
400
- /**
401
- * Return the string value of the attribute <code>key</code> or
402
- * nil.
403
- *
404
- * Only applies where the underlying Node is an Element node, but
405
- * implemented here in XmlNode because not all nodes with
406
- * underlying Element nodes subclass XmlElement, such as the DTD
407
- * declarations like XmlElementDecl.
408
- */
409
- protected IRubyObject getAttribute(ThreadContext context, String key) {
410
- return getAttribute(context.getRuntime(), key);
411
- }
412
-
413
- protected IRubyObject getAttribute(Ruby runtime, String key) {
414
- String value = getAttribute(key);
415
- return nonEmptyStringOrNil(runtime, value);
416
- }
417
-
418
- protected String getAttribute(String key) {
419
- if (node.getNodeType() != Node.ELEMENT_NODE) return null;
420
-
421
- String value = ((Element)node).getAttribute(key);
422
- return value.length() == 0 ? null : value;
423
- }
424
-
425
-
426
- public void post_add_child(ThreadContext context, XmlNode current, XmlNode child) {
427
- }
428
-
429
- public void relink_namespace(ThreadContext context) {
430
- //this should delegate to subclasses' implementation
431
- }
432
-
433
- public void saveContent(ThreadContext context, SaveContext ctx) {}
434
-
435
- public void setName(IRubyObject name) {
436
- this.name = name;
437
- }
438
-
439
- public void setDocument(ThreadContext context, IRubyObject doc) {
440
- this.doc = doc;
441
- setInstanceVariable("@document", doc);
442
- if (doc != null) {
443
- RuntimeHelpers.invoke(context, doc, "decorate", this);
444
- }
445
- }
446
-
447
- public void setNode(ThreadContext context, Node node) {
448
- this.node = node;
449
-
450
- if (node != null) {
451
- resetCache();
452
- if (node.getNodeType() != Node.DOCUMENT_NODE) {
453
- doc = document(context);
454
- }
455
- }
456
- }
457
-
458
- public void updateNodeNamespaceIfNecessary(ThreadContext context, XmlNamespace ns) {
459
- String oldPrefix = this.node.getPrefix();
460
- String uri = rubyStringToString(ns.href(context));
461
-
462
- /*
463
- * Update if both prefixes are null or equal
464
- */
465
- boolean update = (oldPrefix == null && ns.prefix(context).isNil()) ||
466
- (oldPrefix != null && !ns.prefix(context).isNil()
467
- && oldPrefix.equals(rubyStringToString(ns.prefix(context))));
468
-
469
- if(update) {
470
- this.node.getOwnerDocument().renameNode(this.node, uri, this.node.getNodeName());
471
- }
472
- }
473
-
474
- protected IRubyObject getNodeName(ThreadContext context) {
475
- if (name != null) return name;
476
- String str = null;
477
-
478
- if (this.name == null && node != null) {
479
- str = node.getNodeName();
480
- str = NokogiriHelpers.getLocalPart(str);
481
- }
482
- if (str == null) str = "";
483
- name = context.getRuntime().newString(str);
484
- return name;
485
- }
486
-
487
- protected void saveNodeListContent(ThreadContext context, XmlNodeSet list, SaveContext ctx) {
488
- saveNodeListContent(context, (RubyArray) list.to_a(context), ctx);
489
- }
490
-
491
- protected void saveNodeListContent(ThreadContext context, RubyArray array, SaveContext ctx) {
492
- int length = array.getLength();
493
-
494
- boolean formatIndentation = ctx.format() && ctx.indentString()!=null;
495
-
496
- for(int i = 0; i < length; i++) {
497
- Object item = array.get(i);
498
- if (item instanceof XmlNode) {
499
- XmlNode cur = (XmlNode) item;
500
-
501
- // if(formatIndentation &&
502
- // (cur.isElement() || cur.isComment() || cur.isProcessingInstruction())) {
503
- // ctx.append(ctx.getCurrentIndentString());
504
- // }
505
-
506
- cur.saveContent(context, ctx);
507
- } else if (item instanceof XmlNamespace) {
508
- XmlNamespace cur = (XmlNamespace)item;
509
- cur.saveContent(context, ctx);
510
- }
511
-
512
- // if(ctx.format()) ctx.append("\n");
513
- }
514
- }
515
-
516
- /**
517
- * Add a namespace definition to this node. To the underlying
518
- * node, add an attribute of the form
519
- * <code>xmlns:prefix="uri"</code>.
520
- */
521
- @JRubyMethod(name = {"add_namespace_definition", "add_namespace"})
522
- public IRubyObject add_namespace_definition(ThreadContext context,
523
- IRubyObject prefix,
524
- IRubyObject href) {
525
- String prefixString = prefix.isNil() ? "" : rubyStringToString(prefix);
526
- String hrefString = rubyStringToString(href);
527
- XmlDocument xmlDocument = (XmlDocument) doc;
528
- Node namespaceOwner;
529
- if (node.getNodeType() == Node.ELEMENT_NODE) namespaceOwner = node;
530
- else if (node.getNodeType() == Node.ATTRIBUTE_NODE) namespaceOwner = ((Attr)node).getOwnerElement();
531
- else namespaceOwner = node.getParentNode();
532
- XmlNamespace ns = xmlDocument.getNamespaceCache().put(context.getRuntime(), prefixString, hrefString, namespaceOwner, xmlDocument);
533
- if (node != namespaceOwner) {
534
- node.getOwnerDocument().renameNode(node, hrefString, prefixString + node.getLocalName());
535
- }
536
-
537
- return ns;
538
- }
539
-
540
- @JRubyMethod(name = {"attribute", "attr"})
541
- public IRubyObject attribute(ThreadContext context, IRubyObject name){
542
- NamedNodeMap attrs = this.node.getAttributes();
543
- Node attr = attrs.getNamedItem(rubyStringToString(name));
544
- if(attr == null) {
545
- return context.getRuntime().newString(ERR_INSECURE_SET_INST_VAR);
546
- }
547
- return getCachedNodeOrCreate(context.getRuntime(), attr);
548
- }
549
-
550
- @JRubyMethod
551
- public IRubyObject attribute_nodes(ThreadContext context) {
552
- NamedNodeMap nodeMap = this.node.getAttributes();
553
-
554
- Ruby ruby = context.getRuntime();
555
- if(nodeMap == null){
556
- return ruby.newEmptyArray();
557
- }
558
-
559
- RubyArray attr = ruby.newArray();
560
-
561
- for(int i = 0; i < nodeMap.getLength(); i++) {
562
- if (!NokogiriHelpers.isNamespace(nodeMap.item(i))) {
563
- attr.append(getCachedNodeOrCreate(context.getRuntime(), nodeMap.item(i)));
564
- }
565
- }
566
-
567
- return attr;
568
- }
569
-
570
- @JRubyMethod
571
- public IRubyObject attribute_with_ns(ThreadContext context, IRubyObject name, IRubyObject namespace) {
572
- String namej = rubyStringToString(name);
573
- String nsj = (namespace.isNil()) ? null : rubyStringToString(namespace);
574
-
575
- Node el = this.node.getAttributes().getNamedItemNS(nsj, namej);
576
-
577
- if(el == null) {
578
- return context.getRuntime().getNil();
579
- }
580
- return NokogiriHelpers.getCachedNodeOrCreate(context.getRuntime(), el);
581
- }
582
-
583
- @JRubyMethod(name = "blank?")
584
- public IRubyObject blank_p(ThreadContext context) {
585
- String data = node.getTextContent();
586
- if ("".equals(data.trim())) return context.getRuntime().getTrue();
587
- return context.getRuntime().getFalse();
588
- }
589
-
590
- @JRubyMethod
591
- public IRubyObject child(ThreadContext context) {
592
- return getCachedNodeOrCreate(context.getRuntime(), node.getFirstChild());
593
- }
594
-
595
- @JRubyMethod
596
- public IRubyObject children(ThreadContext context) {
597
- XmlNodeSet xmlNodeSet = (XmlNodeSet) NokogiriService.XML_NODESET_ALLOCATOR.allocate(context.getRuntime(), getNokogiriClass(context.getRuntime(), "Nokogiri::XML::NodeSet"));
598
- xmlNodeSet.setNodeList(node.getChildNodes());
599
- return xmlNodeSet;
600
- }
601
-
602
- @JRubyMethod
603
- public IRubyObject first_element_child(ThreadContext context) {
604
- List<Node> elementNodes = new ArrayList<Node>();
605
- addElements(node, elementNodes, true);
606
- if (elementNodes.size() == 0) return context.getRuntime().getNil();
607
- return getCachedNodeOrCreate(context.getRuntime(), elementNodes.get(0));
608
- }
609
-
610
- @JRubyMethod
611
- public IRubyObject last_element_child(ThreadContext context) {
612
- List<Node> elementNodes = new ArrayList<Node>();
613
- addElements(node, elementNodes, false);
614
- if (elementNodes.size() == 0) return context.getRuntime().getNil();
615
- return getCachedNodeOrCreate(context.getRuntime(), elementNodes.get(elementNodes.size()-1));
616
- }
617
-
618
- @JRubyMethod(name = {"element_children", "elements"})
619
- public IRubyObject element_children(ThreadContext context) {
620
- List<Node> elementNodes = new ArrayList<Node>();
621
- addElements(node, elementNodes, false);
622
- if (elementNodes.size() == 0) return XmlNodeSet.newEmptyNodeSet(context);
623
- RubyArray array = NokogiriHelpers.nodeArrayToRubyArray(context.getRuntime(), elementNodes.toArray(new Node[0]));
624
- XmlNodeSet xmlNodeSet = (XmlNodeSet) NokogiriService.XML_NODESET_ALLOCATOR.allocate(context.getRuntime(), getNokogiriClass(getRuntime(), "Nokogiri::XML::NodeSet"));
625
- xmlNodeSet.setInitialNodes(array);
626
- return xmlNodeSet;
627
- }
628
-
629
- private void addElements(Node n, List<Node> nodes, boolean isFirstOnly) {
630
- NodeList children = n.getChildNodes();
631
- if (children.getLength() == 0) return;
632
- for (int i=0; i< children.getLength(); i++) {
633
- Node child = children.item(i);
634
- if (child.getNodeType() == Node.ELEMENT_NODE) {
635
- nodes.add(child);
636
- if (isFirstOnly) return;
637
- }
638
- }
639
- }
640
-
641
- /**
642
- * call-seq:
643
- * compare(other)
644
- *
645
- * Compare this Node to +other+ with respect to their Document
646
- */
647
- @JRubyMethod(visibility=Visibility.PRIVATE)
648
- public IRubyObject compare(ThreadContext context, IRubyObject other) {
649
- if (!(other instanceof XmlNode)) {
650
- return context.getRuntime().newFixnum(-2);
651
- }
652
-
653
- Node otherNode = asXmlNode(context, other).node;
654
-
655
- // Do not touch this if, if it's not for a good reason.
656
- if (node.getNodeType() == Node.DOCUMENT_NODE ||
657
- otherNode.getNodeType() == Node.DOCUMENT_NODE) {
658
- return context.getRuntime().newFixnum(-1);
659
- }
660
-
661
- try{
662
- int res = node.compareDocumentPosition(otherNode);
663
- if ((res & FIRST_PRECEDES_SECOND) == FIRST_PRECEDES_SECOND) {
664
- return context.getRuntime().newFixnum(-1);
665
- } else if ((res & SECOND_PRECEDES_FIRST) == SECOND_PRECEDES_FIRST) {
666
- return context.getRuntime().newFixnum(1);
667
- } else if (res == IDENTICAL_ELEMENTS) {
668
- return context.getRuntime().newFixnum(0);
669
- }
670
-
671
- return context.getRuntime().newFixnum(-2);
672
- } catch (Exception ex) {
673
- return context.getRuntime().newFixnum(-2);
674
- }
675
- }
676
-
677
- /**
678
- * TODO: this is a stub implementation. It's not clear what
679
- * 'in_context' is supposed to do. Also should take
680
- * <code>options</code> into account.
681
- */
682
- @JRubyMethod(required = 2, visibility = Visibility.PRIVATE)
683
- public IRubyObject in_context(ThreadContext context,
684
- IRubyObject str,
685
- IRubyObject options) {
686
- RubyModule klass;
687
- XmlDomParserContext ctx;
688
- InputStream istream;
689
- XmlDocument document;
690
-
691
- IRubyObject d = document(context);
692
- Ruby runtime = context.getRuntime();
693
- if (d != null && d instanceof XmlDocument) {
694
- document = (XmlDocument)d;
695
- } else {
696
- return runtime.getNil();
697
- }
698
-
699
- if (document instanceof HtmlDocument) {
700
- klass = getNokogiriClass(runtime, "Nokogiri::HTML::Document");
701
- ctx = new HtmlDomParserContext(runtime, options);
702
- ((HtmlDomParserContext)ctx).enableDocumentFragment();
703
- istream = new ByteArrayInputStream((rubyStringToString(str)).getBytes());
704
- } else if (document instanceof XmlDocument) {
705
- klass = getNokogiriClass(runtime, "Nokogiri::XML::Document");
706
- ctx = new XmlDomParserContext(runtime, options);
707
- String input = rubyStringToString(str);
708
- istream = new ByteArrayInputStream(input.getBytes());
709
- } else {
710
- return runtime.getNil();
711
- }
712
-
713
- ctx.setInputSource(istream);
714
- XmlDocument doc = ctx.parse(context, klass, runtime.getNil());
715
-
716
- RubyArray documentErrors = getErrorArray(document);
717
- RubyArray docErrors = getErrorArray(doc);
718
- if (isErrorIncreated(documentErrors, docErrors)) {
719
- for (int i = 0; i < docErrors.getLength(); i++) {
720
- documentErrors.add(docErrors.get(i));
721
- }
722
- document.setInstanceVariable("@errors", documentErrors);
723
- XmlNodeSet xmlNodeSet = (XmlNodeSet) NokogiriService.XML_NODESET_ALLOCATOR.allocate(runtime, getNokogiriClass(runtime, "Nokogiri::XML::NodeSet"));
724
- xmlNodeSet.setInitialNodes(RubyArray.newArray(runtime));
725
- return xmlNodeSet;
726
- }
727
-
728
- // The first child might be document type node (dtd declaration).
729
- // XmlNodeSet to be return should not have dtd decl in its list.
730
- Node first;
731
- if (doc.node.getFirstChild().getNodeType() == Node.DOCUMENT_TYPE_NODE) {
732
- first = doc.node.getFirstChild().getNextSibling();
733
- } else {
734
- first = doc.node.getFirstChild();
735
- }
736
- RubyArray nodeArray = RubyArray.newArray(runtime);
737
- nodeArray.add(NokogiriHelpers.getCachedNodeOrCreate(runtime, first));
738
-
739
- NokogiriHelpers.nodeListToRubyArray(runtime, first.getChildNodes(), nodeArray);
740
- XmlNodeSet xmlNodeSet = (XmlNodeSet)NokogiriService.XML_NODESET_ALLOCATOR.allocate(runtime, getNokogiriClass(runtime, "Nokogiri::XML::NodeSet"));
741
- xmlNodeSet.setInitialNodes(nodeArray);
742
- return xmlNodeSet;
743
- }
744
-
745
- private RubyArray getErrorArray(XmlDocument document) {
746
- IRubyObject obj = document.getInstanceVariable("@errors");
747
- if (obj != null && obj instanceof RubyArray) {
748
- return (RubyArray)obj;
749
- }
750
- return RubyArray.newArray(document.getRuntime());
751
- }
752
-
753
- private boolean isErrorIncreated(RubyArray baseErrors, RubyArray createdErrors) {
754
- RubyBoolean result = baseErrors.compare(baseErrors.getRuntime().getCurrentContext(), "eql?", createdErrors, null);
755
- return result.isFalse();
756
- }
757
-
758
- @JRubyMethod(name = {"content", "text", "inner_text"})
759
- public IRubyObject content(ThreadContext context) {
760
- if (content != null && content.isNil()) return content;
761
- String textContent;
762
- if (content != null) textContent = rubyStringToString(content);
763
- else if (this instanceof XmlDocument) {
764
- textContent = ((Document)this.node).getDocumentElement().getTextContent().trim();
765
- } else {
766
- textContent = this.node.getTextContent();
767
- }
768
- String decodedText = null;
769
- if (textContent != null) decodedText = NokogiriHelpers.decodeJavaString(textContent);
770
- return stringOrNil(context.getRuntime(), decodedText);
771
- }
772
-
773
- @JRubyMethod
774
- public IRubyObject document(ThreadContext context) {
775
- if(doc == null) {
776
- doc = getCachedNodeOrCreate(context.getRuntime(), node.getOwnerDocument());
777
- }
778
- return doc;
779
- }
780
-
781
- @JRubyMethod
782
- public IRubyObject dup(ThreadContext context) {
783
- return this.dup_implementation(context, true);
784
- }
785
-
786
- @JRubyMethod
787
- public IRubyObject dup(ThreadContext context, IRubyObject depth) {
788
- boolean deep = (Integer)depth.toJava(Integer.class) != 0;
789
-
790
- return this.dup_implementation(context, deep);
791
- }
792
-
793
- protected IRubyObject dup_implementation(ThreadContext context, boolean deep) {
794
- XmlNode clone;
795
- try {
796
- clone = (XmlNode) clone();
797
- } catch (CloneNotSupportedException e) {
798
- throw context.getRuntime().newRuntimeError(e.toString());
799
- }
800
- if (node == null) throw context.getRuntime().newRuntimeError("FFFFFFFFFUUUUUUU");
801
- Node newNode = node.cloneNode(deep);
802
- clone.node = newNode;
803
- return clone;
804
- }
805
-
806
- public static IRubyObject encode_special_chars(ThreadContext context,
807
- IRubyObject string) {
808
- String s = rubyStringToString(string);
809
- String enc = NokogiriHelpers.encodeJavaString(s);
810
- return context.getRuntime().newString(enc);
811
- }
812
-
813
- /**
814
- * Instance method version of the above static method.
815
- */
816
- @JRubyMethod(name="encode_special_chars")
817
- public IRubyObject i_encode_special_chars(ThreadContext context,
818
- IRubyObject string) {
819
- return encode_special_chars(context, string);
820
- }
821
-
822
- /**
823
- * Get the attribute at the given key, <code>key</code>.
824
- * Assumes that this node has attributes (i.e. that key? returned
825
- * true). Overridden in XmlElement.
826
- */
827
- @JRubyMethod(visibility = Visibility.PRIVATE)
828
- public IRubyObject get(ThreadContext context, IRubyObject key) {
829
- return context.getRuntime().getNil();
830
- }
831
-
832
- /**
833
- * Returns the owner document, checking if this node is the
834
- * document, or returns null if there is no owner.
835
- */
836
- protected Document getOwnerDocument() {
837
- if (node.getNodeType() == Node.DOCUMENT_NODE) {
838
- return (Document) node;
839
- } else {
840
- return node.getOwnerDocument();
841
- }
842
- }
843
-
844
- @JRubyMethod
845
- public IRubyObject internal_subset(ThreadContext context) {
846
- Document document = getOwnerDocument();
847
-
848
- if(document == null) {
849
- return context.getRuntime().getNil();
850
- }
851
-
852
- XmlDocument xdoc =
853
- (XmlDocument) getCachedNodeOrCreate(context.getRuntime(), document);
854
- IRubyObject xdtd = xdoc.getInternalSubset(context);
855
- return xdtd;
856
- }
857
-
858
- @JRubyMethod
859
- public IRubyObject create_internal_subset(ThreadContext context,
860
- IRubyObject name,
861
- IRubyObject external_id,
862
- IRubyObject system_id) {
863
- IRubyObject subset = internal_subset(context);
864
- if (!subset.isNil()) {
865
- throw context.getRuntime()
866
- .newRuntimeError("Document already has internal subset");
867
- }
868
-
869
- Document document = getOwnerDocument();
870
- if(document == null) {
871
- return context.getRuntime().getNil();
872
- }
873
-
874
- XmlDocument xdoc =
875
- (XmlDocument) getCachedNodeOrCreate(context.getRuntime(), document);
876
- IRubyObject xdtd = xdoc.createInternalSubset(context, name,
877
- external_id, system_id);
878
- return xdtd;
879
- }
880
-
881
- @JRubyMethod
882
- public IRubyObject external_subset(ThreadContext context) {
883
- Document document = getOwnerDocument();
884
-
885
- if(document == null) {
886
- return context.getRuntime().getNil();
887
- }
888
-
889
- XmlDocument xdoc =
890
- (XmlDocument) getCachedNodeOrCreate(context.getRuntime(), document);
891
- IRubyObject xdtd = xdoc.getExternalSubset(context);
892
- return xdtd;
893
- }
894
-
895
- @JRubyMethod
896
- public IRubyObject create_external_subset(ThreadContext context,
897
- IRubyObject name,
898
- IRubyObject external_id,
899
- IRubyObject system_id) {
900
- IRubyObject subset = external_subset(context);
901
- if (!subset.isNil()) {
902
- throw context.getRuntime()
903
- .newRuntimeError("Document already has external subset");
904
- }
905
-
906
- Document document = getOwnerDocument();
907
- if(document == null) {
908
- return context.getRuntime().getNil();
909
- }
910
- XmlDocument xdoc = (XmlDocument) getCachedNodeOrCreate(context.getRuntime(), document);
911
- IRubyObject xdtd = xdoc.createExternalSubset(context, name, external_id, system_id);
912
- return xdtd;
913
- }
914
-
915
- /**
916
- * Test if this node has an attribute named <code>rbkey</code>.
917
- * Overridden in XmlElement.
918
- */
919
- @JRubyMethod(name = {"key?", "has_attribute?"})
920
- public IRubyObject key_p(ThreadContext context, IRubyObject rbkey) {
921
- return context.getRuntime().getNil();
922
- }
923
-
924
- @JRubyMethod
925
- public IRubyObject namespace(ThreadContext context){
926
- XmlDocument xmlDocument = (XmlDocument) doc;
927
- NokogiriNamespaceCache nsCache = xmlDocument.getNamespaceCache();
928
- String prefix = node.getPrefix();
929
- XmlNamespace namespace = nsCache.get(prefix == null ? "" : prefix, node.getNamespaceURI());
930
- if (namespace == null || ((XmlNamespace) namespace).isEmpty()) {
931
- return context.getRuntime().getNil();
932
- }
933
-
934
- return namespace;
935
- }
936
-
937
- /**
938
- * Return an array of XmlNamespace nodes based on the attributes
939
- * of this node.
940
- */
941
- @JRubyMethod
942
- public IRubyObject namespace_definitions(ThreadContext context) {
943
- // don't use namespace_definitions cache anymore since
944
- // namespaces might be deleted. Reflecting the result of
945
- // namesapce removals is complicated, so the cache might not be
946
- // updated.
947
- Ruby ruby = context.getRuntime();
948
- RubyArray namespace_definitions = ruby.newArray();
949
- if (doc == null) return namespace_definitions;
950
- List<XmlNamespace> namespaces = ((XmlDocument)doc).getNamespaceCache().get(node);
951
- for (XmlNamespace namespace : namespaces) {
952
- ((RubyArray)namespace_definitions).append(namespace);
953
- }
954
-
955
- return (RubyArray) namespace_definitions;
956
- }
957
-
958
- /**
959
- * Return an array of XmlNamespace nodes defined on this node and
960
- * on any ancestor node.
961
- */
962
- @JRubyMethod
963
- public IRubyObject namespace_scopes(ThreadContext context) {
964
- RubyArray parentNamespaces;
965
- RubyArray namespaces = (RubyArray) namespace_definitions(context);
966
-
967
- IRubyObject parent = parent(context);
968
- if (!parent.isNil()) {
969
- parentNamespaces = (RubyArray)
970
- ((XmlNode) parent).namespace_scopes(context);
971
- } else {
972
- parentNamespaces = getRuntime().newEmptyArray();
973
- }
974
-
975
- return parentNamespaces.op_plus(namespaces);
976
- }
977
-
978
- @JRubyMethod(name="namespaced_key?")
979
- public IRubyObject namespaced_key_p(ThreadContext context, IRubyObject elementLName, IRubyObject namespaceUri) {
980
- return this.attribute_with_ns(context, elementLName, namespaceUri).isNil() ?
981
- context.getRuntime().getFalse() : context.getRuntime().getTrue();
982
- }
983
-
984
- protected void setContent(IRubyObject content) {
985
- this.content = content;
986
- this.node.setTextContent(rubyStringToString(content));
987
- }
988
-
989
- private void setContent(String content) {
990
- node.setTextContent(content);
991
- this.content = null; // clear cache
992
- }
993
-
994
- @JRubyMethod(name = "native_content=", visibility = Visibility.PRIVATE)
995
- public IRubyObject native_content_set(ThreadContext context, IRubyObject content) {
996
- setContent(content);
997
- return content;
998
- }
999
-
1000
- /**
1001
- * @param args {IRubyObject io,
1002
- * IRubyObject encoding,
1003
- * IRubyObject indentString,
1004
- * IRubyObject options}
1005
- */
1006
- @JRubyMethod(required=4, visibility=Visibility.PRIVATE)
1007
- public IRubyObject native_write_to(ThreadContext context,
1008
- IRubyObject[] args) {
1009
-
1010
- IRubyObject io = args[0];
1011
- IRubyObject encoding = args[1];
1012
- IRubyObject indentString = args[2];
1013
- IRubyObject options = args[3];
1014
-
1015
- String encString = encoding.isNil() ? null : rubyStringToString(encoding);
1016
-
1017
- SaveContext ctx = new SaveContext(context, (Integer)options.toJava(Integer.class),
1018
- rubyStringToString(indentString),
1019
- encString);
1020
-
1021
- saveContent(context, ctx);
1022
-
1023
- RuntimeHelpers.invoke(context, io, "write", ctx.toRubyString(context.getRuntime()));
1024
-
1025
- return io;
1026
- }
1027
-
1028
- @JRubyMethod(name = {"next_sibling", "next"})
1029
- public IRubyObject next_sibling(ThreadContext context) {
1030
- return getCachedNodeOrCreate(context.getRuntime(), node.getNextSibling());
1031
- }
1032
-
1033
- @JRubyMethod(name = {"previous_sibling", "previous"})
1034
- public IRubyObject previous_sibling(ThreadContext context) {
1035
- return getCachedNodeOrCreate(context.getRuntime(), node.getPreviousSibling());
1036
- }
1037
-
1038
- @JRubyMethod(meta = true, rest = true)
1039
- public static IRubyObject new_from_str(ThreadContext context,
1040
- IRubyObject cls,
1041
- IRubyObject[] args) {
1042
- XmlDocument doc = (XmlDocument) XmlDocument.read_memory(context, args);
1043
- return doc.root(context);
1044
- }
1045
-
1046
- @JRubyMethod(name = {"node_name", "name"})
1047
- public IRubyObject node_name(ThreadContext context) {
1048
- return getNodeName(context);
1049
- }
1050
-
1051
- @JRubyMethod(name = {"node_name=", "name="})
1052
- public IRubyObject node_name_set(ThreadContext context, IRubyObject nodeName) {
1053
- String newName = rubyStringToString(nodeName);
1054
- getOwnerDocument().renameNode(node, null, newName);
1055
- setName(nodeName);
1056
- return this;
1057
- }
1058
-
1059
- @JRubyMethod(name = {"[]=", "set_attribute"})
1060
- public IRubyObject op_aset(ThreadContext context, IRubyObject index, IRubyObject val) {
1061
- return val;
1062
- }
1063
-
1064
- @JRubyMethod
1065
- public IRubyObject parent(ThreadContext context) {
1066
- /*
1067
- * Check if this node is the root node of the document.
1068
- * If so, parent is the document.
1069
- */
1070
- if (node.getOwnerDocument() != null &&
1071
- node.getOwnerDocument().getDocumentElement() == node) {
1072
- return document(context);
1073
- } else {
1074
- return getCachedNodeOrCreate(context.getRuntime(), node.getParentNode());
1075
- }
1076
- }
1077
-
1078
- @JRubyMethod
1079
- public IRubyObject path(ThreadContext context) {
1080
- return RubyString.newString(context.getRuntime(), NokogiriHelpers.getNodeCompletePath(this.node));
1081
- }
1082
-
1083
- @JRubyMethod
1084
- public IRubyObject pointer_id(ThreadContext context) {
1085
- return RubyFixnum.newFixnum(context.getRuntime(), this.node.hashCode());
1086
- }
1087
-
1088
- @JRubyMethod(name = {"remove_attribute", "delete"})
1089
- public IRubyObject remove_attribute(ThreadContext context, IRubyObject name) {
1090
- return this;
1091
- }
1092
-
1093
- @JRubyMethod(visibility=Visibility.PRIVATE)
1094
- public IRubyObject set_namespace(ThreadContext context, IRubyObject namespace) {
1095
- if (namespace.isNil()) {
1096
- if (doc != null) {
1097
- Node n = node;
1098
- String prefix = n.getPrefix();
1099
- String href = n.getNamespaceURI();
1100
- ((XmlDocument)doc).getNamespaceCache().remove(prefix == null ? "" : prefix, href);
1101
- n.getOwnerDocument().renameNode(n, null, n.getNodeName());
1102
- }
1103
- } else {
1104
- XmlNamespace ns = (XmlNamespace) namespace;
1105
- String prefix = rubyStringToString(ns.prefix(context));
1106
- String href = rubyStringToString(ns.href(context));
1107
-
1108
- // Assigning node = ...renameNode() or not seems to make no
1109
- // difference. Why not? -pmahoney
1110
- node = node.getOwnerDocument().renameNode(node, href, NokogiriHelpers.newQName(prefix, node));
1111
- }
1112
-
1113
- return this;
1114
- }
1115
-
1116
- @JRubyMethod(name = {"unlink", "remove"})
1117
- public IRubyObject unlink(ThreadContext context) {
1118
- if(node.getParentNode() == null) {
1119
- throw context.getRuntime().newRuntimeError("TYPE: " + node.getNodeType()+ " PARENT NULL");
1120
- } else {
1121
- node.getParentNode().removeChild(node);
1122
- }
1123
-
1124
- return this;
1125
- }
1126
-
1127
- /**
1128
- * The C-library simply returns libxml2 magic numbers. Here we
1129
- * convert Java Xml nodes to the appropriate constant defined in
1130
- * xml/node.rb.
1131
- */
1132
- @JRubyMethod(name = {"node_type", "type"})
1133
- public IRubyObject node_type(ThreadContext context) {
1134
- String type;
1135
- switch (node.getNodeType()) {
1136
- case Node.ELEMENT_NODE:
1137
- if (this instanceof XmlElementDecl)
1138
- type = "ELEMENT_DECL";
1139
- else if (this instanceof XmlAttributeDecl)
1140
- type = "ATTRIBUTE_DECL";
1141
- else if (this instanceof XmlEntityDecl)
1142
- type = "ENTITY_DECL";
1143
- else
1144
- type = "ELEMENT_NODE";
1145
- break;
1146
- case Node.ATTRIBUTE_NODE: type = "ATTRIBUTE_NODE"; break;
1147
- case Node.TEXT_NODE: type = "TEXT_NODE"; break;
1148
- case Node.CDATA_SECTION_NODE: type = "CDATA_SECTION_NODE"; break;
1149
- case Node.ENTITY_REFERENCE_NODE: type = "ENTITY_REF_NODE"; break;
1150
- case Node.ENTITY_NODE: type = "ENTITY_NODE"; break;
1151
- case Node.PROCESSING_INSTRUCTION_NODE: type = "PI_NODE"; break;
1152
- case Node.COMMENT_NODE: type = "COMMENT_NODE"; break;
1153
- case Node.DOCUMENT_NODE:
1154
- if (this instanceof HtmlDocument)
1155
- type = "HTML_DOCUMENT_NODE";
1156
- else
1157
- type = "DOCUMENT_NODE";
1158
- break;
1159
- case Node.DOCUMENT_TYPE_NODE: type = "DOCUMENT_TYPE_NODE"; break;
1160
- case Node.DOCUMENT_FRAGMENT_NODE: type = "DOCUMENT_FRAG_NODE"; break;
1161
- case Node.NOTATION_NODE: type = "NOTATION_NODE"; break;
1162
- default:
1163
- return context.getRuntime().newFixnum(0);
1164
- }
1165
-
1166
- return getNokogiriClass(context.getRuntime(), "Nokogiri::XML::Node").getConstant(type);
1167
- }
1168
-
1169
- @JRubyMethod
1170
- public IRubyObject line(ThreadContext context) {
1171
- Node root = getOwnerDocument();
1172
- int[] counter = new int[1];
1173
- count(root, counter);
1174
- return RubyFixnum.newFixnum(context.getRuntime(), counter[0]+1);
1175
- }
1176
-
1177
- private boolean count(Node node, int[] counter) {
1178
- if (node == this.node) {
1179
- return true;
1180
- }
1181
- NodeList list = node.getChildNodes();
1182
- for (int i=0; i<list.getLength(); i++) {
1183
- Node n = list.item(i);
1184
- if (n instanceof Text
1185
- && ((Text)n).getData().contains("\n")) {
1186
- counter[0] += 1;
1187
- }
1188
- if (count(n, counter)) return true;
1189
- }
1190
- return false;
1191
- }
1192
-
1193
- @JRubyMethod
1194
- public IRubyObject next_element(ThreadContext context) {
1195
- Node nextNode = node.getNextSibling();
1196
- Ruby ruby = context.getRuntime();
1197
- if (nextNode == null) return ruby.getNil();
1198
- if (nextNode instanceof Element) {
1199
- return getCachedNodeOrCreate(context.getRuntime(), nextNode);
1200
- }
1201
- Node deeper = nextNode.getNextSibling();
1202
- if (deeper == null) return ruby.getNil();
1203
- return getCachedNodeOrCreate(context.getRuntime(), deeper);
1204
- }
1205
-
1206
- @JRubyMethod
1207
- public IRubyObject previous_element(ThreadContext context) {
1208
- Node prevNode = node.getPreviousSibling();
1209
- Ruby ruby = context.getRuntime();
1210
- if (prevNode == null) return ruby.getNil();
1211
- if (prevNode instanceof Element) {
1212
- return getCachedNodeOrCreate(context.getRuntime(), prevNode);
1213
- }
1214
- Node shallower = prevNode.getPreviousSibling();
1215
- if (shallower == null) return ruby.getNil();
1216
- return getCachedNodeOrCreate(context.getRuntime(), shallower);
1217
- }
1218
-
1219
- protected enum AdoptScheme {
1220
- CHILD, PREV_SIBLING, NEXT_SIBLING, REPLACEMENT;
1221
- }
1222
-
1223
- /**
1224
- * Adopt XmlNode <code>other</code> into the document of
1225
- * <code>this</code> using the specified scheme.
1226
- */
1227
- protected IRubyObject adoptAs(ThreadContext context, AdoptScheme scheme,
1228
- IRubyObject other_) {
1229
- XmlNode other = asXmlNode(context, other_);
1230
- // this.doc might be null since this node can be empty node.
1231
- if (this.doc != null) {
1232
- other.setDocument(context, this.doc);
1233
- }
1234
- IRubyObject nodeOrTags = other;
1235
- Node thisNode = node;
1236
- Node otherNode = other.node;
1237
-
1238
- try {
1239
- Document doc = thisNode.getOwnerDocument();
1240
- if (doc != null && doc != otherNode.getOwnerDocument()) {
1241
- Node ret = doc.adoptNode(otherNode);
1242
- if (ret == null) {
1243
- throw context.getRuntime().newRuntimeError("Failed to take ownership of node");
1244
- }
1245
- }
1246
-
1247
- Node parent = thisNode.getParentNode();
1248
-
1249
- switch (scheme) {
1250
- case CHILD:
1251
- Node[] children = adoptAsChild(context, thisNode, otherNode);
1252
- if (children.length == 1 && otherNode == children[0]) {
1253
- break;
1254
- } else {
1255
- nodeOrTags = nodeArrayToRubyArray(context.getRuntime(), children);
1256
- }
1257
- break;
1258
- case PREV_SIBLING:
1259
- adoptAsPrevSibling(context, parent, thisNode, otherNode);
1260
- break;
1261
- case NEXT_SIBLING:
1262
- adoptAsNextSibling(context, parent, thisNode, otherNode);
1263
- break;
1264
- case REPLACEMENT:
1265
- adoptAsReplacement(context, parent, thisNode, otherNode);
1266
- break;
1267
- }
1268
- } catch (Exception e) {
1269
- throw context.getRuntime().newRuntimeError(e.toString());
1270
- }
1271
-
1272
- if (otherNode.getNodeType() == Node.TEXT_NODE) {
1273
- coalesceTextNodes(context, other);
1274
- }
1275
-
1276
- relink_namespace(context);
1277
- // post_add_child(context, this, other);
1278
-
1279
- return nodeOrTags;
1280
- }
1281
-
1282
- protected Node[] adoptAsChild(ThreadContext context, Node parent,
1283
- Node otherNode) {
1284
- /*
1285
- * This is a bit of a hack. C-Nokogiri allows adding a bare
1286
- * text node as the root element. Java (and XML spec?) does
1287
- * not. So we wrap the text node in an element.
1288
- */
1289
- if (parent.getNodeType() == Node.DOCUMENT_NODE &&
1290
- otherNode.getNodeType() == Node.TEXT_NODE) {
1291
- Element e = ((Document)parent).createElement("text");
1292
- e.appendChild(otherNode);
1293
- otherNode = e;
1294
- }
1295
- addNamespaceURIIfNeeded(otherNode);
1296
- parent.appendChild(otherNode);
1297
- Node[] nodes = new Node[1];
1298
- nodes[0] = otherNode;
1299
- return nodes;
1300
- }
1301
-
1302
- private void addNamespaceURIIfNeeded(Node child) {
1303
- if (this instanceof XmlDocumentFragment && ((XmlDocumentFragment)this).getFragmentContext() != null) {
1304
- XmlElement fragmentContext = ((XmlDocumentFragment)this).getFragmentContext();
1305
- String namespace_uri = fragmentContext.node.getNamespaceURI();
1306
- if (namespace_uri != null && namespace_uri.length() > 0) {
1307
- node.getOwnerDocument().renameNode(child, namespace_uri, child.getNodeName());
1308
- }
1309
- }
1310
- }
1311
-
1312
- protected void adoptAsPrevSibling(ThreadContext context,
1313
- Node parent,
1314
- Node thisNode, Node otherNode) {
1315
- if (parent == null) {
1316
- /* I'm not sure what do do here... A node with no
1317
- * parent can't exactly have a 'sibling', so we make
1318
- * otherNode parentless also. */
1319
- if (otherNode.getParentNode() != null)
1320
- otherNode.getParentNode().removeChild(otherNode);
1321
-
1322
- return;
1323
- }
1324
-
1325
- parent.insertBefore(otherNode, thisNode);
1326
- }
1327
-
1328
- protected void adoptAsNextSibling(ThreadContext context,
1329
- Node parent,
1330
- Node thisNode, Node otherNode) {
1331
- if (parent == null) {
1332
- /* I'm not sure what do do here... A node with no
1333
- * parent can't exactly have a 'sibling', so we make
1334
- * otherNode parentless also. */
1335
- if (otherNode.getParentNode() != null)
1336
- otherNode.getParentNode().removeChild(otherNode);
1337
-
1338
- return;
1339
- }
1340
-
1341
- Node nextSib = thisNode.getNextSibling();
1342
- if (nextSib != null) {
1343
- parent.insertBefore(otherNode, nextSib);
1344
- } else {
1345
- parent.appendChild(otherNode);
1346
- }
1347
- }
1348
-
1349
- protected void adoptAsReplacement(ThreadContext context,
1350
- Node parentNode,
1351
- Node thisNode, Node otherNode) {
1352
- if (parentNode == null) {
1353
- /* nothing to replace? */
1354
- return;
1355
- }
1356
-
1357
- try {
1358
- parentNode.replaceChild(otherNode, thisNode);
1359
- if (otherNode.getNodeType() != Node.TEXT_NODE) {
1360
- otherNode.getOwnerDocument().renameNode(otherNode, thisNode.getNamespaceURI(), otherNode.getNodeName());
1361
- }
1362
- } catch (Exception e) {
1363
- String prefix = "could not replace child: ";
1364
- throw context.getRuntime().newRuntimeError(prefix + e.toString());
1365
- }
1366
- }
1367
-
1368
- /**
1369
- * Add <code>other</code> as a child of <code>this</code>.
1370
- */
1371
- @JRubyMethod(visibility=Visibility.PRIVATE)
1372
- public IRubyObject add_child_node(ThreadContext context, IRubyObject other) {
1373
- return adoptAs(context, AdoptScheme.CHILD, other);
1374
- }
1375
-
1376
- /**
1377
- * Replace <code>this</code> with <code>other</code>.
1378
- */
1379
- @JRubyMethod(visibility=Visibility.PRIVATE)
1380
- public IRubyObject replace_node(ThreadContext context, IRubyObject other) {
1381
- return adoptAs(context, AdoptScheme.REPLACEMENT, other);
1382
- }
1383
-
1384
- /**
1385
- * Add <code>other</code> as a sibling before <code>this</code>.
1386
- */
1387
- @JRubyMethod(visibility=Visibility.PRIVATE)
1388
- public IRubyObject add_previous_sibling_node(ThreadContext context, IRubyObject other) {
1389
- return adoptAs(context, AdoptScheme.PREV_SIBLING, other);
1390
- }
1391
-
1392
- /**
1393
- * Add <code>other</code> as a sibling after <code>this</code>.
1394
- */
1395
- @JRubyMethod(visibility=Visibility.PRIVATE)
1396
- public IRubyObject add_next_sibling_node(ThreadContext context, IRubyObject other) {
1397
- return adoptAs(context, AdoptScheme.NEXT_SIBLING, other);
1398
- }
1399
- }