1 package org.codehaus.groovy.grails.web.json; 2 3 import java.util.Date; 4 import java.util.regex.Matcher; 5 import java.util.regex.Pattern; 6 7 /* 8 Copyright (c) 2002 JSON.org 9 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: 16 17 The above copyright notice and this permission notice shall be included in all 18 copies or substantial portions of the Software. 19 20 The Software shall be used for Good, not Evil. 21 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. 29 */ 30 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. 35 * 36 * @author JSON.org 37 * @version 2 38 */ 39 public class JSONTokener { 40 41 /** 42 * The index of the next character. 43 */ 44 private int myIndex; 45 46 47 /** 48 * The source string being tokenized. 49 */ 50 private String mySource; 51 52 53 /** 54 * Construct a JSONTokener from a string. 55 * 56 * @param s A source string. 57 */ JSONTokener(String s)58 public JSONTokener(String s) { 59 this.myIndex = 0; 60 this.mySource = s; 61 } 62 63 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. 68 */ back()69 public void back() { 70 if (this.myIndex > 0) { 71 this.myIndex -= 1; 72 } 73 } 74 75 76 /** 77 * Get the hex value of a character (base16). 78 * 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. 82 */ dehexchar(char c)83 public static int dehexchar(char c) { 84 if (c >= '0' && c <= '9') { 85 return c - '0'; 86 } 87 if (c >= 'A' && c <= 'F') { 88 return c - ('A' - 10); 89 } 90 if (c >= 'a' && c <= 'f') { 91 return c - ('a' - 10); 92 } 93 return -1; 94 } 95 96 97 /** 98 * Determine if the source string still contains characters that next() 99 * can consume. 100 * 101 * @return true if not yet at the end of the source. 102 */ more()103 public boolean more() { 104 return this.myIndex < this.mySource.length(); 105 } 106 107 108 /** 109 * Get the next character in the source string. 110 * 111 * @return The next character, or 0 if past the end of the source string. 112 */ next()113 public char next() { 114 if (more()) { 115 char c = this.mySource.charAt(this.myIndex); 116 this.myIndex += 1; 117 return c; 118 } 119 return 0; 120 } 121 122 123 /** 124 * Consume the next character, and check that it matches a specified 125 * character. 126 * 127 * @param c The character to match. 128 * @return The character. 129 * @throws JSONException if the character does not match. 130 */ next(char c)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 + "'."); 136 } 137 return n; 138 } 139 140 141 /** 142 * Get the next n characters. 143 * 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. 148 */ next(int n)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"); 154 } 155 this.myIndex += n; 156 return this.mySource.substring(i, j); 157 } 158 159 160 /** 161 * Get the next char in the string, skipping whitespace 162 * and comments (slashslash, slashstar, and hash). 163 * 164 * @return A character, or 0 if there are no more characters. 165 * @throws JSONException 166 */ nextClean()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."); 182 } 183 if (c == '*') { 184 if (next() == '/') { 185 break; 186 } 187 back(); 188 } 189 } 190 break; 191 default: 192 back(); 193 return '/'; 194 } 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; 201 } 202 } 203 } 204 205 206 /** 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. 211 * 212 * @param quote The quoting character, either 213 * <code>"</code> <small>(double quote)</small> or 214 * <code>'</code> <small>(single quote)</small>. 215 * @return A String. 216 * @throws JSONException Unterminated string. 217 */ nextString(char quote)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); 254 } 255 break; 256 default: 257 if (c == quote) { 258 return sb.toString(); 259 } 260 sb.append(c); 261 } 262 } 263 } 264 265 266 /** 267 * Get the text up but not including the specified character or the 268 * end of line, whichever comes first. 269 * 270 * @param d A delimiter character. 271 * @return A string. 272 */ nextTo(char d)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(); 280 } 281 return sb.toString().trim(); 282 } 283 sb.append(c); 284 } 285 } 286 287 288 /** 289 * Get the text up but not including one of the specified delimeter 290 * characters or the end of line, whichever comes first. 291 * 292 * @param delimiters A set of delimiter characters. 293 * @return A string, trimmed. 294 */ nextTo(String delimiters)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(); 304 } 305 return sb.toString().trim(); 306 } 307 sb.append(c); 308 } 309 } 310 311 312 /** 313 * Get the next value. The value can be a Boolean, Double, Integer, 314 * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. 315 * 316 * @return An object. 317 * @throws JSONException If syntax error. 318 */ nextValue()319 public Object nextValue() throws JSONException { 320 char c = nextClean(); 321 String s; 322 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); 333 } 334 335 /* 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. 339 * 340 * Accumulate characters until we reach the end of the text or a 341 * formatting character. 342 */ 343 344 StringBuffer sb = new StringBuffer(); 345 char b = c; 346 while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { 347 sb.append(c); 348 c = next(); 349 } 350 back(); 351 352 /* 353 * If it is true, false, or null, return the proper value. 354 */ 355 356 s = sb.toString().trim(); 357 if (s.equals("")) { 358 throw syntaxError("Missing value."); 359 } 360 if (s.equalsIgnoreCase("true")) { 361 return Boolean.TRUE; 362 } 363 if (s.equalsIgnoreCase("false")) { 364 return Boolean.FALSE; 365 } 366 if (s.equalsIgnoreCase("null")) { 367 return JSONObject.NULL; 368 } 369 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); 376 } 377 } catch (Exception e) { 378 // ignored 379 } 380 381 } 382 383 /* 384 * If it might be a number, try converting it. We support the 0- and 0x- 385 * conventions. If a number cannot be produced, then the value will just 386 * be a string. Note that the 0-, 0x-, plus, and implied string 387 * conventions are non-standard. A JSON parser is free to accept 388 * non-JSON forms as long as it accepts all correct JSON forms. 389 */ 390 391 if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { 392 if (b == '0') { 393 if (s.length() > 2 && 394 (s.charAt(1) == 'x' || s.charAt(1) == 'X')) { 395 try { 396 return new Integer(Integer.parseInt(s.substring(2), 397 16)); 398 } catch (Exception e) { 399 /* Ignore the error */ 400 } 401 } else { 402 try { 403 return new Integer(Integer.parseInt(s, 8)); 404 } catch (Exception e) { 405 /* Ignore the error */ 406 } 407 } 408 } 409 try { 410 return new Integer(s); 411 } catch (Exception e) { 412 try { 413 return new Long(s); 414 } catch (Exception f) { 415 try { 416 return new Double(s); 417 } catch (Exception g) { 418 return s; 419 } 420 } 421 } 422 } 423 return s; 424 } 425 426 427 /** 428 * Skip characters until the next character is the requested character. 429 * If the requested character is not found, no characters are skipped. 430 * 431 * @param to A character to skip to. 432 * @return The requested character, or zero if the requested character 433 * is not found. 434 */ skipTo(char to)435 public char skipTo(char to) { 436 char c; 437 int index = this.myIndex; 438 do { 439 c = next(); 440 if (c == 0) { 441 this.myIndex = index; 442 return c; 443 } 444 } while (c != to); 445 back(); 446 return c; 447 } 448 449 450 /** 451 * Skip characters until past the requested string. 452 * If it is not found, we are left at the end of the source. 453 * 454 * @param to A string to skip past. 455 */ skipPast(String to)456 public void skipPast(String to) { 457 this.myIndex = this.mySource.indexOf(to, this.myIndex); 458 if (this.myIndex < 0) { 459 this.myIndex = this.mySource.length(); 460 } else { 461 this.myIndex += to.length(); 462 } 463 } 464 465 466 /** 467 * Make a JSONException to signal a syntax error. 468 * 469 * @param message The error message. 470 * @return A JSONException object, suitable for throwing 471 */ syntaxError(String message)472 public JSONException syntaxError(String message) { 473 return new JSONException(message + toString()); 474 } 475 476 477 /** 478 * Make a printable string of this JSONTokener. 479 * 480 * @return " at character [this.myIndex] of [this.mySource]" 481 */ 482 @Override toString()483 public String toString() { 484 return " at character " + this.myIndex + " of " + this.mySource; 485 } 486 }