nokogiri-fitzsimmons 1.5.5.3-java

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