GRAILS-1019: Allowing expressions to be used with the 'disabled' attribute for g...
[grails.git] / src / web / org / codehaus / groovy / grails / web / json / JSONTokener.java
blobab5ffe60ea67e2ba30dc17c4a103688609b21f92
1 package org.codehaus.groovy.grails.web.json;
3 import java.util.Date;
4 import java.util.regex.Matcher;
5 import java.util.regex.Pattern;
7 /*
8 Copyright (c) 2002 JSON.org
10 Permission is hereby granted, free of charge, to any person obtaining a copy
11 of this software and associated documentation files (the "Software"), to deal
12 in the Software without restriction, including without limitation the rights
13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 copies of the Software, and to permit persons to whom the Software is
15 furnished to do so, subject to the following conditions:
17 The above copyright notice and this permission notice shall be included in all
18 copies or substantial portions of the Software.
20 The Software shall be used for Good, not Evil.
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
31 /**
32 * A JSONTokener takes a source string and extracts characters and tokens from
33 * it. It is used by the JSONObject and JSONArray constructors to parse
34 * JSON source strings.
36 * @author JSON.org
37 * @version 2
39 public class JSONTokener {
41 /**
42 * The index of the next character.
44 private int myIndex;
47 /**
48 * The source string being tokenized.
50 private String mySource;
53 /**
54 * Construct a JSONTokener from a string.
56 * @param s A source string.
58 public JSONTokener(String s) {
59 this.myIndex = 0;
60 this.mySource = s;
64 /**
65 * Back up one character. This provides a sort of lookahead capability,
66 * so that you can test for a digit or letter before attempting to parse
67 * the next number or identifier.
69 public void back() {
70 if (this.myIndex > 0) {
71 this.myIndex -= 1;
76 /**
77 * Get the hex value of a character (base16).
79 * @param c A character between '0' and '9' or between 'A' and 'F' or
80 * between 'a' and 'f'.
81 * @return An int between 0 and 15, or -1 if c was not a hex digit.
83 public static int dehexchar(char c) {
84 if (c >= '0' && c <= '9') {
85 return c - '0';
87 if (c >= 'A' && c <= 'F') {
88 return c - ('A' - 10);
90 if (c >= 'a' && c <= 'f') {
91 return c - ('a' - 10);
93 return -1;
97 /**
98 * Determine if the source string still contains characters that next()
99 * can consume.
101 * @return true if not yet at the end of the source.
103 public boolean more() {
104 return this.myIndex < this.mySource.length();
109 * Get the next character in the source string.
111 * @return The next character, or 0 if past the end of the source string.
113 public char next() {
114 if (more()) {
115 char c = this.mySource.charAt(this.myIndex);
116 this.myIndex += 1;
117 return c;
119 return 0;
124 * Consume the next character, and check that it matches a specified
125 * character.
127 * @param c The character to match.
128 * @return The character.
129 * @throws JSONException if the character does not match.
131 public char next(char c) throws JSONException {
132 char n = next();
133 if (n != c) {
134 throw syntaxError("Expected '" + c + "' and instead saw '" +
135 n + "'.");
137 return n;
142 * Get the next n characters.
144 * @param n The number of characters to take.
145 * @return A string of n characters.
146 * @throws JSONException Substring bounds error if there are not
147 * n characters remaining in the source string.
149 public String next(int n) throws JSONException {
150 int i = this.myIndex;
151 int j = i + n;
152 if (j >= this.mySource.length()) {
153 throw syntaxError("Substring bounds error");
155 this.myIndex += n;
156 return this.mySource.substring(i, j);
161 * Get the next char in the string, skipping whitespace
162 * and comments (slashslash, slashstar, and hash).
164 * @return A character, or 0 if there are no more characters.
165 * @throws JSONException
167 public char nextClean() throws JSONException {
168 for (; ;) {
169 char c = next();
170 if (c == '/') {
171 switch (next()) {
172 case '/':
173 do {
174 c = next();
175 } while (c != '\n' && c != '\r' && c != 0);
176 break;
177 case '*':
178 for (; ;) {
179 c = next();
180 if (c == 0) {
181 throw syntaxError("Unclosed comment.");
183 if (c == '*') {
184 if (next() == '/') {
185 break;
187 back();
190 break;
191 default:
192 back();
193 return '/';
195 } else if (c == '#') {
196 do {
197 c = next();
198 } while (c != '\n' && c != '\r' && c != 0);
199 } else if (c == 0 || c > ' ') {
200 return c;
207 * Return the characters up to the next close quote character.
208 * Backslash processing is done. The formal JSON format does not
209 * allow strings in single quotes, but an implementation is allowed to
210 * accept them.
212 * @param quote The quoting character, either
213 * <code>"</code>&nbsp;<small>(double quote)</small> or
214 * <code>'</code>&nbsp;<small>(single quote)</small>.
215 * @return A String.
216 * @throws JSONException Unterminated string.
218 public String nextString(char quote) throws JSONException {
219 char c;
220 StringBuffer sb = new StringBuffer();
221 for (; ;) {
222 c = next();
223 switch (c) {
224 case 0:
225 case '\n':
226 case '\r':
227 throw syntaxError("Unterminated string");
228 case '\\':
229 c = next();
230 switch (c) {
231 case 'b':
232 sb.append('\b');
233 break;
234 case 't':
235 sb.append('\t');
236 break;
237 case 'n':
238 sb.append('\n');
239 break;
240 case 'f':
241 sb.append('\f');
242 break;
243 case 'r':
244 sb.append('\r');
245 break;
246 case 'u':
247 sb.append((char) Integer.parseInt(next(4), 16));
248 break;
249 case 'x':
250 sb.append((char) Integer.parseInt(next(2), 16));
251 break;
252 default:
253 sb.append(c);
255 break;
256 default:
257 if (c == quote) {
258 return sb.toString();
260 sb.append(c);
267 * Get the text up but not including the specified character or the
268 * end of line, whichever comes first.
270 * @param d A delimiter character.
271 * @return A string.
273 public String nextTo(char d) {
274 StringBuffer sb = new StringBuffer();
275 for (; ;) {
276 char c = next();
277 if (c == d || c == 0 || c == '\n' || c == '\r') {
278 if (c != 0) {
279 back();
281 return sb.toString().trim();
283 sb.append(c);
289 * Get the text up but not including one of the specified delimeter
290 * characters or the end of line, whichever comes first.
292 * @param delimiters A set of delimiter characters.
293 * @return A string, trimmed.
295 public String nextTo(String delimiters) {
296 char c;
297 StringBuffer sb = new StringBuffer();
298 for (; ;) {
299 c = next();
300 if (delimiters.indexOf(c) >= 0 || c == 0 ||
301 c == '\n' || c == '\r') {
302 if (c != 0) {
303 back();
305 return sb.toString().trim();
307 sb.append(c);
313 * Get the next value. The value can be a Boolean, Double, Integer,
314 * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
316 * @return An object.
317 * @throws JSONException If syntax error.
319 public Object nextValue() throws JSONException {
320 char c = nextClean();
321 String s;
323 switch (c) {
324 case '"':
325 case '\'':
326 return nextString(c);
327 case '{':
328 back();
329 return new JSONObject(this);
330 case '[':
331 back();
332 return new JSONArray(this);
336 * Handle unquoted text. This could be the values true, false, or
337 * null, or it can be a number. An implementation (such as this one)
338 * is allowed to also accept non-standard forms.
340 * Accumulate characters until we reach the end of the text or a
341 * formatting character.
344 StringBuffer sb = new StringBuffer();
345 char b = c;
346 while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
347 sb.append(c);
348 c = next();
350 back();
353 * If it is true, false, or null, return the proper value.
356 s = sb.toString().trim();
357 if (s.equals("")) {
358 throw syntaxError("Missing value.");
360 if (s.equalsIgnoreCase("true")) {
361 return Boolean.TRUE;
363 if (s.equalsIgnoreCase("false")) {
364 return Boolean.FALSE;
366 if (s.equalsIgnoreCase("null")) {
367 return JSONObject.NULL;
370 if (s.startsWith("new Date(")) {
371 try {
372 Matcher matcher = Pattern.compile("^\\s*new\\s+Date\\(\\s*(\\d+)\\s*\\)\\s*$").matcher(s);
373 if (matcher.find()) {
374 long time = Long.parseLong(matcher.group(1));
375 return new Date(time);
377 } catch (Exception e) {
383 * If it might be a number, try converting it. We support the 0- and 0x-
384 * conventions. If a number cannot be produced, then the value will just
385 * be a string. Note that the 0-, 0x-, plus, and implied string
386 * conventions are non-standard. A JSON parser is free to accept
387 * non-JSON forms as long as it accepts all correct JSON forms.
390 if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
391 if (b == '0') {
392 if (s.length() > 2 &&
393 (s.charAt(1) == 'x' || s.charAt(1) == 'X')) {
394 try {
395 return new Integer(Integer.parseInt(s.substring(2),
396 16));
397 } catch (Exception e) {
398 /* Ignore the error */
400 } else {
401 try {
402 return new Integer(Integer.parseInt(s, 8));
403 } catch (Exception e) {
404 /* Ignore the error */
408 try {
409 return new Integer(s);
410 } catch (Exception e) {
411 try {
412 return new Long(s);
413 } catch (Exception f) {
414 try {
415 return new Double(s);
416 } catch (Exception g) {
417 return s;
422 return s;
427 * Skip characters until the next character is the requested character.
428 * If the requested character is not found, no characters are skipped.
430 * @param to A character to skip to.
431 * @return The requested character, or zero if the requested character
432 * is not found.
434 public char skipTo(char to) {
435 char c;
436 int index = this.myIndex;
437 do {
438 c = next();
439 if (c == 0) {
440 this.myIndex = index;
441 return c;
443 } while (c != to);
444 back();
445 return c;
450 * Skip characters until past the requested string.
451 * If it is not found, we are left at the end of the source.
453 * @param to A string to skip past.
455 public void skipPast(String to) {
456 this.myIndex = this.mySource.indexOf(to, this.myIndex);
457 if (this.myIndex < 0) {
458 this.myIndex = this.mySource.length();
459 } else {
460 this.myIndex += to.length();
466 * Make a JSONException to signal a syntax error.
468 * @param message The error message.
469 * @return A JSONException object, suitable for throwing
471 public JSONException syntaxError(String message) {
472 return new JSONException(message + toString());
477 * Make a printable string of this JSONTokener.
479 * @return " at character [this.myIndex] of [this.mySource]"
481 public String toString() {
482 return " at character " + this.myIndex + " of " + this.mySource;