增加 welcome-file 以支持 Tomcat 7 下根路径可以被 map 到 LoginServlet。
[jibu.git] / plugins / jibu-json / src / main / java / org / gaixie / jibu / json / XML.java
blobdf67957fdee60b01a2598e55c39d680d1f4cc8af
1 package org.gaixie.jibu.json;
2 /*
3 Copyright (c) 2002 JSON.org
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
12 The above copyright notice and this permission notice shall be included in all
13 copies or substantial portions of the Software.
15 The Software shall be used for Good, not Evil.
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 SOFTWARE.
26 import java.util.Iterator;
29 /**
30 * This provides static methods to convert an XML text into a JSONObject,
31 * and to covert a JSONObject into an XML text.
32 * @author JSON.org
33 * @version 2008-10-14
35 public class XML {
37 /** The Character '&'. */
38 public static final Character AMP = new Character('&');
40 /** The Character '''. */
41 public static final Character APOS = new Character('\'');
43 /** The Character '!'. */
44 public static final Character BANG = new Character('!');
46 /** The Character '='. */
47 public static final Character EQ = new Character('=');
49 /** The Character '>'. */
50 public static final Character GT = new Character('>');
52 /** The Character '<'. */
53 public static final Character LT = new Character('<');
55 /** The Character '?'. */
56 public static final Character QUEST = new Character('?');
58 /** The Character '"'. */
59 public static final Character QUOT = new Character('"');
61 /** The Character '/'. */
62 public static final Character SLASH = new Character('/');
64 /**
65 * Replace special characters with XML escapes:
66 * <pre>
67 * &amp; <small>(ampersand)</small> is replaced by &amp;amp;
68 * &lt; <small>(less than)</small> is replaced by &amp;lt;
69 * &gt; <small>(greater than)</small> is replaced by &amp;gt;
70 * &quot; <small>(double quote)</small> is replaced by &amp;quot;
71 * </pre>
72 * @param string The string to be escaped.
73 * @return The escaped string.
75 public static String escape(String string) {
76 StringBuffer sb = new StringBuffer();
77 for (int i = 0, len = string.length(); i < len; i++) {
78 char c = string.charAt(i);
79 switch (c) {
80 case '&':
81 sb.append("&amp;");
82 break;
83 case '<':
84 sb.append("&lt;");
85 break;
86 case '>':
87 sb.append("&gt;");
88 break;
89 case '"':
90 sb.append("&quot;");
91 break;
92 default:
93 sb.append(c);
96 return sb.toString();
99 /**
100 * Throw an exception if the string contains whitespace.
101 * Whitespace is not allowed in tagNames and attributes.
102 * @param string
103 * @throws JSONException
105 public static void noSpace(String string) throws JSONException {
106 int i, length = string.length();
107 if (length == 0) {
108 throw new JSONException("Empty string.");
110 for (i = 0; i < length; i += 1) {
111 if (Character.isWhitespace(string.charAt(i))) {
112 throw new JSONException("'" + string +
113 "' contains a space character.");
119 * Scan the content following the named tag, attaching it to the context.
120 * @param x The XMLTokener containing the source string.
121 * @param context The JSONObject that will include the new material.
122 * @param name The tag name.
123 * @return true if the close tag is processed.
124 * @throws JSONException
126 private static boolean parse(XMLTokener x, JSONObject context,
127 String name) throws JSONException {
128 char c;
129 int i;
130 String n;
131 JSONObject o = null;
132 String s;
133 Object t;
135 // Test for and skip past these forms:
136 // <!-- ... -->
137 // <! ... >
138 // <![ ... ]]>
139 // <? ... ?>
140 // Report errors for these forms:
141 // <>
142 // <=
143 // <<
145 t = x.nextToken();
147 // <!
149 if (t == BANG) {
150 c = x.next();
151 if (c == '-') {
152 if (x.next() == '-') {
153 x.skipPast("-->");
154 return false;
156 x.back();
157 } else if (c == '[') {
158 t = x.nextToken();
159 if (t.equals("CDATA")) {
160 if (x.next() == '[') {
161 s = x.nextCDATA();
162 if (s.length() > 0) {
163 context.accumulate("content", s);
165 return false;
168 throw x.syntaxError("Expected 'CDATA['");
170 i = 1;
171 do {
172 t = x.nextMeta();
173 if (t == null) {
174 throw x.syntaxError("Missing '>' after '<!'.");
175 } else if (t == LT) {
176 i += 1;
177 } else if (t == GT) {
178 i -= 1;
180 } while (i > 0);
181 return false;
182 } else if (t == QUEST) {
184 // <?
186 x.skipPast("?>");
187 return false;
188 } else if (t == SLASH) {
190 // Close tag </
192 t = x.nextToken();
193 if (name == null) {
194 throw x.syntaxError("Mismatched close tag" + t);
196 if (!t.equals(name)) {
197 throw x.syntaxError("Mismatched " + name + " and " + t);
199 if (x.nextToken() != GT) {
200 throw x.syntaxError("Misshaped close tag");
202 return true;
204 } else if (t instanceof Character) {
205 throw x.syntaxError("Misshaped tag");
207 // Open tag <
209 } else {
210 n = (String)t;
211 t = null;
212 o = new JSONObject();
213 for (;;) {
214 if (t == null) {
215 t = x.nextToken();
218 // attribute = value
220 if (t instanceof String) {
221 s = (String)t;
222 t = x.nextToken();
223 if (t == EQ) {
224 t = x.nextToken();
225 if (!(t instanceof String)) {
226 throw x.syntaxError("Missing value");
228 o.accumulate(s, JSONObject.stringToValue((String)t));
229 t = null;
230 } else {
231 o.accumulate(s, "");
234 // Empty tag <.../>
236 } else if (t == SLASH) {
237 if (x.nextToken() != GT) {
238 throw x.syntaxError("Misshaped tag");
240 context.accumulate(n, o);
241 return false;
243 // Content, between <...> and </...>
245 } else if (t == GT) {
246 for (;;) {
247 t = x.nextContent();
248 if (t == null) {
249 if (n != null) {
250 throw x.syntaxError("Unclosed tag " + n);
252 return false;
253 } else if (t instanceof String) {
254 s = (String)t;
255 if (s.length() > 0) {
256 o.accumulate("content", JSONObject.stringToValue(s));
259 // Nested element
261 } else if (t == LT) {
262 if (parse(x, o, n)) {
263 if (o.length() == 0) {
264 context.accumulate(n, "");
265 } else if (o.length() == 1 &&
266 o.opt("content") != null) {
267 context.accumulate(n, o.opt("content"));
268 } else {
269 context.accumulate(n, o);
271 return false;
275 } else {
276 throw x.syntaxError("Misshaped tag");
284 * Convert a well-formed (but not necessarily valid) XML string into a
285 * JSONObject. Some information may be lost in this transformation
286 * because JSON is a data format and XML is a document format. XML uses
287 * elements, attributes, and content text, while JSON uses unordered
288 * collections of name/value pairs and arrays of values. JSON does not
289 * does not like to distinguish between elements and attributes.
290 * Sequences of similar elements are represented as JSONArrays. Content
291 * text may be placed in a "content" member. Comments, prologs, DTDs, and
292 * <code>&lt;[ [ ]]></code> are ignored.
293 * @param string The source string.
294 * @return A JSONObject containing the structured data from the XML string.
295 * @throws JSONException
297 public static JSONObject toJSONObject(String string) throws JSONException {
298 JSONObject o = new JSONObject();
299 XMLTokener x = new XMLTokener(string);
300 while (x.more() && x.skipPast("<")) {
301 parse(x, o, null);
303 return o;
308 * Convert a JSONObject into a well-formed, element-normal XML string.
309 * @param o A JSONObject.
310 * @return A string.
311 * @throws JSONException
313 public static String toString(Object o) throws JSONException {
314 return toString(o, null);
319 * Convert a JSONObject into a well-formed, element-normal XML string.
320 * @param o A JSONObject.
321 * @param tagName The optional name of the enclosing tag.
322 * @return A string.
323 * @throws JSONException
325 public static String toString(Object o, String tagName)
326 throws JSONException {
327 StringBuffer b = new StringBuffer();
328 int i;
329 JSONArray ja;
330 JSONObject jo;
331 String k;
332 Iterator keys;
333 int len;
334 String s;
335 Object v;
336 if (o instanceof JSONObject) {
338 // Emit <tagName>
340 if (tagName != null) {
341 b.append('<');
342 b.append(tagName);
343 b.append('>');
346 // Loop thru the keys.
348 jo = (JSONObject)o;
349 keys = jo.keys();
350 while (keys.hasNext()) {
351 k = keys.next().toString();
352 v = jo.opt(k);
353 if (v == null) {
354 v = "";
356 if (v instanceof String) {
357 s = (String)v;
358 } else {
359 s = null;
362 // Emit content in body
364 if (k.equals("content")) {
365 if (v instanceof JSONArray) {
366 ja = (JSONArray)v;
367 len = ja.length();
368 for (i = 0; i < len; i += 1) {
369 if (i > 0) {
370 b.append('\n');
372 b.append(escape(ja.get(i).toString()));
374 } else {
375 b.append(escape(v.toString()));
378 // Emit an array of similar keys
380 } else if (v instanceof JSONArray) {
381 ja = (JSONArray)v;
382 len = ja.length();
383 for (i = 0; i < len; i += 1) {
384 v = ja.get(i);
385 if (v instanceof JSONArray) {
386 b.append('<');
387 b.append(k);
388 b.append('>');
389 b.append(toString(v));
390 b.append("</");
391 b.append(k);
392 b.append('>');
393 } else {
394 b.append(toString(v, k));
397 } else if (v.equals("")) {
398 b.append('<');
399 b.append(k);
400 b.append("/>");
402 // Emit a new tag <k>
404 } else {
405 b.append(toString(v, k));
408 if (tagName != null) {
410 // Emit the </tagname> close tag
412 b.append("</");
413 b.append(tagName);
414 b.append('>');
416 return b.toString();
418 // XML does not have good support for arrays. If an array appears in a place
419 // where XML is lacking, synthesize an <array> element.
421 } else if (o instanceof JSONArray) {
422 ja = (JSONArray)o;
423 len = ja.length();
424 for (i = 0; i < len; ++i) {
425 v = ja.opt(i);
426 b.append(toString(v, (tagName == null) ? "array" : tagName));
428 return b.toString();
429 } else {
430 s = (o == null) ? "null" : escape(o.toString());
431 return (tagName == null) ? "\"" + s + "\"" :
432 (s.length() == 0) ? "<" + tagName + "/>" :
433 "<" + tagName + ">" + s + "</" + tagName + ">";