Debian Codegraph @

jetty-util-ajax/src/main/java/org/eclipse/jetty/util/ajax/AsyncJSON.java

raw
1 //
2 // ========================================================================
3 // Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
8 //
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
11 //
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
14 //
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
17 //
18
19 package org.eclipse.jetty.util.ajax;
20
21 import java.nio.ByteBuffer;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Objects;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.function.Function;
30
31 import org.eclipse.jetty.util.ArrayTernaryTrie;
32 import org.eclipse.jetty.util.BufferUtil;
33 import org.eclipse.jetty.util.Loader;
34 import org.eclipse.jetty.util.Trie;
35 import org.eclipse.jetty.util.TypeUtil;
36 import org.eclipse.jetty.util.Utf8StringBuilder;
37 import org.eclipse.jetty.util.ajax.JSON.Convertible;
38 import org.eclipse.jetty.util.ajax.JSON.Convertor;
39
40 /**
41 * <p>A non-blocking JSON parser that can parse partial JSON strings.</p>
42 * <p>Usage:</p>
43 * <pre>
44 * AsyncJSON parser = new AsyncJSON.Factory().newAsyncJSON();
45 *
46 * // Feed the parser with partial JSON string content.
47 * parser.parse(chunk1);
48 * parser.parse(chunk2);
49 *
50 * // Tell the parser that the JSON string content
51 * // is terminated and get the JSON object back.
52 * Map&lt;String, Object&gt; object = parser.complete();
53 * </pre>
54 * <p>After the call to {@link #complete()} the parser can be reused to parse
55 * another JSON string.</p>
56 * <p>Custom objects can be created by specifying a {@code "class"} or
57 * {@code "x-class"} field:</p>
58 * <pre>
59 * String json = """
60 * {
61 * "x-class": "com.acme.Person",
62 * "firstName": "John",
63 * "lastName": "Doe",
64 * "age": 42
65 * }
66 * """
67 *
68 * parser.parse(json);
69 * com.acme.Person person = parser.complete();
70 * </pre>
71 * <p>Class {@code com.acme.Person} must either implement {@link Convertible},
72 * or be mapped with a {@link Convertor} via {@link Factory#putConvertor(String, Convertor)}.</p>
73 * <p>JSON arrays are by default represented with a {@code List<Object>}, but the
74 * Java representation can be customized via {@link Factory#setArrayConverter(Function)}.</p>
75 */
76 public class AsyncJSON
77 {
78 /**
79 * <p>The factory that creates AsyncJSON instances.</p>
80 * <p>The factory can be configured with custom {@link Convertor}s,
81 * and with cached strings that will not be allocated if they can
82 * be looked up from the cache.</p>
83 */
84 public static class Factory
85 {
86 private Trie<CachedString> cache;
87 private Map<String, Convertor> convertors;
88 private Function<List<?>, Object> arrayConverter = list -> list;
89 private boolean detailedParseException;
90
91 /**
92 * @return the function to customize the Java representation of JSON arrays
93 * @see #setArrayConverter(Function)
94 */
95 public Function<List<?>, Object> getArrayConverter()
96 {
97 return arrayConverter;
98 }
99
100 /**
101 * <p>Sets the function to convert JSON arrays from their default Java
102 * representation, a {@code List<Object>}, to another Java data structure
103 * such as an {@code Object[]}.</p>
104 *
105 * @param arrayConverter the function to customize the Java representation of JSON arrays
106 * @see #getArrayConverter()
107 */
108 public void setArrayConverter(Function<List<?>, Object> arrayConverter)
109 {
110 this.arrayConverter = Objects.requireNonNull(arrayConverter);
111 }
112
113 /**
114 * @return whether a parse failure should report the whole JSON string or just the last chunk
115 */
116 public boolean isDetailedParseException()
117 {
118 return detailedParseException;
119 }
120
121 /**
122 * @param detailedParseException whether a parse failure should report the whole JSON string or just the last chunk
123 */
124 public void setDetailedParseException(boolean detailedParseException)
125 {
126 this.detailedParseException = detailedParseException;
127 }
128
129 /**
130 * @param value the string to cache
131 * @return whether the value can be cached
132 */
133 public boolean cache(String value)
134 {
135 if (cache == null)
136 cache = new ArrayTernaryTrie.Growing<>(false, 64, 64);
137
138 CachedString cached = new CachedString(value);
139 if (cached.isCacheable())
140 {
141 cache.put(cached.encoded, cached);
142 return true;
143 }
144 return false;
145 }
146
147 /**
148 * <p>Attempts to return a cached string from the buffer bytes.</p>
149 * <p>In case of a cache hit, the string is returned and the buffer
150 * position updated.</p>
151 * <p>In case of cache miss, {@code null} is returned and the buffer
152 * position is left unaltered.</p>
153 *
154 * @param buffer the buffer to lookup the string from
155 * @return a cached string or {@code null}
156 */
157 protected String cached(ByteBuffer buffer)
158 {
159 if (cache != null)
160 {
161 CachedString result = cache.getBest(buffer, 0, buffer.remaining());
162 if (result != null)
163 {
164 buffer.position(buffer.position() + result.encoded.length());
165 return result.value;
166 }
167 }
168 return null;
169 }
170
171 /**
172 * @return a new parser instance
173 */
174 public AsyncJSON newAsyncJSON()
175 {
176 return new AsyncJSON(this);
177 }
178
179 /**
180 * <p>Associates the given {@link Convertor} to the given class name.</p>
181 *
182 * @param className the domain class name such as {@code com.acme.Person}
183 * @param convertor the {@link Convertor} that converts {@code Map} to domain objects
184 */
185 public void putConvertor(String className, Convertor convertor)
186 {
187 if (convertors == null)
188 convertors = new ConcurrentHashMap<>();
189 convertors.put(className, convertor);
190 }
191
192 /**
193 * <p>Removes the {@link Convertor} associated with the given class name.</p>
194 *
195 * @param className the class name associated with the {@link Convertor}
196 * @return the {@link Convertor} associated with the class name, or {@code null}
197 */
198 public Convertor removeConvertor(String className)
199 {
200 if (convertors != null)
201 return convertors.remove(className);
202 return null;
203 }
204
205 /**
206 * <p>Returns the {@link Convertor} associated with the given class name, if any.</p>
207 *
208 * @param className the class name associated with the {@link Convertor}
209 * @return the {@link Convertor} associated with the class name, or {@code null}
210 */
211 public Convertor getConvertor(String className)
212 {
213 return convertors == null ? null : convertors.get(className);
214 }
215
216 private static class CachedString
217 {
218 private final String encoded;
219 private final String value;
220
221 private CachedString(String value)
222 {
223 this.encoded = JSON.toString(value);
224 this.value = value;
225 }
226
227 private boolean isCacheable()
228 {
229 for (int i = encoded.length(); i-- > 0;)
230 {
231 char c = encoded.charAt(i);
232 if (c > 127)
233 return false;
234 }
235 return true;
236 }
237 }
238 }
239
240 private static final Object UNSET = new Object();
241
242 private final FrameStack stack = new FrameStack();
243 private final NumberBuilder numberBuilder = new NumberBuilder();
244 private final Utf8StringBuilder stringBuilder = new Utf8StringBuilder(32);
245 private final Factory factory;
246 private List<ByteBuffer> chunks;
247
248 public AsyncJSON(Factory factory)
249 {
250 this.factory = factory;
251 }
252
253 // Used by tests only.
254 boolean isEmpty()
255 {
256 return stack.isEmpty();
257 }
258
259 /**
260 * <p>Feeds the parser with the given bytes chunk.</p>
261 *
262 * @param bytes the bytes to parse
263 * @return whether the JSON parsing was complete
264 * @throws IllegalArgumentException if the JSON is malformed
265 */
266 public boolean parse(byte[] bytes)
267 {
268 return parse(bytes, 0, bytes.length);
269 }
270
271 /**
272 * <p>Feeds the parser with the given bytes chunk.</p>
273 *
274 * @param bytes the bytes to parse
275 * @param offset the offset to start parsing from
276 * @param length the number of bytes to parse
277 * @return whether the JSON parsing was complete
278 * @throws IllegalArgumentException if the JSON is malformed
279 */
280 public boolean parse(byte[] bytes, int offset, int length)
281 {
282 return parse(ByteBuffer.wrap(bytes, offset, length));
283 }
284
285 /**
286 * <p>Feeds the parser with the given buffer chunk.</p>
287 *
288 * @param buffer the buffer to parse
289 * @return whether the JSON parsing was complete
290 * @throws IllegalArgumentException if the JSON is malformed
291 */
292 public boolean parse(ByteBuffer buffer)
293 {
294 try
295 {
296 if (factory.isDetailedParseException())
297 {
298 if (chunks == null)
299 chunks = new ArrayList<>();
300 ByteBuffer copy = buffer.isDirect()
301 ? ByteBuffer.allocateDirect(buffer.remaining())
302 : ByteBuffer.allocate(buffer.remaining());
303 copy.put(buffer).flip();
304 chunks.add(copy);
305 buffer.flip();
306 }
307
308 if (stack.isEmpty())
309 stack.push(State.COMPLETE, UNSET);
310
311 while (true)
312 {
313 Frame frame = stack.peek();
314 State state = frame.state;
315 switch (state)
316 {
317 case COMPLETE:
318 {
319 if (frame.value == UNSET)
320 {
321 if (parseAny(buffer))
322 break;
323 return false;
324 }
325 else
326 {
327 while (buffer.hasRemaining())
328 {
329 int position = buffer.position();
330 byte peek = buffer.get(position);
331 if (isWhitespace(peek))
332 buffer.position(position + 1);
333 else
334 throw newInvalidJSON(buffer, "invalid character after JSON data");
335 }
336 return true;
337 }
338 }
339 case NULL:
340 {
341 if (parseNull(buffer))
342 break;
343 return false;
344 }
345 case TRUE:
346 {
347 if (parseTrue(buffer))
348 break;
349 return false;
350 }
351 case FALSE:
352 {
353 if (parseFalse(buffer))
354 break;
355 return false;
356 }
357 case NUMBER:
358 {
359 if (parseNumber(buffer))
360 break;
361 return false;
362 }
363 case STRING:
364 {
365 if (parseString(buffer))
366 break;
367 return false;
368 }
369 case ESCAPE:
370 {
371 if (parseEscape(buffer))
372 break;
373 return false;
374 }
375 case UNICODE:
376 {
377 if (parseUnicode(buffer))
378 break;
379 return false;
380 }
381 case ARRAY:
382 {
383 if (parseArray(buffer))
384 break;
385 return false;
386 }
387 case OBJECT:
388 {
389 if (parseObject(buffer))
390 break;
391 return false;
392 }
393 case OBJECT_FIELD:
394 {
395 if (parseObjectField(buffer))
396 break;
397 return false;
398 }
399 case OBJECT_FIELD_NAME:
400 {
401 if (parseObjectFieldName(buffer))
402 break;
403 return false;
404 }
405 case OBJECT_FIELD_VALUE:
406 {
407 if (parseObjectFieldValue(buffer))
408 break;
409 return false;
410 }
411 default:
412 {
413 throw new IllegalStateException("invalid state " + state);
414 }
415 }
416 }
417 }
418 catch (Throwable x)
419 {
420 reset();
421 throw x;
422 }
423 }
424
425 /**
426 * <p>Signals to the parser that the parse data is complete, and returns
427 * the object parsed from the JSON chunks passed to the {@code parse()}
428 * methods.</p>
429 *
430 * @param <R> the type the result is cast to
431 * @return the result of the JSON parsing
432 * @throws IllegalArgumentException if the JSON is malformed
433 * @throws IllegalStateException if the no JSON was passed to the {@code parse()} methods
434 */
435 public <R> R complete()
436 {
437 try
438 {
439 if (stack.isEmpty())
440 throw new IllegalStateException("no JSON parsed");
441
442 while (true)
443 {
444 State state = stack.peek().state;
445 switch (state)
446 {
447 case NUMBER:
448 {
449 Number value = numberBuilder.value();
450 stack.pop();
451 stack.peek().value(value);
452 break;
453 }
454 case COMPLETE:
455 {
456 if (stack.peek().value == UNSET)
457 throw new IllegalStateException("invalid state " + state);
458 return (R)end();
459 }
460 default:
461 {
462 throw newInvalidJSON(BufferUtil.EMPTY_BUFFER, "incomplete JSON");
463 }
464 }
465 }
466 }
467 catch (Throwable x)
468 {
469 reset();
470 throw x;
471 }
472 }
473
474 /**
475 * <p>When a JSON <code>{</code> is encountered during parsing,
476 * this method is called to create a new {@code Map} instance.</p>
477 * <p>Subclasses may override to return a custom {@code Map} instance.</p>
478 *
479 * @param context the parsing context
480 * @return a {@code Map} instance
481 */
482 protected Map<String, Object> newObject(Context context)
483 {
484 return new HashMap<>();
485 }
486
487 /**
488 * <p>When a JSON <code>[</code> is encountered during parsing,
489 * this method is called to create a new {@code List} instance.</p>
490 * <p>Subclasses may override to return a custom {@code List} instance.</p>
491 *
492 * @param context the parsing context
493 * @return a {@code List} instance
494 */
495 protected List<Object> newArray(Context context)
496 {
497 return new ArrayList<>();
498 }
499
500 private Object end()
501 {
502 Object result = stack.peek().value;
503 reset();
504 return result;
505 }
506
507 private void reset()
508 {
509 stack.clear();
510 chunks = null;
511 }
512
513 private boolean parseAny(ByteBuffer buffer)
514 {
515 while (buffer.hasRemaining())
516 {
517 byte peek = buffer.get(buffer.position());
518 switch (peek)
519 {
520 case '[':
521 if (parseArray(buffer))
522 return true;
523 break;
524 case '{':
525 if (parseObject(buffer))
526 return true;
527 break;
528 case '-':
529 case '0':
530 case '1':
531 case '2':
532 case '3':
533 case '4':
534 case '5':
535 case '6':
536 case '7':
537 case '8':
538 case '9':
539 if (parseNumber(buffer))
540 return true;
541 break;
542 case '"':
543 if (parseString(buffer))
544 return true;
545 break;
546 case 'f':
547 if (parseFalse(buffer))
548 return true;
549 break;
550 case 'n':
551 if (parseNull(buffer))
552 return true;
553 break;
554 case 't':
555 if (parseTrue(buffer))
556 return true;
557 break;
558 default:
559 if (isWhitespace(peek))
560 {
561 buffer.get();
562 break;
563 }
564 throw newInvalidJSON(buffer, "unrecognized JSON value");
565 }
566 }
567 return false;
568 }
569
570 private boolean parseNull(ByteBuffer buffer)
571 {
572 while (buffer.hasRemaining())
573 {
574 byte currentByte = buffer.get();
575 switch (currentByte)
576 {
577 case 'n':
578 if (stack.peek().state != State.NULL)
579 {
580 stack.push(State.NULL, 0);
581 parseNullCharacter(buffer, 0);
582 break;
583 }
584 throw newInvalidJSON(buffer, "invalid 'null' literal");
585 case 'u':
586 parseNullCharacter(buffer, 1);
587 break;
588 case 'l':
589 int index = (Integer)stack.peek().value;
590 if (index == 2 || index == 3)
591 parseNullCharacter(buffer, index);
592 else
593 throw newInvalidJSON(buffer, "invalid 'null' literal");
594 if (index == 3)
595 {
596 stack.pop();
597 stack.peek().value(null);
598 return true;
599 }
600 break;
601 default:
602 throw newInvalidJSON(buffer, "invalid 'null' literal");
603 }
604 }
605 return false;
606 }
607
608 private void parseNullCharacter(ByteBuffer buffer, int index)
609 {
610 Frame frame = stack.peek();
611 int value = (Integer)frame.value;
612 if (value == index)
613 frame.value = ++value;
614 else
615 throw newInvalidJSON(buffer, "invalid 'null' literal");
616 }
617
618 private boolean parseTrue(ByteBuffer buffer)
619 {
620 while (buffer.hasRemaining())
621 {
622 byte currentByte = buffer.get();
623 switch (currentByte)
624 {
625 case 't':
626 if (stack.peek().state != State.TRUE)
627 {
628 stack.push(State.TRUE, 0);
629 parseTrueCharacter(buffer, 0);
630 break;
631 }
632 throw newInvalidJSON(buffer, "invalid 'true' literal");
633 case 'r':
634 parseTrueCharacter(buffer, 1);
635 break;
636 case 'u':
637 parseTrueCharacter(buffer, 2);
638 break;
639 case 'e':
640 parseTrueCharacter(buffer, 3);
641 stack.pop();
642 stack.peek().value(Boolean.TRUE);
643 return true;
644 default:
645 throw newInvalidJSON(buffer, "invalid 'true' literal");
646 }
647 }
648 return false;
649 }
650
651 private void parseTrueCharacter(ByteBuffer buffer, int index)
652 {
653 Frame frame = stack.peek();
654 int value = (Integer)frame.value;
655 if (value == index)
656 frame.value = ++value;
657 else
658 throw newInvalidJSON(buffer, "invalid 'true' literal");
659 }
660
661 private boolean parseFalse(ByteBuffer buffer)
662 {
663 while (buffer.hasRemaining())
664 {
665 byte currentByte = buffer.get();
666 switch (currentByte)
667 {
668 case 'f':
669 if (stack.peek().state != State.FALSE)
670 {
671 stack.push(State.FALSE, 0);
672 parseFalseCharacter(buffer, 0);
673 break;
674 }
675 throw newInvalidJSON(buffer, "invalid 'false' literal");
676 case 'a':
677 parseFalseCharacter(buffer, 1);
678 break;
679 case 'l':
680 parseFalseCharacter(buffer, 2);
681 break;
682 case 's':
683 parseFalseCharacter(buffer, 3);
684 break;
685 case 'e':
686 parseFalseCharacter(buffer, 4);
687 stack.pop();
688 stack.peek().value(Boolean.FALSE);
689 return true;
690 default:
691 throw newInvalidJSON(buffer, "invalid 'false' literal");
692 }
693 }
694 return false;
695 }
696
697 private void parseFalseCharacter(ByteBuffer buffer, int index)
698 {
699 Frame frame = stack.peek();
700 int value = (Integer)frame.value;
701 if (value == index)
702 frame.value = ++value;
703 else
704 throw newInvalidJSON(buffer, "invalid 'false' literal");
705 }
706
707 private boolean parseNumber(ByteBuffer buffer)
708 {
709 if (stack.peek().state != State.NUMBER)
710 stack.push(State.NUMBER, numberBuilder);
711
712 while (buffer.hasRemaining())
713 {
714 byte currentByte = buffer.get();
715 switch (currentByte)
716 {
717 case '+':
718 case '-':
719 if (numberBuilder.appendSign(currentByte))
720 break;
721 throw newInvalidJSON(buffer, "invalid number");
722 case '.':
723 case 'E':
724 case 'e':
725 if (numberBuilder.appendAlpha(currentByte))
726 break;
727 throw newInvalidJSON(buffer, "invalid number");
728 case '0':
729 case '1':
730 case '2':
731 case '3':
732 case '4':
733 case '5':
734 case '6':
735 case '7':
736 case '8':
737 case '9':
738 numberBuilder.appendDigit(currentByte);
739 break;
740 default:
741 buffer.position(buffer.position() - 1);
742 Number value = numberBuilder.value();
743 stack.pop();
744 stack.peek().value(value);
745 return true;
746 }
747 }
748 return false;
749 }
750
751 private boolean parseString(ByteBuffer buffer)
752 {
753 Frame frame = stack.peek();
754 if (buffer.hasRemaining() && frame.state != State.STRING)
755 {
756 String result = factory.cached(buffer);
757 if (result != null)
758 {
759 frame.value(result);
760 return true;
761 }
762 }
763
764 while (buffer.hasRemaining())
765 {
766 byte currentByte = buffer.get();
767 switch (currentByte)
768 {
769 // Explicit delimiter, handle push and pop in this method.
770 case '"':
771 {
772 if (stack.peek().state != State.STRING)
773 {
774 stack.push(State.STRING, stringBuilder);
775 break;
776 }
777 else
778 {
779 String string = stringBuilder.toString();
780 stringBuilder.reset();
781 stack.pop();
782 stack.peek().value(string);
783 return true;
784 }
785 }
786 case '\\':
787 {
788 buffer.position(buffer.position() - 1);
789 if (parseEscape(buffer))
790 break;
791 return false;
792 }
793 default:
794 {
795 stringBuilder.append(currentByte);
796 break;
797 }
798 }
799 }
800 return false;
801 }
802
803 private boolean parseEscape(ByteBuffer buffer)
804 {
805 while (buffer.hasRemaining())
806 {
807 byte currentByte = buffer.get();
808 switch (currentByte)
809 {
810 case '\\':
811 if (stack.peek().state != State.ESCAPE)
812 {
813 stack.push(State.ESCAPE, stringBuilder);
814 break;
815 }
816 else
817 {
818 return parseEscapeCharacter((char)currentByte);
819 }
820 case '"':
821 case '/':
822 return parseEscapeCharacter((char)currentByte);
823 case 'b':
824 return parseEscapeCharacter('\b');
825 case 'f':
826 return parseEscapeCharacter('\f');
827 case 'n':
828 return parseEscapeCharacter('\n');
829 case 'r':
830 return parseEscapeCharacter('\r');
831 case 't':
832 return parseEscapeCharacter('\t');
833 case 'u':
834 stack.push(State.UNICODE, ByteBuffer.allocate(4));
835 return parseUnicode(buffer);
836 default:
837 throw newInvalidJSON(buffer, "invalid escape sequence");
838 }
839 }
840 return false;
841 }
842
843 private boolean parseEscapeCharacter(char escape)
844 {
845 stack.pop();
846 stringBuilder.append(escape);
847 return true;
848 }
849
850 private boolean parseUnicode(ByteBuffer buffer)
851 {
852 // Expect 4 hex digits.
853 while (buffer.hasRemaining())
854 {
855 byte currentByte = buffer.get();
856 ByteBuffer hex = (ByteBuffer)stack.peek().value;
857 hex.put(hexToByte(buffer, currentByte));
858 if (!hex.hasRemaining())
859 {
860 int result = (hex.get(0) << 12) +
861 (hex.get(1) << 8) +
862 (hex.get(2) << 4) +
863 (hex.get(3));
864 stack.pop();
865 // Also done with escape parsing.
866 stack.pop();
867 stringBuilder.append((char)result);
868 return true;
869 }
870 }
871 return false;
872 }
873
874 private byte hexToByte(ByteBuffer buffer, byte currentByte)
875 {
876 try
877 {
878 return TypeUtil.convertHexDigit(currentByte);
879 }
880 catch (Throwable x)
881 {
882 throw newInvalidJSON(buffer, "invalid hex digit");
883 }
884 }
885
886 private boolean parseArray(ByteBuffer buffer)
887 {
888 while (buffer.hasRemaining())
889 {
890 byte peek = buffer.get(buffer.position());
891 switch (peek)
892 {
893 // Explicit delimiters, handle push and pop in this method.
894 case '[':
895 {
896 buffer.get();
897 stack.push(State.ARRAY, newArray(stack));
898 break;
899 }
900 case ']':
901 {
902 buffer.get();
903 @SuppressWarnings("unchecked")
904 List<Object> array = (List<Object>)stack.peek().value;
905 stack.pop();
906 stack.peek().value(convertArray(array));
907 return true;
908 }
909 case ',':
910 {
911 buffer.get();
912 break;
913 }
914 default:
915 {
916 if (isWhitespace(peek))
917 {
918 buffer.get();
919 break;
920 }
921 else
922 {
923 if (parseAny(buffer))
924 {
925 break;
926 }
927 return false;
928 }
929 }
930 }
931 }
932 return false;
933 }
934
935 private boolean parseObject(ByteBuffer buffer)
936 {
937 while (buffer.hasRemaining())
938 {
939 byte currentByte = buffer.get();
940 switch (currentByte)
941 {
942 // Explicit delimiters, handle push and pop in this method.
943 case '{':
944 {
945 if (stack.peek().state != State.OBJECT)
946 {
947 stack.push(State.OBJECT, newObject(stack));
948 break;
949 }
950 throw newInvalidJSON(buffer, "invalid object");
951 }
952 case '}':
953 {
954 @SuppressWarnings("unchecked")
955 Map<String, Object> object = (Map<String, Object>)stack.peek().value;
956 stack.pop();
957 stack.peek().value(convertObject(object));
958 return true;
959 }
960 case ',':
961 {
962 break;
963 }
964 default:
965 {
966 if (isWhitespace(currentByte))
967 {
968 break;
969 }
970 else
971 {
972 buffer.position(buffer.position() - 1);
973 if (parseObjectField(buffer))
974 break;
975 return false;
976 }
977 }
978 }
979 }
980 return false;
981 }
982
983 private boolean parseObjectField(ByteBuffer buffer)
984 {
985 while (buffer.hasRemaining())
986 {
987 byte peek = buffer.get(buffer.position());
988 switch (peek)
989 {
990 case '"':
991 {
992 if (stack.peek().state == State.OBJECT)
993 {
994 stack.push(State.OBJECT_FIELD, UNSET);
995 if (parseObjectFieldName(buffer))
996 {
997 // We are not done yet, parse the value.
998 break;
999 }
1000 return false;
1001 }
1002 else
1003 {
1004 return parseObjectFieldValue(buffer);
1005 }
1006 }
1007 default:
1008 {
1009 if (isWhitespace(peek))
1010 {
1011 buffer.get();
1012 break;
1013 }
1014 else if (stack.peek().state == State.OBJECT_FIELD_VALUE)
1015 {
1016 return parseObjectFieldValue(buffer);
1017 }
1018 else
1019 {
1020 throw newInvalidJSON(buffer, "invalid object field");
1021 }
1022 }
1023 }
1024 }
1025 return false;
1026 }
1027
1028 private boolean parseObjectFieldName(ByteBuffer buffer)
1029 {
1030 while (buffer.hasRemaining())
1031 {
1032 byte peek = buffer.get(buffer.position());
1033 switch (peek)
1034 {
1035 case '"':
1036 {
1037 if (stack.peek().state == State.OBJECT_FIELD)
1038 {
1039 stack.push(State.OBJECT_FIELD_NAME, UNSET);
1040 if (parseString(buffer))
1041 {
1042 // We are not done yet, parse until the ':'.
1043 break;
1044 }
1045 return false;
1046 }
1047 else
1048 {
1049 throw newInvalidJSON(buffer, "invalid object field");
1050 }
1051 }
1052 case ':':
1053 {
1054 buffer.get();
1055 // We are done with the field name.
1056 String fieldName = (String)stack.peek().value;
1057 stack.pop();
1058 // Change state to parse the field value.
1059 stack.push(fieldName, State.OBJECT_FIELD_VALUE, UNSET);
1060 return true;
1061 }
1062 default:
1063 {
1064 if (isWhitespace(peek))
1065 {
1066 buffer.get();
1067 break;
1068 }
1069 else
1070 {
1071 throw newInvalidJSON(buffer, "invalid object field");
1072 }
1073 }
1074 }
1075 }
1076 return false;
1077 }
1078
1079 private boolean parseObjectFieldValue(ByteBuffer buffer)
1080 {
1081 if (stack.peek().value == UNSET)
1082 {
1083 if (!parseAny(buffer))
1084 return false;
1085 }
1086
1087 // We are done with the field value.
1088 Frame frame = stack.peek();
1089 Object value = frame.value;
1090 String name = frame.name;
1091 stack.pop();
1092 // We are done with the field.
1093 stack.pop();
1094 @SuppressWarnings("unchecked")
1095 Map<String, Object> map = (Map<String, Object>)stack.peek().value;
1096 map.put(name, value);
1097
1098 return true;
1099 }
1100
1101 private Object convertArray(List<?> array)
1102 {
1103 return factory.getArrayConverter().apply(array);
1104 }
1105
1106 private Object convertObject(Map<String, Object> object)
1107 {
1108 Object result = convertObject("x-class", object);
1109 if (result == null)
1110 {
1111 result = convertObject("class", object);
1112 if (result == null)
1113 return object;
1114 }
1115 return result;
1116 }
1117
1118 private Object convertObject(String fieldName, Map<String, Object> object)
1119 {
1120 String className = (String)object.get(fieldName);
1121 if (className == null)
1122 return null;
1123
1124 Convertible convertible = toConvertible(className);
1125 if (convertible != null)
1126 {
1127 convertible.fromJSON(object);
1128 return convertible;
1129 }
1130
1131 Convertor convertor = factory.getConvertor(className);
1132 if (convertor != null)
1133 return convertor.fromJSON(object);
1134
1135 return null;
1136 }
1137
1138 private Convertible toConvertible(String className)
1139 {
1140 try
1141 {
1142 Class<?> klass = Loader.loadClass(className);
1143 if (Convertible.class.isAssignableFrom(klass))
1144 return (Convertible)klass.getConstructor().newInstance();
1145 return null;
1146 }
1147 catch (Throwable x)
1148 {
1149 throw new IllegalArgumentException(x);
1150 }
1151 }
1152
1153 protected RuntimeException newInvalidJSON(ByteBuffer buffer, String message)
1154 {
1155 Utf8StringBuilder builder = new Utf8StringBuilder();
1156 builder.append(System.lineSeparator());
1157 int position = buffer.position();
1158 if (factory.isDetailedParseException())
1159 {
1160 chunks.forEach(chunk -> builder.append(buffer));
1161 }
1162 else
1163 {
1164 buffer.position(0);
1165 builder.append(buffer);
1166 buffer.position(position);
1167 }
1168 builder.append(System.lineSeparator());
1169 String indent = "";
1170 if (position > 1)
1171 {
1172 char[] chars = new char[position - 1];
1173 Arrays.fill(chars, ' ');
1174 indent = new String(chars);
1175 }
1176 builder.append(indent);
1177 builder.append("^ ");
1178 builder.append(message);
1179 return new IllegalArgumentException(builder.toString());
1180 }
1181
1182 private static boolean isWhitespace(byte ws)
1183 {
1184 switch (ws)
1185 {
1186 case ' ':
1187 case '\n':
1188 case '\r':
1189 case '\t':
1190 return true;
1191 default:
1192 return false;
1193 }
1194 }
1195
1196 /**
1197 * <p>The state of JSON parsing.</p>
1198 */
1199 public interface Context
1200 {
1201 /**
1202 * @return the depth in the JSON structure
1203 */
1204 public int depth();
1205 }
1206
1207 private enum State
1208 {
1209 COMPLETE, NULL, TRUE, FALSE, NUMBER, STRING, ESCAPE, UNICODE, ARRAY, OBJECT, OBJECT_FIELD, OBJECT_FIELD_NAME, OBJECT_FIELD_VALUE
1210 }
1211
1212 private static class Frame
1213 {
1214 private String name;
1215 private State state;
1216 private Object value;
1217
1218 private void value(Object value)
1219 {
1220 switch (state)
1221 {
1222 case COMPLETE:
1223 case STRING:
1224 case OBJECT_FIELD_NAME:
1225 case OBJECT_FIELD_VALUE:
1226 {
1227 this.value = value;
1228 break;
1229 }
1230 case ARRAY:
1231 {
1232 @SuppressWarnings("unchecked")
1233 List<Object> array = (List<Object>)this.value;
1234 array.add(value);
1235 break;
1236 }
1237 default:
1238 {
1239 throw new IllegalStateException("invalid state " + state);
1240 }
1241 }
1242 }
1243 }
1244
1245 private static class NumberBuilder
1246 {
1247 // 1 => positive integer
1248 // 0 => non-integer
1249 // -1 => negative integer
1250 private int integer = 1;
1251 private long value;
1252 private StringBuilder builder;
1253
1254 private boolean appendSign(byte b)
1255 {
1256 if (integer == 0)
1257 {
1258 if (builder.length() == 0)
1259 {
1260 builder.append((char)b);
1261 return true;
1262 }
1263 else
1264 {
1265 char c = builder.charAt(builder.length() - 1);
1266 if (c == 'E' || c == 'e')
1267 {
1268 builder.append((char)b);
1269 return true;
1270 }
1271 }
1272 return false;
1273 }
1274 else
1275 {
1276 if (value == 0)
1277 {
1278 if (b == '-')
1279 {
1280 if (integer == 1)
1281 {
1282 integer = -1;
1283 return true;
1284 }
1285 }
1286 else
1287 {
1288 return true;
1289 }
1290 }
1291 }
1292 return false;
1293 }
1294
1295 private void appendDigit(byte b)
1296 {
1297 if (integer == 0)
1298 builder.append((char)b);
1299 else
1300 value = value * 10 + (b - '0');
1301 }
1302
1303 private boolean appendAlpha(byte b)
1304 {
1305 if (integer == 0)
1306 {
1307 char c = builder.charAt(builder.length() - 1);
1308 if ('0' <= c && c <= '9' && builder.indexOf("" + (char)b) < 0)
1309 {
1310 builder.append((char)b);
1311 return true;
1312 }
1313 }
1314 else
1315 {
1316 if (builder == null)
1317 builder = new StringBuilder(16);
1318 if (integer == -1)
1319 builder.append('-');
1320 integer = 0;
1321 builder.append(value);
1322 builder.append((char)b);
1323 return true;
1324 }
1325 return false;
1326 }
1327
1328 private Number value()
1329 {
1330 try
1331 {
1332 if (integer == 0)
1333 return Double.parseDouble(builder.toString());
1334 return integer * value;
1335 }
1336 finally
1337 {
1338 reset();
1339 }
1340 }
1341
1342 private void reset()
1343 {
1344 integer = 1;
1345 value = 0;
1346 if (builder != null)
1347 builder.setLength(0);
1348 }
1349 }
1350
1351 private static class FrameStack implements AsyncJSON.Context
1352 {
1353 private final List<Frame> stack = new ArrayList<>();
1354 private int cursor;
1355
1356 private FrameStack()
1357 {
1358 grow(6);
1359 }
1360
1361 private void grow(int grow)
1362 {
1363 for (int i = 0; i < grow; i++)
1364 {
1365 stack.add(new Frame());
1366 }
1367 }
1368
1369 private void clear()
1370 {
1371 while (!isEmpty())
1372 {
1373 pop();
1374 }
1375 }
1376
1377 private boolean isEmpty()
1378 {
1379 return cursor == 0;
1380 }
1381
1382 @Override
1383 public int depth()
1384 {
1385 return cursor - 1;
1386 }
1387
1388 private Frame peek()
1389 {
1390 if (isEmpty())
1391 throw new IllegalStateException("empty stack");
1392 return stack.get(depth());
1393 }
1394
1395 private void push(AsyncJSON.State state, Object value)
1396 {
1397 push(null, state, value);
1398 }
1399
1400 private void push(String name, AsyncJSON.State state, Object value)
1401 {
1402 if (cursor == stack.size())
1403 grow(2);
1404 ++cursor;
1405 Frame frame = stack.get(depth());
1406 frame.name = name;
1407 frame.state = state;
1408 frame.value = value;
1409 }
1410
1411 private void pop()
1412 {
1413 if (isEmpty())
1414 throw new IllegalStateException("empty stack");
1415 Frame frame = stack.get(depth());
1416 --cursor;
1417 frame.name = null;
1418 frame.value = null;
1419 frame.state = null;
1420 }
1421 }
1422 }