PageRenderTime 48ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/Agetac-server/lib/restlet/org.json_2.0/src/org/json/XML.java

https://github.com/Agetac/Server
Java | 437 lines | 281 code | 53 blank | 103 comment | 109 complexity | 97c7d3904e6fd75a3905f977af31570b MD5 | raw file
  1. package org.json;
  2. /*
  3. Copyright (c) 2002 JSON.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. The Software shall be used for Good, not Evil.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. SOFTWARE.
  20. */
  21. import java.util.Iterator;
  22. /**
  23. * This provides static methods to convert an XML text into a JSONObject,
  24. * and to covert a JSONObject into an XML text.
  25. * @author JSON.org
  26. * @version 2008-10-14
  27. */
  28. public class XML {
  29. /** The Character '&'. */
  30. public static final Character AMP = new Character('&');
  31. /** The Character '''. */
  32. public static final Character APOS = new Character('\'');
  33. /** The Character '!'. */
  34. public static final Character BANG = new Character('!');
  35. /** The Character '='. */
  36. public static final Character EQ = new Character('=');
  37. /** The Character '>'. */
  38. public static final Character GT = new Character('>');
  39. /** The Character '<'. */
  40. public static final Character LT = new Character('<');
  41. /** The Character '?'. */
  42. public static final Character QUEST = new Character('?');
  43. /** The Character '"'. */
  44. public static final Character QUOT = new Character('"');
  45. /** The Character '/'. */
  46. public static final Character SLASH = new Character('/');
  47. /**
  48. * Replace special characters with XML escapes:
  49. * <pre>
  50. * &amp; <small>(ampersand)</small> is replaced by &amp;amp;
  51. * &lt; <small>(less than)</small> is replaced by &amp;lt;
  52. * &gt; <small>(greater than)</small> is replaced by &amp;gt;
  53. * &quot; <small>(double quote)</small> is replaced by &amp;quot;
  54. * </pre>
  55. * @param string The string to be escaped.
  56. * @return The escaped string.
  57. */
  58. public static String escape(String string) {
  59. StringBuffer sb = new StringBuffer();
  60. for (int i = 0, len = string.length(); i < len; i++) {
  61. char c = string.charAt(i);
  62. switch (c) {
  63. case '&':
  64. sb.append("&amp;");
  65. break;
  66. case '<':
  67. sb.append("&lt;");
  68. break;
  69. case '>':
  70. sb.append("&gt;");
  71. break;
  72. case '"':
  73. sb.append("&quot;");
  74. break;
  75. default:
  76. sb.append(c);
  77. }
  78. }
  79. return sb.toString();
  80. }
  81. /**
  82. * Throw an exception if the string contains whitespace.
  83. * Whitespace is not allowed in tagNames and attributes.
  84. * @param string
  85. * @throws JSONException
  86. */
  87. public static void noSpace(String string) throws JSONException {
  88. int i, length = string.length();
  89. if (length == 0) {
  90. throw new JSONException("Empty string.");
  91. }
  92. for (i = 0; i < length; i += 1) {
  93. if (Character.isWhitespace(string.charAt(i))) {
  94. throw new JSONException("'" + string +
  95. "' contains a space character.");
  96. }
  97. }
  98. }
  99. /**
  100. * Scan the content following the named tag, attaching it to the context.
  101. * @param x The XMLTokener containing the source string.
  102. * @param context The JSONObject that will include the new material.
  103. * @param name The tag name.
  104. * @return true if the close tag is processed.
  105. * @throws JSONException
  106. */
  107. private static boolean parse(XMLTokener x, JSONObject context,
  108. String name) throws JSONException {
  109. char c;
  110. int i;
  111. String n;
  112. JSONObject o = null;
  113. String s;
  114. Object t;
  115. // Test for and skip past these forms:
  116. // <!-- ... -->
  117. // <! ... >
  118. // <![ ... ]]>
  119. // <? ... ?>
  120. // Report errors for these forms:
  121. // <>
  122. // <=
  123. // <<
  124. t = x.nextToken();
  125. // <!
  126. if (t == BANG) {
  127. c = x.next();
  128. if (c == '-') {
  129. if (x.next() == '-') {
  130. x.skipPast("-->");
  131. return false;
  132. }
  133. x.back();
  134. } else if (c == '[') {
  135. t = x.nextToken();
  136. if (t.equals("CDATA")) {
  137. if (x.next() == '[') {
  138. s = x.nextCDATA();
  139. if (s.length() > 0) {
  140. context.accumulate("content", s);
  141. }
  142. return false;
  143. }
  144. }
  145. throw x.syntaxError("Expected 'CDATA['");
  146. }
  147. i = 1;
  148. do {
  149. t = x.nextMeta();
  150. if (t == null) {
  151. throw x.syntaxError("Missing '>' after '<!'.");
  152. } else if (t == LT) {
  153. i += 1;
  154. } else if (t == GT) {
  155. i -= 1;
  156. }
  157. } while (i > 0);
  158. return false;
  159. } else if (t == QUEST) {
  160. // <?
  161. x.skipPast("?>");
  162. return false;
  163. } else if (t == SLASH) {
  164. // Close tag </
  165. t = x.nextToken();
  166. if (name == null) {
  167. throw x.syntaxError("Mismatched close tag" + t);
  168. }
  169. if (!t.equals(name)) {
  170. throw x.syntaxError("Mismatched " + name + " and " + t);
  171. }
  172. if (x.nextToken() != GT) {
  173. throw x.syntaxError("Misshaped close tag");
  174. }
  175. return true;
  176. } else if (t instanceof Character) {
  177. throw x.syntaxError("Misshaped tag");
  178. // Open tag <
  179. } else {
  180. n = (String)t;
  181. t = null;
  182. o = new JSONObject();
  183. for (;;) {
  184. if (t == null) {
  185. t = x.nextToken();
  186. }
  187. // attribute = value
  188. if (t instanceof String) {
  189. s = (String)t;
  190. t = x.nextToken();
  191. if (t == EQ) {
  192. t = x.nextToken();
  193. if (!(t instanceof String)) {
  194. throw x.syntaxError("Missing value");
  195. }
  196. o.accumulate(s, JSONObject.stringToValue((String)t));
  197. t = null;
  198. } else {
  199. o.accumulate(s, "");
  200. }
  201. // Empty tag <.../>
  202. } else if (t == SLASH) {
  203. if (x.nextToken() != GT) {
  204. throw x.syntaxError("Misshaped tag");
  205. }
  206. context.accumulate(n, o);
  207. return false;
  208. // Content, between <...> and </...>
  209. } else if (t == GT) {
  210. for (;;) {
  211. t = x.nextContent();
  212. if (t == null) {
  213. if (n != null) {
  214. throw x.syntaxError("Unclosed tag " + n);
  215. }
  216. return false;
  217. } else if (t instanceof String) {
  218. s = (String)t;
  219. if (s.length() > 0) {
  220. o.accumulate("content", JSONObject.stringToValue(s));
  221. }
  222. // Nested element
  223. } else if (t == LT) {
  224. if (parse(x, o, n)) {
  225. if (o.length() == 0) {
  226. context.accumulate(n, "");
  227. } else if (o.length() == 1 &&
  228. o.opt("content") != null) {
  229. context.accumulate(n, o.opt("content"));
  230. } else {
  231. context.accumulate(n, o);
  232. }
  233. return false;
  234. }
  235. }
  236. }
  237. } else {
  238. throw x.syntaxError("Misshaped tag");
  239. }
  240. }
  241. }
  242. }
  243. /**
  244. * Convert a well-formed (but not necessarily valid) XML string into a
  245. * JSONObject. Some information may be lost in this transformation
  246. * because JSON is a data format and XML is a document format. XML uses
  247. * elements, attributes, and content text, while JSON uses unordered
  248. * collections of name/value pairs and arrays of values. JSON does not
  249. * does not like to distinguish between elements and attributes.
  250. * Sequences of similar elements are represented as JSONArrays. Content
  251. * text may be placed in a "content" member. Comments, prologs, DTDs, and
  252. * <code>&lt;[ [ ]]></code> are ignored.
  253. * @param string The source string.
  254. * @return A JSONObject containing the structured data from the XML string.
  255. * @throws JSONException
  256. */
  257. public static JSONObject toJSONObject(String string) throws JSONException {
  258. JSONObject o = new JSONObject();
  259. XMLTokener x = new XMLTokener(string);
  260. while (x.more() && x.skipPast("<")) {
  261. parse(x, o, null);
  262. }
  263. return o;
  264. }
  265. /**
  266. * Convert a JSONObject into a well-formed, element-normal XML string.
  267. * @param o A JSONObject.
  268. * @return A string.
  269. * @throws JSONException
  270. */
  271. public static String toString(Object o) throws JSONException {
  272. return toString(o, null);
  273. }
  274. /**
  275. * Convert a JSONObject into a well-formed, element-normal XML string.
  276. * @param o A JSONObject.
  277. * @param tagName The optional name of the enclosing tag.
  278. * @return A string.
  279. * @throws JSONException
  280. */
  281. public static String toString(Object o, String tagName)
  282. throws JSONException {
  283. StringBuffer b = new StringBuffer();
  284. int i;
  285. JSONArray ja;
  286. JSONObject jo;
  287. String k;
  288. Iterator keys;
  289. int len;
  290. String s;
  291. Object v;
  292. if (o instanceof JSONObject) {
  293. // Emit <tagName>
  294. if (tagName != null) {
  295. b.append('<');
  296. b.append(tagName);
  297. b.append('>');
  298. }
  299. // Loop thru the keys.
  300. jo = (JSONObject)o;
  301. keys = jo.keys();
  302. while (keys.hasNext()) {
  303. k = keys.next().toString();
  304. v = jo.opt(k);
  305. if (v == null) {
  306. v = "";
  307. }
  308. if (v instanceof String) {
  309. s = (String)v;
  310. } else {
  311. s = null;
  312. }
  313. // Emit content in body
  314. if (k.equals("content")) {
  315. if (v instanceof JSONArray) {
  316. ja = (JSONArray)v;
  317. len = ja.length();
  318. for (i = 0; i < len; i += 1) {
  319. if (i > 0) {
  320. b.append('\n');
  321. }
  322. b.append(escape(ja.get(i).toString()));
  323. }
  324. } else {
  325. b.append(escape(v.toString()));
  326. }
  327. // Emit an array of similar keys
  328. } else if (v instanceof JSONArray) {
  329. ja = (JSONArray)v;
  330. len = ja.length();
  331. for (i = 0; i < len; i += 1) {
  332. v = ja.get(i);
  333. if (v instanceof JSONArray) {
  334. b.append('<');
  335. b.append(k);
  336. b.append('>');
  337. b.append(toString(v));
  338. b.append("</");
  339. b.append(k);
  340. b.append('>');
  341. } else {
  342. b.append(toString(v, k));
  343. }
  344. }
  345. } else if (v.equals("")) {
  346. b.append('<');
  347. b.append(k);
  348. b.append("/>");
  349. // Emit a new tag <k>
  350. } else {
  351. b.append(toString(v, k));
  352. }
  353. }
  354. if (tagName != null) {
  355. // Emit the </tagname> close tag
  356. b.append("</");
  357. b.append(tagName);
  358. b.append('>');
  359. }
  360. return b.toString();
  361. // XML does not have good support for arrays. If an array appears in a place
  362. // where XML is lacking, synthesize an <array> element.
  363. } else if (o instanceof JSONArray) {
  364. ja = (JSONArray)o;
  365. len = ja.length();
  366. for (i = 0; i < len; ++i) {
  367. v = ja.opt(i);
  368. b.append(toString(v, (tagName == null) ? "array" : tagName));
  369. }
  370. return b.toString();
  371. } else {
  372. s = (o == null) ? "null" : escape(o.toString());
  373. return (tagName == null) ? "\"" + s + "\"" :
  374. (s.length() == 0) ? "<" + tagName + "/>" :
  375. "<" + tagName + ">" + s + "</" + tagName + ">";
  376. }
  377. }
  378. }