001: package org.jboss.portal.theme.impl.render.dynamic.json;
002:
003: import java.io.IOException;
004: import java.io.Writer;
005:
006: /*
007: Copyright (c) 2006 JSON.org
008:
009: Permission is hereby granted, free of charge, to any person obtaining a copy
010: of this software and associated documentation files (the "Software"), to deal
011: in the Software without restriction, including without limitation the rights
012: to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
013: copies of the Software, and to permit persons to whom the Software is
014: furnished to do so, subject to the following conditions:
015:
016: The above copyright notice and this permission notice shall be included in all
017: copies or substantial portions of the Software.
018:
019: The Software shall be used for Good, not Evil.
020:
021: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
022: IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
023: FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
024: AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
025: LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
026: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
027: SOFTWARE.
028: */
029:
030: /**
031: * JSONWriter provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON
032: * syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of
033: * JSONWriter can produce one JSON text.
034: * <p/>
035: * A JSONWriter instance provides a <code>value</code> method for appending values to the text, and a <code>key</code>
036: * method for adding keys before values in objects. There are <code>array</code> and <code>endArray</code> methods that
037: * make and bound array values, and <code>object</code> and <code>endObject</code> methods which make and bound object
038: * values. All of these methods return the JSONWriter instance,
039: * permitting a cascade style. For example, <pre>
040: * new JSONWriter(myWriter)
041: * .object()
042: * .key("JSON")
043: * .value("Hello, World!")
044: * .endObject();</pre> which writes <pre>
045: * {"JSON":"Hello, World!"}</pre>
046: * <p/>
047: * The first method called must be <code>array</code> or <code>object</code>. There are no methods for adding commas or
048: * colons. JSONWriter adds them for you. Objects and arrays can be nested up to 20 levels deep.
049: * <p/>
050: * This can sometimes be easier than using a JSONObject to build a string.
051: *
052: * @author JSON.org
053: * @version 2
054: */
055: public class JSONWriter {
056: private static final int maxdepth = 20;
057:
058: /** The comma flag determines if a comma should be output before the next value. */
059: private boolean comma;
060:
061: /** The current mode. Values: 'a' (array), 'd' (done), 'i' (initial), 'k' (key), 'o' (object). */
062: protected char mode;
063:
064: /** The object/array stack. */
065: private char stack[];
066:
067: /** The stack top index. A value of 0 indicates that the stack is empty. */
068: private int top;
069:
070: /** The writer that will receive the output. */
071: protected Writer writer;
072:
073: /** Make a fresh JSONWriter. It can be used to build one JSON text. */
074: public JSONWriter(Writer w) {
075: this .comma = false;
076: this .mode = 'i';
077: this .stack = new char[maxdepth];
078: this .top = 0;
079: this .writer = w;
080: }
081:
082: /**
083: * Append a value.
084: *
085: * @param s A string value.
086: * @return this
087: * @throws JSONException If the value is out of sequence.
088: */
089: private JSONWriter append(String s) throws JSONException {
090: if (s == null) {
091: throw new JSONException("Null pointer");
092: }
093: if (this .mode == 'o' || this .mode == 'a') {
094: try {
095: if (this .comma && this .mode == 'a') {
096: this .writer.write(',');
097: }
098: this .writer.write(s);
099: } catch (IOException e) {
100: throw new JSONException(e);
101: }
102: if (this .mode == 'o') {
103: this .mode = 'k';
104: }
105: this .comma = true;
106: return this ;
107: }
108: throw new JSONException("Value out of sequence.");
109: }
110:
111: /**
112: * Begin appending a new array. All values until the balancing <code>endArray</code> will be appended to this array.
113: * The <code>endArray</code> method must be called to mark the array's end.
114: *
115: * @return this
116: * @throws JSONException If the nesting is too deep, or if the object is started in the wrong place (for example as
117: * a key or after the end of the outermost array or object).
118: */
119: public JSONWriter array() throws JSONException {
120: if (this .mode == 'i' || this .mode == 'o' || this .mode == 'a') {
121: this .push('a');
122: this .append("[");
123: this .comma = false;
124: return this ;
125: }
126: throw new JSONException("Misplaced array.");
127: }
128:
129: /**
130: * End something.
131: *
132: * @param m Mode
133: * @param c Closing character
134: * @return this
135: * @throws JSONException If unbalanced.
136: */
137: private JSONWriter end(char m, char c) throws JSONException {
138: if (this .mode != m) {
139: throw new JSONException(m == 'o' ? "Misplaced endObject."
140: : "Misplaced endArray.");
141: }
142: this .pop(m);
143: try {
144: this .writer.write(c);
145: } catch (IOException e) {
146: throw new JSONException(e);
147: }
148: this .comma = true;
149: return this ;
150: }
151:
152: /**
153: * End an array. This method most be called to balance calls to <code>array</code>.
154: *
155: * @return this
156: * @throws JSONException If incorrectly nested.
157: */
158: public JSONWriter endArray() throws JSONException {
159: return this .end('a', ']');
160: }
161:
162: /**
163: * End an object. This method most be called to balance calls to <code>object</code>.
164: *
165: * @return this
166: * @throws JSONException If incorrectly nested.
167: */
168: public JSONWriter endObject() throws JSONException {
169: return this .end('k', '}');
170: }
171:
172: /**
173: * Append a key. The key will be associated with the next value. In an object, every value must be preceded by a
174: * key.
175: *
176: * @param s A key string.
177: * @return this
178: * @throws JSONException If the key is out of place. For example, keys do not belong in arrays or if the key is
179: * null.
180: */
181: public JSONWriter key(String s) throws JSONException {
182: if (s == null) {
183: throw new JSONException("Null key.");
184: }
185: if (this .mode == 'k') {
186: try {
187: if (this .comma) {
188: this .writer.write(',');
189: }
190: this .writer.write(JSONObject.quote(s));
191: this .writer.write(':');
192: this .comma = false;
193: this .mode = 'o';
194: return this ;
195: } catch (IOException e) {
196: throw new JSONException(e);
197: }
198: }
199: throw new JSONException("Misplaced key.");
200: }
201:
202: /**
203: * Begin appending a new object. All keys and values until the balancing <code>endObject</code> will be appended to
204: * this object. The <code>endObject</code> method must be called to mark the object's end.
205: *
206: * @return this
207: * @throws JSONException If the nesting is too deep, or if the object is started in the wrong place (for example as
208: * a key or after the end of the outermost array or object).
209: */
210: public JSONWriter object() throws JSONException {
211: if (this .mode == 'i') {
212: this .mode = 'o';
213: }
214: if (this .mode == 'o' || this .mode == 'a') {
215: this .append("{");
216: this .push('k');
217: this .comma = false;
218: return this ;
219: }
220: throw new JSONException("Misplaced object.");
221:
222: }
223:
224: /**
225: * Pop an array or object scope.
226: *
227: * @param c The scope to close.
228: * @throws JSONException If nesting is wrong.
229: */
230: private void pop(char c) throws JSONException {
231: if (this .top <= 0 || this .stack[this .top - 1] != c) {
232: throw new JSONException("Nesting error.");
233: }
234: this .top -= 1;
235: this .mode = this .top == 0 ? 'd' : this .stack[this .top - 1];
236: }
237:
238: /**
239: * Push an array or object scope.
240: *
241: * @param c The scope to open.
242: * @throws JSONException If nesting is too deep.
243: */
244: private void push(char c) throws JSONException {
245: if (this .top >= maxdepth) {
246: throw new JSONException("Nesting too deep.");
247: }
248: this .stack[this .top] = c;
249: this .mode = c;
250: this .top += 1;
251: }
252:
253: /**
254: * Append either the value <code>true</code> or the value <code>false</code>.
255: *
256: * @param b A boolean.
257: * @return this
258: * @throws JSONException
259: */
260: public JSONWriter value(boolean b) throws JSONException {
261: return this .append(b ? "true" : "false");
262: }
263:
264: /**
265: * Append a double value.
266: *
267: * @param d A double.
268: * @return this
269: * @throws JSONException If the number is not finite.
270: */
271: public JSONWriter value(double d) throws JSONException {
272: return this .value(new Double(d));
273: }
274:
275: /**
276: * Append a long value.
277: *
278: * @param l A long.
279: * @return this
280: * @throws JSONException
281: */
282: public JSONWriter value(long l) throws JSONException {
283: return this .append(Long.toString(l));
284: }
285:
286: /**
287: * Append an object value.
288: *
289: * @param o The object to append. It can be null, or a Boolean, Number, String, JSONObject, or JSONArray, or an
290: * object with a toJSONString() method.
291: * @return this
292: * @throws JSONException If the value is out of sequence.
293: */
294: public JSONWriter value(Object o) throws JSONException {
295: return this.append(JSONObject.valueToString(o));
296: }
297: }
|