[DMAAP-48] Initial code import
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / json / JSONWriter.java
1 /*******************************************************************************\r
2  * ============LICENSE_START==================================================\r
3  * * org.onap.dmaap\r
4  * * ===========================================================================\r
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * * ===========================================================================\r
7  * * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * * you may not use this file except in compliance with the License.\r
9  * * You may obtain a copy of the License at\r
10  * * \r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * * \r
13  *  * Unless required by applicable law or agreed to in writing, software\r
14  * * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * * See the License for the specific language governing permissions and\r
17  * * limitations under the License.\r
18  * * ============LICENSE_END====================================================\r
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 package org.json;\r
24 \r
25 import java.io.IOException;\r
26 import java.io.Writer;\r
27 \r
28 /*\r
29 Copyright (c) 2006 JSON.org\r
30 \r
31 Permission is hereby granted, free of charge, to any person obtaining a copy\r
32 of this software and associated documentation files (the "Software"), to deal\r
33 in the Software without restriction, including without limitation the rights\r
34 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
35 copies of the Software, and to permit persons to whom the Software is\r
36 furnished to do so, subject to the following conditions:\r
37 \r
38 The above copyright notice and this permission notice shall be included in all\r
39 copies or substantial portions of the Software.\r
40 \r
41 The Software shall be used for Good, not Evil.\r
42 \r
43 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
44 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
45 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
46 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
47 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
48 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r
49 SOFTWARE.\r
50 */\r
51 \r
52 /**\r
53  * JSONWriter provides a quick and convenient way of producing JSON text.\r
54  * The texts produced strictly conform to JSON syntax rules. No whitespace is\r
55  * added, so the results are ready for transmission or storage. Each instance of\r
56  * JSONWriter can produce one JSON text.\r
57  * <p>\r
58  * A JSONWriter instance provides a <code>value</code> method for appending\r
59  * values to the\r
60  * text, and a <code>key</code>\r
61  * method for adding keys before values in objects. There are <code>array</code>\r
62  * and <code>endArray</code> methods that make and bound array values, and\r
63  * <code>object</code> and <code>endObject</code> methods which make and bound\r
64  * object values. All of these methods return the JSONWriter instance,\r
65  * permitting a cascade style. For example, <pre>\r
66  * new JSONWriter(myWriter)\r
67  *     .object()\r
68  *         .key("JSON")\r
69  *         .value("Hello, World!")\r
70  *     .endObject();</pre> which writes <pre>\r
71  * {"JSON":"Hello, World!"}</pre>\r
72  * <p>\r
73  * The first method called must be <code>array</code> or <code>object</code>.\r
74  * There are no methods for adding commas or colons. JSONWriter adds them for\r
75  * you. Objects and arrays can be nested up to 20 levels deep.\r
76  * <p>\r
77  * This can sometimes be easier than using a JSONObject to build a string.\r
78  * @author JSON.org\r
79  * @version 2011-11-24\r
80  */\r
81 public class JSONWriter {\r
82     private static final int maxdepth = 200;\r
83 \r
84     /**\r
85      * The comma flag determines if a comma should be output before the next\r
86      * value.\r
87      */\r
88     private boolean comma;\r
89 \r
90     /**\r
91      * The current mode. Values:\r
92      * 'a' (array),\r
93      * 'd' (done),\r
94      * 'i' (initial),\r
95      * 'k' (key),\r
96      * 'o' (object).\r
97      */\r
98     protected char mode;\r
99 \r
100     /**\r
101      * The object/array stack.\r
102      */\r
103     private final JSONObject stack[];\r
104 \r
105     /**\r
106      * The stack top index. A value of 0 indicates that the stack is empty.\r
107      */\r
108     private int top;\r
109 \r
110     /**\r
111      * The writer that will receive the output.\r
112      */\r
113     protected Writer writer;\r
114 \r
115     /**\r
116      * Make a fresh JSONWriter. It can be used to build one JSON text.\r
117      */\r
118     public JSONWriter(Writer w) {\r
119         this.comma = false;\r
120         this.mode = 'i';\r
121         this.stack = new JSONObject[maxdepth];\r
122         this.top = 0;\r
123         this.writer = w;\r
124     }\r
125 \r
126     /**\r
127      * Append a value.\r
128      * @param string A string value.\r
129      * @return this\r
130      * @throws JSONException If the value is out of sequence.\r
131      */\r
132     private JSONWriter append(String string) throws JSONException {\r
133         if (string == null) {\r
134             throw new JSONException("Null pointer");\r
135         }\r
136         if (this.mode == 'o' || this.mode == 'a') {\r
137             try {\r
138                 if (this.comma && this.mode == 'a') {\r
139                     this.writer.write(',');\r
140                 }\r
141                 this.writer.write(string);\r
142             } catch (IOException e) {\r
143                 throw new JSONException(e);\r
144             }\r
145             if (this.mode == 'o') {\r
146                 this.mode = 'k';\r
147             }\r
148             this.comma = true;\r
149             return this;\r
150         }\r
151         throw new JSONException("Value out of sequence.");\r
152     }\r
153 \r
154     /**\r
155      * Begin appending a new array. All values until the balancing\r
156      * <code>endArray</code> will be appended to this array. The\r
157      * <code>endArray</code> method must be called to mark the array's end.\r
158      * @return this\r
159      * @throws JSONException If the nesting is too deep, or if the object is\r
160      * started in the wrong place (for example as a key or after the end of the\r
161      * outermost array or object).\r
162      */\r
163     public JSONWriter array() throws JSONException {\r
164         if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {\r
165             this.push(null);\r
166             this.append("[");\r
167             this.comma = false;\r
168             return this;\r
169         }\r
170         throw new JSONException("Misplaced array.");\r
171     }\r
172 \r
173     /**\r
174      * End something.\r
175      * @param mode Mode\r
176      * @param c Closing character\r
177      * @return this\r
178      * @throws JSONException If unbalanced.\r
179      */\r
180     private JSONWriter end(char mode, char c) throws JSONException {\r
181         if (this.mode != mode) {\r
182             throw new JSONException(mode == 'a'\r
183                 ? "Misplaced endArray."\r
184                 : "Misplaced endObject.");\r
185         }\r
186         this.pop(mode);\r
187         try {\r
188             this.writer.write(c);\r
189         } catch (IOException e) {\r
190             throw new JSONException(e);\r
191         }\r
192         this.comma = true;\r
193         return this;\r
194     }\r
195 \r
196     /**\r
197      * End an array. This method most be called to balance calls to\r
198      * <code>array</code>.\r
199      * @return this\r
200      * @throws JSONException If incorrectly nested.\r
201      */\r
202     public JSONWriter endArray() throws JSONException {\r
203         return this.end('a', ']');\r
204     }\r
205 \r
206     /**\r
207      * End an object. This method most be called to balance calls to\r
208      * <code>object</code>.\r
209      * @return this\r
210      * @throws JSONException If incorrectly nested.\r
211      */\r
212     public JSONWriter endObject() throws JSONException {\r
213         return this.end('k', '}');\r
214     }\r
215 \r
216     /**\r
217      * Append a key. The key will be associated with the next value. In an\r
218      * object, every value must be preceded by a key.\r
219      * @param string A key string.\r
220      * @return this\r
221      * @throws JSONException If the key is out of place. For example, keys\r
222      *  do not belong in arrays or if the key is null.\r
223      */\r
224     public JSONWriter key(String string) throws JSONException {\r
225         if (string == null) {\r
226             throw new JSONException("Null key.");\r
227         }\r
228         if (this.mode == 'k') {\r
229             try {\r
230                 this.stack[this.top - 1].putOnce(string, Boolean.TRUE);\r
231                 if (this.comma) {\r
232                     this.writer.write(',');\r
233                 }\r
234                 this.writer.write(JSONObject.quote(string));\r
235                 this.writer.write(':');\r
236                 this.comma = false;\r
237                 this.mode = 'o';\r
238                 return this;\r
239             } catch (IOException e) {\r
240                 throw new JSONException(e);\r
241             }\r
242         }\r
243         throw new JSONException("Misplaced key.");\r
244     }\r
245 \r
246 \r
247     /**\r
248      * Begin appending a new object. All keys and values until the balancing\r
249      * <code>endObject</code> will be appended to this object. The\r
250      * <code>endObject</code> method must be called to mark the object's end.\r
251      * @return this\r
252      * @throws JSONException If the nesting is too deep, or if the object is\r
253      * started in the wrong place (for example as a key or after the end of the\r
254      * outermost array or object).\r
255      */\r
256     public JSONWriter object() throws JSONException {\r
257         if (this.mode == 'i') {\r
258             this.mode = 'o';\r
259         }\r
260         if (this.mode == 'o' || this.mode == 'a') {\r
261             this.append("{");\r
262             this.push(new JSONObject());\r
263             this.comma = false;\r
264             return this;\r
265         }\r
266         throw new JSONException("Misplaced object.");\r
267 \r
268     }\r
269 \r
270 \r
271     /**\r
272      * Pop an array or object scope.\r
273      * @param c The scope to close.\r
274      * @throws JSONException If nesting is wrong.\r
275      */\r
276     private void pop(char c) throws JSONException {\r
277         if (this.top <= 0) {\r
278             throw new JSONException("Nesting error.");\r
279         }\r
280         char m = this.stack[this.top - 1] == null ? 'a' : 'k';\r
281         if (m != c) {\r
282             throw new JSONException("Nesting error.");\r
283         }\r
284         this.top -= 1;\r
285         this.mode = this.top == 0\r
286             ? 'd'\r
287             : this.stack[this.top - 1] == null\r
288             ? 'a'\r
289             : 'k';\r
290     }\r
291 \r
292     /**\r
293      * Push an array or object scope.\r
294      * @param jo The scope to open.\r
295      * @throws JSONException If nesting is too deep.\r
296      */\r
297     private void push(JSONObject jo) throws JSONException {\r
298         if (this.top >= maxdepth) {\r
299             throw new JSONException("Nesting too deep.");\r
300         }\r
301         this.stack[this.top] = jo;\r
302         this.mode = jo == null ? 'a' : 'k';\r
303         this.top += 1;\r
304     }\r
305 \r
306 \r
307     /**\r
308      * Append either the value <code>true</code> or the value\r
309      * <code>false</code>.\r
310      * @param b A boolean.\r
311      * @return this\r
312      * @throws JSONException\r
313      */\r
314     public JSONWriter value(boolean b) throws JSONException {\r
315         return this.append(b ? "true" : "false");\r
316     }\r
317 \r
318     /**\r
319      * Append a double value.\r
320      * @param d A double.\r
321      * @return this\r
322      * @throws JSONException If the number is not finite.\r
323      */\r
324     public JSONWriter value(double d) throws JSONException {\r
325         return this.value(new Double(d));\r
326     }\r
327 \r
328     /**\r
329      * Append a long value.\r
330      * @param l A long.\r
331      * @return this\r
332      * @throws JSONException\r
333      */\r
334     public JSONWriter value(long l) throws JSONException {\r
335         return this.append(Long.toString(l));\r
336     }\r
337 \r
338 \r
339     /**\r
340      * Append an object value.\r
341      * @param object The object to append. It can be null, or a Boolean, Number,\r
342      *   String, JSONObject, or JSONArray, or an object that implements JSONString.\r
343      * @return this\r
344      * @throws JSONException If the value is out of sequence.\r
345      */\r
346     public JSONWriter value(Object object) throws JSONException {\r
347         return this.append(JSONObject.valueToString(object));\r
348     }\r
349 }\r