[DMAAP-48] Initial code import
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / json / JSONTokener.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.BufferedReader;\r
26 import java.io.IOException;\r
27 import java.io.InputStream;\r
28 import java.io.InputStreamReader;\r
29 import java.io.Reader;\r
30 import java.io.StringReader;\r
31 \r
32 /*\r
33 Copyright (c) 2002 JSON.org\r
34 \r
35 Permission is hereby granted, free of charge, to any person obtaining a copy\r
36 of this software and associated documentation files (the "Software"), to deal\r
37 in the Software without restriction, including without limitation the rights\r
38 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
39 copies of the Software, and to permit persons to whom the Software is\r
40 furnished to do so, subject to the following conditions:\r
41 \r
42 The above copyright notice and this permission notice shall be included in all\r
43 copies or substantial portions of the Software.\r
44 \r
45 The Software shall be used for Good, not Evil.\r
46 \r
47 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
48 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
49 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
50 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
51 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
52 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r
53 SOFTWARE.\r
54 */\r
55 \r
56 /**\r
57  * A JSONTokener takes a source string and extracts characters and tokens from\r
58  * it. It is used by the JSONObject and JSONArray constructors to parse\r
59  * JSON source strings.\r
60  * @author JSON.org\r
61  * @version 2012-02-16\r
62  */\r
63 public class JSONTokener {\r
64 \r
65     private long    character;\r
66     private boolean eof;\r
67     private long    index;\r
68     private long    line;\r
69     private char    previous;\r
70     private Reader  reader;\r
71     private boolean usePrevious;\r
72 \r
73 \r
74     /**\r
75      * Construct a JSONTokener from a Reader.\r
76      *\r
77      * @param reader     A reader.\r
78      */\r
79     public JSONTokener(Reader reader) {\r
80         this.reader = reader.markSupported()\r
81             ? reader\r
82             : new BufferedReader(reader);\r
83         this.eof = false;\r
84         this.usePrevious = false;\r
85         this.previous = 0;\r
86         this.index = 0;\r
87         this.character = 1;\r
88         this.line = 1;\r
89     }\r
90 \r
91 \r
92     /**\r
93      * Construct a JSONTokener from an InputStream.\r
94      */\r
95     public JSONTokener(InputStream inputStream) throws JSONException {\r
96         this(new InputStreamReader(inputStream));\r
97     }\r
98 \r
99 \r
100     /**\r
101      * Construct a JSONTokener from a string.\r
102      *\r
103      * @param s     A source string.\r
104      */\r
105     public JSONTokener(String s) {\r
106         this(new StringReader(s));\r
107     }\r
108 \r
109 \r
110     /**\r
111      * Back up one character. This provides a sort of lookahead capability,\r
112      * so that you can test for a digit or letter before attempting to parse\r
113      * the next number or identifier.\r
114      */\r
115     public void back() throws JSONException {\r
116         if (this.usePrevious || this.index <= 0) {\r
117             throw new JSONException("Stepping back two steps is not supported");\r
118         }\r
119         this.index -= 1;\r
120         this.character -= 1;\r
121         this.usePrevious = true;\r
122         this.eof = false;\r
123     }\r
124 \r
125 \r
126     /**\r
127      * Get the hex value of a character (base16).\r
128      * @param c A character between '0' and '9' or between 'A' and 'F' or\r
129      * between 'a' and 'f'.\r
130      * @return  An int between 0 and 15, or -1 if c was not a hex digit.\r
131      */\r
132     public static int dehexchar(char c) {\r
133         if (c >= '0' && c <= '9') {\r
134             return c - '0';\r
135         }\r
136         if (c >= 'A' && c <= 'F') {\r
137             return c - ('A' - 10);\r
138         }\r
139         if (c >= 'a' && c <= 'f') {\r
140             return c - ('a' - 10);\r
141         }\r
142         return -1;\r
143     }\r
144 \r
145     public boolean end() {\r
146         return this.eof && !this.usePrevious;\r
147     }\r
148 \r
149 \r
150     /**\r
151      * Determine if the source string still contains characters that next()\r
152      * can consume.\r
153      * @return true if not yet at the end of the source.\r
154      */\r
155     public boolean more() throws JSONException {\r
156         this.next();\r
157         if (this.end()) {\r
158             return false;\r
159         }\r
160         this.back();\r
161         return true;\r
162     }\r
163 \r
164 \r
165     /**\r
166      * Get the next character in the source string.\r
167      *\r
168      * @return The next character, or 0 if past the end of the source string.\r
169      */\r
170     public char next() throws JSONException {\r
171         int c;\r
172         if (this.usePrevious) {\r
173             this.usePrevious = false;\r
174             c = this.previous;\r
175         } else {\r
176             try {\r
177                 c = this.reader.read();\r
178             } catch (IOException exception) {\r
179                 throw new JSONException(exception);\r
180             }\r
181 \r
182             if (c <= 0) { // End of stream\r
183                 this.eof = true;\r
184                 c = 0;\r
185             }\r
186         }\r
187         this.index += 1;\r
188         if (this.previous == '\r') {\r
189             this.line += 1;\r
190             this.character = c == '\n' ? 0 : 1;\r
191         } else if (c == '\n') {\r
192             this.line += 1;\r
193             this.character = 0;\r
194         } else {\r
195             this.character += 1;\r
196         }\r
197         this.previous = (char) c;\r
198         return this.previous;\r
199     }\r
200 \r
201 \r
202     /**\r
203      * Consume the next character, and check that it matches a specified\r
204      * character.\r
205      * @param c The character to match.\r
206      * @return The character.\r
207      * @throws JSONException if the character does not match.\r
208      */\r
209     public char next(char c) throws JSONException {\r
210         char n = this.next();\r
211         if (n != c) {\r
212             throw this.syntaxError("Expected '" + c + "' and instead saw '" +\r
213                     n + "'");\r
214         }\r
215         return n;\r
216     }\r
217 \r
218 \r
219     /**\r
220      * Get the next n characters.\r
221      *\r
222      * @param n     The number of characters to take.\r
223      * @return      A string of n characters.\r
224      * @throws JSONException\r
225      *   Substring bounds error if there are not\r
226      *   n characters remaining in the source string.\r
227      */\r
228      public String next(int n) throws JSONException {\r
229          if (n == 0) {\r
230              return "";\r
231          }\r
232 \r
233          char[] chars = new char[n];\r
234          int pos = 0;\r
235 \r
236          while (pos < n) {\r
237              chars[pos] = this.next();\r
238              if (this.end()) {\r
239                  throw this.syntaxError("Substring bounds error");\r
240              }\r
241              pos += 1;\r
242          }\r
243          return new String(chars);\r
244      }\r
245 \r
246 \r
247     /**\r
248      * Get the next char in the string, skipping whitespace.\r
249      * @throws JSONException\r
250      * @return  A character, or 0 if there are no more characters.\r
251      */\r
252     public char nextClean() throws JSONException {\r
253         for (;;) {\r
254             char c = this.next();\r
255             if (c == 0 || c > ' ') {\r
256                 return c;\r
257             }\r
258         }\r
259     }\r
260 \r
261 \r
262     /**\r
263      * Return the characters up to the next close quote character.\r
264      * Backslash processing is done. The formal JSON format does not\r
265      * allow strings in single quotes, but an implementation is allowed to\r
266      * accept them.\r
267      * @param quote The quoting character, either\r
268      *      <code>"</code>&nbsp;<small>(double quote)</small> or\r
269      *      <code>'</code>&nbsp;<small>(single quote)</small>.\r
270      * @return      A String.\r
271      * @throws JSONException Unterminated string.\r
272      */\r
273     public String nextString(char quote) throws JSONException {\r
274         char c;\r
275         StringBuffer sb = new StringBuffer();\r
276         for (;;) {\r
277             c = this.next();\r
278             switch (c) {\r
279             case 0:\r
280             case '\n':\r
281             case '\r':\r
282                 throw this.syntaxError("Unterminated string");\r
283             case '\\':\r
284                 c = this.next();\r
285                 switch (c) {\r
286                 case 'b':\r
287                     sb.append('\b');\r
288                     break;\r
289                 case 't':\r
290                     sb.append('\t');\r
291                     break;\r
292                 case 'n':\r
293                     sb.append('\n');\r
294                     break;\r
295                 case 'f':\r
296                     sb.append('\f');\r
297                     break;\r
298                 case 'r':\r
299                     sb.append('\r');\r
300                     break;\r
301                 case 'u':\r
302                     sb.append((char)Integer.parseInt(this.next(4), 16));\r
303                     break;\r
304                 case '"':\r
305                 case '\'':\r
306                 case '\\':\r
307                 case '/':\r
308                     sb.append(c);\r
309                     break;\r
310                 default:\r
311                     throw this.syntaxError("Illegal escape.");\r
312                 }\r
313                 break;\r
314             default:\r
315                 if (c == quote) {\r
316                     return sb.toString();\r
317                 }\r
318                 sb.append(c);\r
319             }\r
320         }\r
321     }\r
322 \r
323 \r
324     /**\r
325      * Get the text up but not including the specified character or the\r
326      * end of line, whichever comes first.\r
327      * @param  delimiter A delimiter character.\r
328      * @return   A string.\r
329      */\r
330     public String nextTo(char delimiter) throws JSONException {\r
331         StringBuffer sb = new StringBuffer();\r
332         for (;;) {\r
333             char c = this.next();\r
334             if (c == delimiter || c == 0 || c == '\n' || c == '\r') {\r
335                 if (c != 0) {\r
336                     this.back();\r
337                 }\r
338                 return sb.toString().trim();\r
339             }\r
340             sb.append(c);\r
341         }\r
342     }\r
343 \r
344 \r
345     /**\r
346      * Get the text up but not including one of the specified delimiter\r
347      * characters or the end of line, whichever comes first.\r
348      * @param delimiters A set of delimiter characters.\r
349      * @return A string, trimmed.\r
350      */\r
351     public String nextTo(String delimiters) throws JSONException {\r
352         char c;\r
353         StringBuffer sb = new StringBuffer();\r
354         for (;;) {\r
355             c = this.next();\r
356             if (delimiters.indexOf(c) >= 0 || c == 0 ||\r
357                     c == '\n' || c == '\r') {\r
358                 if (c != 0) {\r
359                     this.back();\r
360                 }\r
361                 return sb.toString().trim();\r
362             }\r
363             sb.append(c);\r
364         }\r
365     }\r
366 \r
367 \r
368     /**\r
369      * Get the next value. The value can be a Boolean, Double, Integer,\r
370      * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.\r
371      * @throws JSONException If syntax error.\r
372      *\r
373      * @return An object.\r
374      */\r
375     public Object nextValue() throws JSONException {\r
376         char c = this.nextClean();\r
377         String string;\r
378 \r
379         switch (c) {\r
380             case '"':\r
381             case '\'':\r
382                 return this.nextString(c);\r
383             case '{':\r
384                 this.back();\r
385                 return new JSONObject(this);\r
386             case '[':\r
387                 this.back();\r
388                 return new JSONArray(this);\r
389         }\r
390 \r
391         /*\r
392          * Handle unquoted text. This could be the values true, false, or\r
393          * null, or it can be a number. An implementation (such as this one)\r
394          * is allowed to also accept non-standard forms.\r
395          *\r
396          * Accumulate characters until we reach the end of the text or a\r
397          * formatting character.\r
398          */\r
399 \r
400         StringBuffer sb = new StringBuffer();\r
401         while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {\r
402             sb.append(c);\r
403             c = this.next();\r
404         }\r
405         this.back();\r
406 \r
407         string = sb.toString().trim();\r
408         if ("".equals(string)) {\r
409             throw this.syntaxError("Missing value");\r
410         }\r
411         return JSONObject.stringToValue(string);\r
412     }\r
413 \r
414 \r
415     /**\r
416      * Skip characters until the next character is the requested character.\r
417      * If the requested character is not found, no characters are skipped.\r
418      * @param to A character to skip to.\r
419      * @return The requested character, or zero if the requested character\r
420      * is not found.\r
421      */\r
422     public char skipTo(char to) throws JSONException {\r
423         char c;\r
424         try {\r
425             long startIndex = this.index;\r
426             long startCharacter = this.character;\r
427             long startLine = this.line;\r
428             this.reader.mark(1000000);\r
429             do {\r
430                 c = this.next();\r
431                 if (c == 0) {\r
432                     this.reader.reset();\r
433                     this.index = startIndex;\r
434                     this.character = startCharacter;\r
435                     this.line = startLine;\r
436                     return c;\r
437                 }\r
438             } while (c != to);\r
439         } catch (IOException exc) {\r
440             throw new JSONException(exc);\r
441         }\r
442 \r
443         this.back();\r
444         return c;\r
445     }\r
446 \r
447 \r
448     /**\r
449      * Make a JSONException to signal a syntax error.\r
450      *\r
451      * @param message The error message.\r
452      * @return  A JSONException object, suitable for throwing\r
453      */\r
454     public JSONException syntaxError(String message) {\r
455         return new JSONException(message + this.toString());\r
456     }\r
457 \r
458 \r
459     /**\r
460      * Make a printable string of this JSONTokener.\r
461      *\r
462      * @return " at {index} [character {character} line {line}]"\r
463      */\r
464     public String toString() {\r
465         return " at " + this.index + " [character " + this.character + " line " +\r
466             this.line + "]";\r
467     }\r
468 }\r