a utility for generating JSON from SQL queries using JDBC
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

634 lines
18 KiB

12 years ago
  1. /*
  2. * Copyright (C) 2010 Google Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.google.gson.stream;
  17. import java.io.Closeable;
  18. import java.io.Flushable;
  19. import java.io.IOException;
  20. import java.io.Writer;
  21. import static com.google.gson.stream.JsonScope.DANGLING_NAME;
  22. import static com.google.gson.stream.JsonScope.EMPTY_ARRAY;
  23. import static com.google.gson.stream.JsonScope.EMPTY_DOCUMENT;
  24. import static com.google.gson.stream.JsonScope.EMPTY_OBJECT;
  25. import static com.google.gson.stream.JsonScope.NONEMPTY_ARRAY;
  26. import static com.google.gson.stream.JsonScope.NONEMPTY_DOCUMENT;
  27. import static com.google.gson.stream.JsonScope.NONEMPTY_OBJECT;
  28. /**
  29. * Writes a JSON (<a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>)
  30. * encoded value to a stream, one token at a time. The stream includes both
  31. * literal values (strings, numbers, booleans and nulls) as well as the begin
  32. * and end delimiters of objects and arrays.
  33. *
  34. * <h3>Encoding JSON</h3>
  35. * To encode your data as JSON, create a new {@code JsonWriter}. Each JSON
  36. * document must contain one top-level array or object. Call methods on the
  37. * writer as you walk the structure's contents, nesting arrays and objects as
  38. * necessary:
  39. * <ul>
  40. * <li>To write <strong>arrays</strong>, first call {@link #beginArray()}.
  41. * Write each of the array's elements with the appropriate {@link #value}
  42. * methods or by nesting other arrays and objects. Finally close the array
  43. * using {@link #endArray()}.
  44. * <li>To write <strong>objects</strong>, first call {@link #beginObject()}.
  45. * Write each of the object's properties by alternating calls to
  46. * {@link #name} with the property's value. Write property values with the
  47. * appropriate {@link #value} method or by nesting other objects or arrays.
  48. * Finally close the object using {@link #endObject()}.
  49. * </ul>
  50. *
  51. * <h3>Example</h3>
  52. * Suppose we'd like to encode a stream of messages such as the following: <pre> {@code
  53. * [
  54. * {
  55. * "id": 912345678901,
  56. * "text": "How do I stream JSON in Java?",
  57. * "geo": null,
  58. * "user": {
  59. * "name": "json_newb",
  60. * "followers_count": 41
  61. * }
  62. * },
  63. * {
  64. * "id": 912345678902,
  65. * "text": "@json_newb just use JsonWriter!",
  66. * "geo": [50.454722, -104.606667],
  67. * "user": {
  68. * "name": "jesse",
  69. * "followers_count": 2
  70. * }
  71. * }
  72. * ]}</pre>
  73. * This code encodes the above structure: <pre> {@code
  74. * public void writeJsonStream(OutputStream out, List<Message> messages) throws IOException {
  75. * JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
  76. * writer.setIndentSpaces(4);
  77. * writeMessagesArray(writer, messages);
  78. * writer.close();
  79. * }
  80. *
  81. * public void writeMessagesArray(JsonWriter writer, List<Message> messages) throws IOException {
  82. * writer.beginArray();
  83. * for (Message message : messages) {
  84. * writeMessage(writer, message);
  85. * }
  86. * writer.endArray();
  87. * }
  88. *
  89. * public void writeMessage(JsonWriter writer, Message message) throws IOException {
  90. * writer.beginObject();
  91. * writer.name("id").value(message.getId());
  92. * writer.name("text").value(message.getText());
  93. * if (message.getGeo() != null) {
  94. * writer.name("geo");
  95. * writeDoublesArray(writer, message.getGeo());
  96. * } else {
  97. * writer.name("geo").nullValue();
  98. * }
  99. * writer.name("user");
  100. * writeUser(writer, message.getUser());
  101. * writer.endObject();
  102. * }
  103. *
  104. * public void writeUser(JsonWriter writer, User user) throws IOException {
  105. * writer.beginObject();
  106. * writer.name("name").value(user.getName());
  107. * writer.name("followers_count").value(user.getFollowersCount());
  108. * writer.endObject();
  109. * }
  110. *
  111. * public void writeDoublesArray(JsonWriter writer, List<Double> doubles) throws IOException {
  112. * writer.beginArray();
  113. * for (Double value : doubles) {
  114. * writer.value(value);
  115. * }
  116. * writer.endArray();
  117. * }}</pre>
  118. *
  119. * <p>Each {@code JsonWriter} may be used to write a single JSON stream.
  120. * Instances of this class are not thread safe. Calls that would result in a
  121. * malformed JSON string will fail with an {@link IllegalStateException}.
  122. *
  123. * @author Jesse Wilson
  124. * @since 1.6
  125. */
  126. public class JsonWriter implements Closeable, Flushable {
  127. /*
  128. * From RFC 4627, "All Unicode characters may be placed within the
  129. * quotation marks except for the characters that must be escaped:
  130. * quotation mark, reverse solidus, and the control characters
  131. * (U+0000 through U+001F)."
  132. *
  133. * We also escape '\u2028' and '\u2029', which JavaScript interprets as
  134. * newline characters. This prevents eval() from failing with a syntax
  135. * error. http://code.google.com/p/google-gson/issues/detail?id=341
  136. */
  137. private static final String[] REPLACEMENT_CHARS;
  138. private static final String[] HTML_SAFE_REPLACEMENT_CHARS;
  139. static {
  140. REPLACEMENT_CHARS = new String[128];
  141. for (int i = 0; i <= 0x1f; i++) {
  142. REPLACEMENT_CHARS[i] = String.format("\\u%04x", (int) i);
  143. }
  144. REPLACEMENT_CHARS['"'] = "\\\"";
  145. REPLACEMENT_CHARS['\\'] = "\\\\";
  146. REPLACEMENT_CHARS['\t'] = "\\t";
  147. REPLACEMENT_CHARS['\b'] = "\\b";
  148. REPLACEMENT_CHARS['\n'] = "\\n";
  149. REPLACEMENT_CHARS['\r'] = "\\r";
  150. REPLACEMENT_CHARS['\f'] = "\\f";
  151. HTML_SAFE_REPLACEMENT_CHARS = REPLACEMENT_CHARS.clone();
  152. HTML_SAFE_REPLACEMENT_CHARS['<'] = "\\u003c";
  153. HTML_SAFE_REPLACEMENT_CHARS['>'] = "\\u003e";
  154. HTML_SAFE_REPLACEMENT_CHARS['&'] = "\\u0026";
  155. HTML_SAFE_REPLACEMENT_CHARS['='] = "\\u003d";
  156. HTML_SAFE_REPLACEMENT_CHARS['\''] = "\\u0027";
  157. }
  158. /** The output data, containing at most one top-level array or object. */
  159. private final Writer out;
  160. private int[] stack = new int[32];
  161. private int stackSize = 0;
  162. {
  163. push(EMPTY_DOCUMENT);
  164. }
  165. /**
  166. * A string containing a full set of spaces for a single level of
  167. * indentation, or null for no pretty printing.
  168. */
  169. private String indent;
  170. /**
  171. * The name/value separator; either ":" or ": ".
  172. */
  173. private String separator = ":";
  174. private boolean lenient;
  175. private boolean htmlSafe;
  176. private String deferredName;
  177. private boolean serializeNulls = true;
  178. /**
  179. * Creates a new instance that writes a JSON-encoded stream to {@code out}.
  180. * For best performance, ensure {@link Writer} is buffered; wrapping in
  181. * {@link java.io.BufferedWriter BufferedWriter} if necessary.
  182. */
  183. public JsonWriter(Writer out) {
  184. if (out == null) {
  185. throw new NullPointerException("out == null");
  186. }
  187. this.out = out;
  188. }
  189. /**
  190. * Sets the indentation string to be repeated for each level of indentation
  191. * in the encoded document. If {@code indent.isEmpty()} the encoded document
  192. * will be compact. Otherwise the encoded document will be more
  193. * human-readable.
  194. *
  195. * @param indent a string containing only whitespace.
  196. */
  197. public final void setIndent(String indent) {
  198. if (indent.length() == 0) {
  199. this.indent = null;
  200. this.separator = ":";
  201. } else {
  202. this.indent = indent;
  203. this.separator = ": ";
  204. }
  205. }
  206. /**
  207. * Configure this writer to relax its syntax rules. By default, this writer
  208. * only emits well-formed JSON as specified by <a
  209. * href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>. Setting the writer
  210. * to lenient permits the following:
  211. * <ul>
  212. * <li>Top-level values of any type. With strict writing, the top-level
  213. * value must be an object or an array.
  214. * <li>Numbers may be {@link Double#isNaN() NaNs} or {@link
  215. * Double#isInfinite() infinities}.
  216. * </ul>
  217. */
  218. public final void setLenient(boolean lenient) {
  219. this.lenient = lenient;
  220. }
  221. /**
  222. * Returns true if this writer has relaxed syntax rules.
  223. */
  224. public boolean isLenient() {
  225. return lenient;
  226. }
  227. /**
  228. * Configure this writer to emit JSON that's safe for direct inclusion in HTML
  229. * and XML documents. This escapes the HTML characters {@code <}, {@code >},
  230. * {@code &} and {@code =} before writing them to the stream. Without this
  231. * setting, your XML/HTML encoder should replace these characters with the
  232. * corresponding escape sequences.
  233. */
  234. public final void setHtmlSafe(boolean htmlSafe) {
  235. this.htmlSafe = htmlSafe;
  236. }
  237. /**
  238. * Returns true if this writer writes JSON that's safe for inclusion in HTML
  239. * and XML documents.
  240. */
  241. public final boolean isHtmlSafe() {
  242. return htmlSafe;
  243. }
  244. /**
  245. * Sets whether object members are serialized when their value is null.
  246. * This has no impact on array elements. The default is true.
  247. */
  248. public final void setSerializeNulls(boolean serializeNulls) {
  249. this.serializeNulls = serializeNulls;
  250. }
  251. /**
  252. * Returns true if object members are serialized when their value is null.
  253. * This has no impact on array elements. The default is true.
  254. */
  255. public final boolean getSerializeNulls() {
  256. return serializeNulls;
  257. }
  258. /**
  259. * Begins encoding a new array. Each call to this method must be paired with
  260. * a call to {@link #endArray}.
  261. *
  262. * @return this writer.
  263. */
  264. public JsonWriter beginArray() throws IOException {
  265. writeDeferredName();
  266. return open(EMPTY_ARRAY, "[");
  267. }
  268. /**
  269. * Ends encoding the current array.
  270. *
  271. * @return this writer.
  272. */
  273. public JsonWriter endArray() throws IOException {
  274. return close(EMPTY_ARRAY, NONEMPTY_ARRAY, "]");
  275. }
  276. /**
  277. * Begins encoding a new object. Each call to this method must be paired
  278. * with a call to {@link #endObject}.
  279. *
  280. * @return this writer.
  281. */
  282. public JsonWriter beginObject() throws IOException {
  283. writeDeferredName();
  284. return open(EMPTY_OBJECT, "{");
  285. }
  286. /**
  287. * Ends encoding the current object.
  288. *
  289. * @return this writer.
  290. */
  291. public JsonWriter endObject() throws IOException {
  292. return close(EMPTY_OBJECT, NONEMPTY_OBJECT, "}");
  293. }
  294. /**
  295. * Enters a new scope by appending any necessary whitespace and the given
  296. * bracket.
  297. */
  298. private JsonWriter open(int empty, String openBracket) throws IOException {
  299. beforeValue(true);
  300. push(empty);
  301. out.write(openBracket);
  302. return this;
  303. }
  304. /**
  305. * Closes the current scope by appending any necessary whitespace and the
  306. * given bracket.
  307. */
  308. private JsonWriter close(int empty, int nonempty, String closeBracket)
  309. throws IOException {
  310. int context = peek();
  311. if (context != nonempty && context != empty) {
  312. throw new IllegalStateException("Nesting problem.");
  313. }
  314. if (deferredName != null) {
  315. throw new IllegalStateException("Dangling name: " + deferredName);
  316. }
  317. stackSize--;
  318. if (context == nonempty) {
  319. newline();
  320. }
  321. out.write(closeBracket);
  322. return this;
  323. }
  324. private void push(int newTop) {
  325. if (stackSize == stack.length) {
  326. int[] newStack = new int[stackSize * 2];
  327. System.arraycopy(stack, 0, newStack, 0, stackSize);
  328. stack = newStack;
  329. }
  330. stack[stackSize++] = newTop;
  331. }
  332. /**
  333. * Returns the value on the top of the stack.
  334. */
  335. private int peek() {
  336. if (stackSize == 0) {
  337. throw new IllegalStateException("JsonWriter is closed.");
  338. }
  339. return stack[stackSize - 1];
  340. }
  341. /**
  342. * Replace the value on the top of the stack with the given value.
  343. */
  344. private void replaceTop(int topOfStack) {
  345. stack[stackSize - 1] = topOfStack;
  346. }
  347. /**
  348. * Encodes the property name.
  349. *
  350. * @param name the name of the forthcoming value. May not be null.
  351. * @return this writer.
  352. */
  353. public JsonWriter name(String name) throws IOException {
  354. if (name == null) {
  355. throw new NullPointerException("name == null");
  356. }
  357. if (deferredName != null) {
  358. throw new IllegalStateException();
  359. }
  360. if (stackSize == 0) {
  361. throw new IllegalStateException("JsonWriter is closed.");
  362. }
  363. deferredName = name;
  364. return this;
  365. }
  366. private void writeDeferredName() throws IOException {
  367. if (deferredName != null) {
  368. beforeName();
  369. string(deferredName);
  370. deferredName = null;
  371. }
  372. }
  373. /**
  374. * Encodes {@code value}.
  375. *
  376. * @param value the literal string value, or null to encode a null literal.
  377. * @return this writer.
  378. */
  379. public JsonWriter value(String value) throws IOException {
  380. if (value == null) {
  381. return nullValue();
  382. }
  383. writeDeferredName();
  384. beforeValue(false);
  385. string(value);
  386. return this;
  387. }
  388. /**
  389. * Encodes {@code null}.
  390. *
  391. * @return this writer.
  392. */
  393. public JsonWriter nullValue() throws IOException {
  394. if (deferredName != null) {
  395. if (serializeNulls) {
  396. writeDeferredName();
  397. } else {
  398. deferredName = null;
  399. return this; // skip the name and the value
  400. }
  401. }
  402. beforeValue(false);
  403. out.write("null");
  404. return this;
  405. }
  406. /**
  407. * Encodes {@code value}.
  408. *
  409. * @return this writer.
  410. */
  411. public JsonWriter value(boolean value) throws IOException {
  412. writeDeferredName();
  413. beforeValue(false);
  414. out.write(value ? "true" : "false");
  415. return this;
  416. }
  417. /**
  418. * Encodes {@code value}.
  419. *
  420. * @param value a finite value. May not be {@link Double#isNaN() NaNs} or
  421. * {@link Double#isInfinite() infinities}.
  422. * @return this writer.
  423. */
  424. public JsonWriter value(double value) throws IOException {
  425. if (Double.isNaN(value) || Double.isInfinite(value)) {
  426. throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
  427. }
  428. writeDeferredName();
  429. beforeValue(false);
  430. out.append(Double.toString(value));
  431. return this;
  432. }
  433. /**
  434. * Encodes {@code value}.
  435. *
  436. * @return this writer.
  437. */
  438. public JsonWriter value(long value) throws IOException {
  439. writeDeferredName();
  440. beforeValue(false);
  441. out.write(Long.toString(value));
  442. return this;
  443. }
  444. /**
  445. * Encodes {@code value}.
  446. *
  447. * @param value a finite value. May not be {@link Double#isNaN() NaNs} or
  448. * {@link Double#isInfinite() infinities}.
  449. * @return this writer.
  450. */
  451. public JsonWriter value(Number value) throws IOException {
  452. if (value == null) {
  453. return nullValue();
  454. }
  455. writeDeferredName();
  456. String string = value.toString();
  457. if (!lenient
  458. && (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN"))) {
  459. throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
  460. }
  461. beforeValue(false);
  462. out.append(string);
  463. return this;
  464. }
  465. /**
  466. * Ensures all buffered data is written to the underlying {@link Writer}
  467. * and flushes that writer.
  468. */
  469. public void flush() throws IOException {
  470. if (stackSize == 0) {
  471. throw new IllegalStateException("JsonWriter is closed.");
  472. }
  473. out.flush();
  474. }
  475. /**
  476. * Flushes and closes this writer and the underlying {@link Writer}.
  477. *
  478. * @throws IOException if the JSON document is incomplete.
  479. */
  480. public void close() throws IOException {
  481. out.close();
  482. int size = stackSize;
  483. if (size > 1 || size == 1 && stack[size - 1] != NONEMPTY_DOCUMENT) {
  484. throw new IOException("Incomplete document");
  485. }
  486. stackSize = 0;
  487. }
  488. private void string(String value) throws IOException {
  489. String[] replacements = htmlSafe ? HTML_SAFE_REPLACEMENT_CHARS : REPLACEMENT_CHARS;
  490. out.write("\"");
  491. int last = 0;
  492. int length = value.length();
  493. for (int i = 0; i < length; i++) {
  494. char c = value.charAt(i);
  495. String replacement;
  496. if (c < 128) {
  497. replacement = replacements[c];
  498. if (replacement == null) {
  499. continue;
  500. }
  501. } else if (c == '\u2028') {
  502. replacement = "\\u2028";
  503. } else if (c == '\u2029') {
  504. replacement = "\\u2029";
  505. } else {
  506. continue;
  507. }
  508. if (last < i) {
  509. out.write(value, last, i - last);
  510. }
  511. out.write(replacement);
  512. last = i + 1;
  513. }
  514. if (last < length) {
  515. out.write(value, last, length - last);
  516. }
  517. out.write("\"");
  518. }
  519. private void newline() throws IOException {
  520. if (indent == null) {
  521. return;
  522. }
  523. out.write("\n");
  524. for (int i = 1, size = stackSize; i < size; i++) {
  525. out.write(indent);
  526. }
  527. }
  528. /**
  529. * Inserts any necessary separators and whitespace before a name. Also
  530. * adjusts the stack to expect the name's value.
  531. */
  532. private void beforeName() throws IOException {
  533. int context = peek();
  534. if (context == NONEMPTY_OBJECT) { // first in object
  535. out.write(',');
  536. } else if (context != EMPTY_OBJECT) { // not in an object!
  537. throw new IllegalStateException("Nesting problem.");
  538. }
  539. newline();
  540. replaceTop(DANGLING_NAME);
  541. }
  542. /**
  543. * Inserts any necessary separators and whitespace before a literal value,
  544. * inline array, or inline object. Also adjusts the stack to expect either a
  545. * closing bracket or another element.
  546. *
  547. * @param root true if the value is a new array or object, the two values
  548. * permitted as top-level elements.
  549. */
  550. @SuppressWarnings("fallthrough")
  551. private void beforeValue(boolean root) throws IOException {
  552. switch (peek()) {
  553. case NONEMPTY_DOCUMENT:
  554. if (!lenient) {
  555. throw new IllegalStateException(
  556. "JSON must have only one top-level value.");
  557. }
  558. // fall-through
  559. case EMPTY_DOCUMENT: // first in document
  560. if (!lenient && !root) {
  561. throw new IllegalStateException(
  562. "JSON must start with an array or an object.");
  563. }
  564. replaceTop(NONEMPTY_DOCUMENT);
  565. break;
  566. case EMPTY_ARRAY: // first in array
  567. replaceTop(NONEMPTY_ARRAY);
  568. newline();
  569. break;
  570. case NONEMPTY_ARRAY: // another in array
  571. out.append(',');
  572. newline();
  573. break;
  574. case DANGLING_NAME: // value for name
  575. out.append(separator);
  576. replaceTop(NONEMPTY_OBJECT);
  577. break;
  578. default:
  579. throw new IllegalStateException("Nesting problem.");
  580. }
  581. }
  582. }