Debian Codegraph @

jetty-util-ajax/src/main/java/org/eclipse/jetty/util/ajax/JSON.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.io.Externalizable;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.Reader;
25 import java.lang.reflect.Array;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Objects;
34 import java.util.concurrent.ConcurrentHashMap;
35 import java.util.function.Function;
36 import java.util.stream.IntStream;
37
38 import org.eclipse.jetty.util.IO;
39 import org.eclipse.jetty.util.Loader;
40 import org.eclipse.jetty.util.TypeUtil;
41 import org.eclipse.jetty.util.log.Log;
42 import org.eclipse.jetty.util.log.Logger;
43
44 /**
45 * JSON Parser and Generator.
46 * <p>
47 * This class provides some static methods to convert POJOs to and from JSON
48 * notation. The mapping from JSON to java is:
49 *
50 * <pre>
51 * object --&gt; Map
52 * array --&gt; Object[]
53 * number --&gt; Double or Long
54 * string --&gt; String
55 * null --&gt; null
56 * bool --&gt; Boolean
57 * </pre>
58 *
59 * The java to JSON mapping is:
60 *
61 * <pre>
62 * String --&gt; string
63 * Number --&gt; number
64 * Map --&gt; object
65 * List --&gt; array
66 * Array --&gt; array
67 * null --&gt; null
68 * Boolean--&gt; boolean
69 * Object --&gt; string (dubious!)
70 * </pre>
71 *
72 * The interface {@link JSON.Convertible} may be implemented by classes that
73 * wish to externalize and initialize specific fields to and from JSON objects.
74 * Only directed acyclic graphs of objects are supported.
75 * <p>
76 * The interface {@link JSON.Generator} may be implemented by classes that know
77 * how to render themselves as JSON and the {@link #toString(Object)} method
78 * will use {@link JSON.Generator#addJSON(Appendable)} to generate the JSON.
79 * The class {@link JSON.Literal} may be used to hold pre-generated JSON object.
80 * <p>
81 * The interface {@link JSON.Convertor} may be implemented to provide static
82 * converters for objects that may be registered with
83 * {@link #registerConvertor(Class, Convertor)}.
84 * These converters are looked up by class, interface and super class by
85 * {@link #getConvertor(Class)}.
86 * <p>
87 * If a JSON object has a "class" field, then a java class for that name is
88 * loaded and the method {@link #convertTo(Class, Map)} is used to find a
89 * {@link JSON.Convertor} for that class.
90 * <p>
91 * If a JSON object has a "x-class" field then a direct lookup for a
92 * {@link JSON.Convertor} for that class name is done (without loading the class).
93 */
94 public class JSON
95 {
96 static final Logger LOG = Log.getLogger(JSON.class);
97 public static final JSON DEFAULT = new JSON();
98
99 private final Map<String, Convertor> _convertors = new ConcurrentHashMap<>();
100 private int _stringBufferSize = 1024;
101 private Function<List<?>, Object> _arrayConverter = this::defaultArrayConverter;
102
103 public JSON()
104 {
105 }
106
107 /**
108 * Reset the default JSON behaviors to default
109 */
110 public static void reset()
111 {
112 DEFAULT._convertors.clear();
113 DEFAULT._stringBufferSize = 1024;
114 }
115
116 /**
117 * @return the initial stringBuffer size to use when creating JSON strings
118 * (default 1024)
119 */
120 public int getStringBufferSize()
121 {
122 return _stringBufferSize;
123 }
124
125 /**
126 * @param stringBufferSize the initial stringBuffer size to use when creating JSON
127 * strings (default 1024)
128 */
129 public void setStringBufferSize(int stringBufferSize)
130 {
131 _stringBufferSize = stringBufferSize;
132 }
133
134 /**
135 * Register a {@link Convertor} for a class or interface.
136 *
137 * @param forClass The class or interface that the convertor applies to
138 * @param convertor the convertor
139 */
140 public static void registerConvertor(Class forClass, Convertor convertor)
141 {
142 DEFAULT.addConvertor(forClass, convertor);
143 }
144
145 public static JSON getDefault()
146 {
147 return DEFAULT;
148 }
149
150 @Deprecated
151 public static void setDefault(JSON json)
152 {
153 }
154
155 public static String toString(Object object)
156 {
157 StringBuilder buffer = new StringBuilder(DEFAULT.getStringBufferSize());
158 DEFAULT.append(buffer, object);
159 return buffer.toString();
160 }
161
162 public static String toString(Map object)
163 {
164 StringBuilder buffer = new StringBuilder(DEFAULT.getStringBufferSize());
165 DEFAULT.appendMap(buffer, object);
166 return buffer.toString();
167 }
168
169 public static String toString(Object[] array)
170 {
171 StringBuilder buffer = new StringBuilder(DEFAULT.getStringBufferSize());
172 DEFAULT.appendArray(buffer, array);
173 return buffer.toString();
174 }
175
176 /**
177 * @param s String containing JSON object or array.
178 * @return A Map, Object array or primitive array parsed from the JSON.
179 */
180 public static Object parse(String s)
181 {
182 return DEFAULT.parse(new StringSource(s), false);
183 }
184
185 /**
186 * @param s String containing JSON object or array.
187 * @param stripOuterComment If true, an outer comment around the JSON is ignored.
188 * @return A Map, Object array or primitive array parsed from the JSON.
189 */
190 public static Object parse(String s, boolean stripOuterComment)
191 {
192 return DEFAULT.parse(new StringSource(s), stripOuterComment);
193 }
194
195 /**
196 * @param in Reader containing JSON object or array.
197 * @return A Map, Object array or primitive array parsed from the JSON.
198 * @throws IOException if unable to parse
199 */
200 public static Object parse(Reader in) throws IOException
201 {
202 return DEFAULT.parse(new ReaderSource(in), false);
203 }
204
205 /**
206 * @param in Reader containing JSON object or array.
207 * @param stripOuterComment If true, an outer comment around the JSON is ignored.
208 * @return A Map, Object array or primitive array parsed from the JSON.
209 * @throws IOException if unable to parse
210 */
211 public static Object parse(Reader in, boolean stripOuterComment) throws IOException
212 {
213 return DEFAULT.parse(new ReaderSource(in), stripOuterComment);
214 }
215
216 /**
217 * @param in Reader containing JSON object or array.
218 * @return A Map, Object array or primitive array parsed from the JSON.
219 * @throws IOException if unable to parse
220 * @deprecated use {@link #parse(Reader)}
221 */
222 @Deprecated
223 public static Object parse(InputStream in) throws IOException
224 {
225 return DEFAULT.parse(new StringSource(IO.toString(in)), false);
226 }
227
228 /**
229 * @param in Stream containing JSON object or array.
230 * @param stripOuterComment If true, an outer comment around the JSON is ignored.
231 * @return A Map, Object array or primitive array parsed from the JSON.
232 * @throws IOException if unable to parse
233 * @deprecated use {@link #parse(Reader, boolean)}
234 */
235 @Deprecated
236 public static Object parse(InputStream in, boolean stripOuterComment) throws IOException
237 {
238 return DEFAULT.parse(new StringSource(IO.toString(in)), stripOuterComment);
239 }
240
241 private void quotedEscape(Appendable buffer, String input)
242 {
243 try
244 {
245 buffer.append('"');
246 if (input != null && !input.isEmpty())
247 {
248 escapeString(buffer, input);
249 }
250 buffer.append('"');
251 }
252 catch (IOException e)
253 {
254 throw new RuntimeException(e);
255 }
256 }
257
258 public void escapeString(Appendable buffer, String input) throws IOException
259 {
260 // default escaping here.
261
262 for (int i = 0; i < input.length(); ++i)
263 {
264 char c = input.charAt(i);
265
266 // ASCII printable range
267 if ((c >= 0x20) && (c <= 0x7E))
268 {
269 // Special cases for quotation-mark, reverse-solidus, and solidus
270 if ((c == '"') || (c == '\\')
271 /* solidus is optional - per Carsten Bormann (IETF)
272 || (c == '/') */)
273 {
274 buffer.append('\\').append(c);
275 }
276 else
277 {
278 // ASCII printable (that isn't escaped above)
279 buffer.append(c);
280 }
281 }
282 else
283 {
284 // All other characters are escaped (in some way)
285
286 // First we deal with the special short-form escaping
287 if (c == '\b') // backspace
288 buffer.append("\\b");
289 else if (c == '\f') // form-feed
290 buffer.append("\\f");
291 else if (c == '\n') // line feed
292 buffer.append("\\n");
293 else if (c == '\r') // carriage return
294 buffer.append("\\r");
295 else if (c == '\t') // tab
296 buffer.append("\\t");
297 else if (c < 0x20 || c == 0x7F) // all control characters
298 {
299 // default behavior is to encode
300 buffer.append(String.format("\\u%04x", (short)c));
301 }
302 else
303 {
304 // optional behavior in JSON spec
305 escapeUnicode(buffer, c);
306 }
307 }
308 }
309 }
310
311 /**
312 * Per spec, unicode characters are by default NOT escaped.
313 * This overridable allows for alternate behavior to escape those with your choice
314 * of encoding.
315 *
316 * <pre>
317 * protected void escapeUnicode(Appendable buffer, char c) throws IOException
318 * {
319 * // Unicode is slash-u escaped
320 * buffer.append(String.format("\\u%04x", (int)c));
321 * }
322 * </pre>
323 */
324 protected void escapeUnicode(Appendable buffer, char c) throws IOException
325 {
326 buffer.append(c);
327 }
328
329 /**
330 * Convert Object to JSON
331 *
332 * @param object The object to convert
333 * @return The JSON String
334 */
335 public String toJSON(Object object)
336 {
337 StringBuilder buffer = new StringBuilder(getStringBufferSize());
338 append(buffer, object);
339 return buffer.toString();
340 }
341
342 /**
343 * Convert JSON to Object
344 *
345 * @param json The json to convert
346 * @return The object
347 */
348 public Object fromJSON(String json)
349 {
350 Source source = new StringSource(json);
351 return parse(source);
352 }
353
354 @Deprecated
355 public void append(StringBuffer buffer, Object object)
356 {
357 append((Appendable)buffer, object);
358 }
359
360 /**
361 * Append object as JSON to string buffer.
362 *
363 * @param buffer the buffer to append to
364 * @param object the object to append
365 */
366 public void append(Appendable buffer, Object object)
367 {
368 try
369 {
370 if (object == null)
371 {
372 buffer.append("null");
373 }
374 // Most likely first
375 else if (object instanceof Map)
376 {
377 appendMap(buffer, (Map)object);
378 }
379 else if (object instanceof String)
380 {
381 appendString(buffer, (String)object);
382 }
383 else if (object instanceof Number)
384 {
385 appendNumber(buffer, (Number)object);
386 }
387 else if (object instanceof Boolean)
388 {
389 appendBoolean(buffer, (Boolean)object);
390 }
391 else if (object.getClass().isArray())
392 {
393 appendArray(buffer, object);
394 }
395 else if (object instanceof Character)
396 {
397 appendString(buffer, object.toString());
398 }
399 else if (object instanceof Convertible)
400 {
401 appendJSON(buffer, (Convertible)object);
402 }
403 else if (object instanceof Generator)
404 {
405 appendJSON(buffer, (Generator)object);
406 }
407 else
408 {
409 // Check Convertor before Collection to support JSONCollectionConvertor
410 Convertor convertor = getConvertor(object.getClass());
411 if (convertor != null)
412 {
413 appendJSON(buffer, convertor, object);
414 }
415 else if (object instanceof Collection)
416 {
417 appendArray(buffer, (Collection)object);
418 }
419 else
420 {
421 appendString(buffer, object.toString());
422 }
423 }
424 }
425 catch (IOException e)
426 {
427 throw new RuntimeException(e);
428 }
429 }
430
431 @Deprecated
432 public void appendNull(StringBuffer buffer)
433 {
434 appendNull((Appendable)buffer);
435 }
436
437 public void appendNull(Appendable buffer)
438 {
439 try
440 {
441 buffer.append("null");
442 }
443 catch (IOException e)
444 {
445 throw new RuntimeException(e);
446 }
447 }
448
449 @Deprecated
450 public void appendJSON(final StringBuffer buffer, final Convertor convertor, final Object object)
451 {
452 appendJSON((Appendable)buffer, convertor, object);
453 }
454
455 public void appendJSON(final Appendable buffer, final Convertor convertor, final Object object)
456 {
457 appendJSON(buffer, new Convertible()
458 {
459 @Override
460 public void fromJSON(Map object)
461 {
462 }
463
464 @Override
465 public void toJSON(Output out)
466 {
467 convertor.toJSON(object, out);
468 }
469 });
470 }
471
472 @Deprecated
473 public void appendJSON(final StringBuffer buffer, Convertible converter)
474 {
475 appendJSON((Appendable)buffer, converter);
476 }
477
478 public void appendJSON(final Appendable buffer, Convertible converter)
479 {
480 ConvertableOutput out = new ConvertableOutput(buffer);
481 converter.toJSON(out);
482 out.complete();
483 }
484
485 @Deprecated
486 public void appendJSON(StringBuffer buffer, Generator generator)
487 {
488 generator.addJSON(buffer);
489 }
490
491 public void appendJSON(Appendable buffer, Generator generator)
492 {
493 generator.addJSON(buffer);
494 }
495
496 @Deprecated
497 public void appendMap(StringBuffer buffer, Map<?, ?> map)
498 {
499 appendMap((Appendable)buffer, map);
500 }
501
502 public void appendMap(Appendable buffer, Map<?, ?> map)
503 {
504 try
505 {
506 if (map == null)
507 {
508 appendNull(buffer);
509 return;
510 }
511
512 buffer.append('{');
513 Iterator<?> iter = map.entrySet().iterator();
514 while (iter.hasNext())
515 {
516 Map.Entry<?, ?> entry = (Map.Entry<?, ?>)iter.next();
517 quotedEscape(buffer, entry.getKey().toString());
518 buffer.append(':');
519 append(buffer, entry.getValue());
520 if (iter.hasNext())
521 buffer.append(',');
522 }
523
524 buffer.append('}');
525 }
526 catch (IOException e)
527 {
528 throw new RuntimeException(e);
529 }
530 }
531
532 @Deprecated
533 public void appendArray(StringBuffer buffer, Collection collection)
534 {
535 appendArray((Appendable)buffer, collection);
536 }
537
538 public void appendArray(Appendable buffer, Collection collection)
539 {
540 try
541 {
542 if (collection == null)
543 {
544 appendNull(buffer);
545 return;
546 }
547
548 buffer.append('[');
549 Iterator iter = collection.iterator();
550 boolean first = true;
551 while (iter.hasNext())
552 {
553 if (!first)
554 buffer.append(',');
555
556 first = false;
557 append(buffer, iter.next());
558 }
559
560 buffer.append(']');
561 }
562 catch (IOException e)
563 {
564 throw new RuntimeException(e);
565 }
566 }
567
568 @Deprecated
569 public void appendArray(StringBuffer buffer, Object array)
570 {
571 appendArray((Appendable)buffer, array);
572 }
573
574 public void appendArray(Appendable buffer, Object array)
575 {
576 try
577 {
578 if (array == null)
579 {
580 appendNull(buffer);
581 return;
582 }
583
584 buffer.append('[');
585 int length = Array.getLength(array);
586
587 for (int i = 0; i < length; i++)
588 {
589 if (i != 0)
590 buffer.append(',');
591 append(buffer, Array.get(array, i));
592 }
593
594 buffer.append(']');
595 }
596 catch (IOException e)
597 {
598 throw new RuntimeException(e);
599 }
600 }
601
602 @Deprecated
603 public void appendBoolean(StringBuffer buffer, Boolean b)
604 {
605 appendBoolean((Appendable)buffer, b);
606 }
607
608 public void appendBoolean(Appendable buffer, Boolean b)
609 {
610 try
611 {
612 if (b == null)
613 {
614 appendNull(buffer);
615 return;
616 }
617 buffer.append(b ? "true" : "false");
618 }
619 catch (IOException e)
620 {
621 throw new RuntimeException(e);
622 }
623 }
624
625 @Deprecated
626 public void appendNumber(StringBuffer buffer, Number number)
627 {
628 appendNumber((Appendable)buffer, number);
629 }
630
631 public void appendNumber(Appendable buffer, Number number)
632 {
633 try
634 {
635 if (number == null)
636 {
637 appendNull(buffer);
638 return;
639 }
640 buffer.append(String.valueOf(number));
641 }
642 catch (IOException e)
643 {
644 throw new RuntimeException(e);
645 }
646 }
647
648 @Deprecated
649 public void appendString(StringBuffer buffer, String string)
650 {
651 appendString((Appendable)buffer, string);
652 }
653
654 public void appendString(Appendable buffer, String string)
655 {
656 if (string == null)
657 {
658 appendNull(buffer);
659 return;
660 }
661
662 quotedEscape(buffer, string);
663 }
664
665 // Parsing utilities
666
667 protected String toString(char[] buffer, int offset, int length)
668 {
669 return new String(buffer, offset, length);
670 }
671
672 protected Map<String, Object> newMap()
673 {
674 return new HashMap<>();
675 }
676
677 /**
678 * @param size the size of the array
679 * @return a new array
680 * @deprecated use {@link #setArrayConverter(Function)} instead.
681 */
682 @Deprecated
683 protected Object[] newArray(int size)
684 {
685 return new Object[size];
686 }
687
688 protected JSON contextForArray()
689 {
690 return this;
691 }
692
693 protected JSON contextFor(String field)
694 {
695 return this;
696 }
697
698 protected Object convertTo(Class type, Map map)
699 {
700 if (type != null && Convertible.class.isAssignableFrom(type))
701 {
702 try
703 {
704 Convertible conv = (Convertible)type.getDeclaredConstructor().newInstance();
705 conv.fromJSON(map);
706 return conv;
707 }
708 catch (Exception e)
709 {
710 throw new RuntimeException(e);
711 }
712 }
713
714 Convertor convertor = getConvertor(type);
715 if (convertor != null)
716 {
717 return convertor.fromJSON(map);
718 }
719 return map;
720 }
721
722 /**
723 * Register a {@link Convertor} for a class or interface.
724 *
725 * @param forClass The class or interface that the convertor applies to
726 * @param convertor the convertor
727 */
728 public void addConvertor(Class forClass, Convertor convertor)
729 {
730 _convertors.put(forClass.getName(), convertor);
731 }
732
733 /**
734 * Lookup a convertor for a class.
735 * <p>
736 * If no match is found for the class, then the interfaces for the class are
737 * tried. If still no match is found, then the super class and it's
738 * interfaces are tried recursively.
739 *
740 * @param forClass The class
741 * @return a {@link JSON.Convertor} or null if none were found.
742 */
743 protected Convertor getConvertor(Class forClass)
744 {
745 Class cls = forClass;
746 Convertor convertor = _convertors.get(cls.getName());
747 if (convertor == null && this != DEFAULT)
748 convertor = DEFAULT.getConvertor(cls);
749
750 while (convertor == null && cls != Object.class)
751 {
752 Class[] ifs = cls.getInterfaces();
753 int i = 0;
754 while (convertor == null && i < ifs.length)
755 {
756 convertor = _convertors.get(ifs[i++].getName());
757 }
758 if (convertor == null)
759 {
760 cls = cls.getSuperclass();
761 convertor = _convertors.get(cls.getName());
762 }
763 }
764 return convertor;
765 }
766
767 /**
768 * Register a {@link JSON.Convertor} for a named class or interface.
769 *
770 * @param name name of a class or an interface that the convertor applies to
771 * @param convertor the convertor
772 */
773 public void addConvertorFor(String name, Convertor convertor)
774 {
775 _convertors.put(name, convertor);
776 }
777
778 /**
779 * Removes a registered {@link JSON.Convertor} for the given named class or interface.
780 *
781 * @param name name of a class or an interface for a registered {@link JSON.Convertor}
782 * @return the {@link JSON.Convertor} that was removed, or null
783 */
784 public Convertor removeConvertorFor(String name)
785 {
786 return _convertors.remove(name);
787 }
788
789 /**
790 * @return the function to customize the Java representation of JSON arrays
791 * @see #setArrayConverter(Function)
792 */
793 public Function<List<?>, Object> getArrayConverter()
794 {
795 return _arrayConverter;
796 }
797
798 /**
799 * <p>Sets the function to convert JSON arrays from their default Java
800 * representation, a {@code List<Object>}, to another Java data structure
801 * such as an {@code Object[]}.</p>
802 *
803 * @param arrayConverter the function to customize the Java representation of JSON arrays
804 * @see #getArrayConverter()
805 */
806 public void setArrayConverter(Function<List<?>, Object> arrayConverter)
807 {
808 _arrayConverter = Objects.requireNonNull(arrayConverter);
809 }
810
811 /**
812 * Lookup a convertor for a named class.
813 *
814 * @param name name of the class
815 * @return a {@link JSON.Convertor} or null if none were found.
816 */
817 public Convertor getConvertorFor(String name)
818 {
819 Convertor convertor = _convertors.get(name);
820 if (convertor == null && this != DEFAULT)
821 convertor = DEFAULT.getConvertorFor(name);
822 return convertor;
823 }
824
825 public Object parse(Source source, boolean stripOuterComment)
826 {
827 int commentState = 0; // 0=no comment, 1="/", 2="/*", 3="/* *" -1="//"
828 if (!stripOuterComment)
829 return parse(source);
830
831 int stripState = 1; // 0=no strip, 1=wait for /*, 2= wait for */
832
833 Object o = null;
834 while (source.hasNext())
835 {
836 char c = source.peek();
837
838 // handle // or /* comment
839 if (commentState == 1)
840 {
841 switch (c)
842 {
843 case '/':
844 commentState = -1;
845 break;
846 case '*':
847 commentState = 2;
848 if (stripState == 1)
849 {
850 commentState = 0;
851 stripState = 2;
852 }
853 }
854 }
855 // handle comment
856 else if (commentState > 1)
857 {
858 switch (c)
859 {
860 case '*':
861 commentState = 3;
862 break;
863 case '/':
864 if (commentState == 3)
865 {
866 commentState = 0;
867 if (stripState == 2)
868 return o;
869 }
870 else
871 commentState = 2;
872 break;
873 default:
874 commentState = 2;
875 }
876 }
877 // handle // comment
878 else if (commentState < 0)
879 {
880 switch (c)
881 {
882 case '\r':
883 case '\n':
884 commentState = 0;
885 break;
886 default:
887 break;
888 }
889 }
890 // handle unknown
891 else
892 {
893 if (!Character.isWhitespace(c))
894 {
895 if (c == '/')
896 commentState = 1;
897 else if (c == '*')
898 commentState = 3;
899 else if (o == null)
900 {
901 o = parse(source);
902 continue;
903 }
904 }
905 }
906
907 source.next();
908 }
909
910 return o;
911 }
912
913 public Object parse(Source source)
914 {
915 int commentState = 0; // 0=no comment, 1="/", 2="/*", 3="/* *" -1="//"
916
917 while (source.hasNext())
918 {
919 char c = source.peek();
920
921 // handle // or /* comment
922 if (commentState == 1)
923 {
924 switch (c)
925 {
926 case '/':
927 commentState = -1;
928 break;
929 case '*':
930 commentState = 2;
931 }
932 }
933 // handle comment
934 else if (commentState > 1)
935 {
936 switch (c)
937 {
938 case '*':
939 commentState = 3;
940 break;
941 case '/':
942 if (commentState == 3)
943 commentState = 0;
944 else
945 commentState = 2;
946 break;
947 default:
948 commentState = 2;
949 }
950 }
951 // handle // comment
952 else if (commentState < 0)
953 {
954 switch (c)
955 {
956 case '\r':
957 case '\n':
958 commentState = 0;
959 break;
960 default:
961 break;
962 }
963 }
964 // handle unknown
965 else
966 {
967 switch (c)
968 {
969 case '{':
970 return parseObject(source);
971 case '[':
972 return parseArray(source);
973 case '"':
974 return parseString(source);
975 case '-':
976 return parseNumber(source);
977
978 case 'n':
979 complete("null", source);
980 return null;
981 case 't':
982 complete("true", source);
983 return Boolean.TRUE;
984 case 'f':
985 complete("false", source);
986 return Boolean.FALSE;
987 case 'u':
988 complete("undefined", source);
989 return null;
990 case 'N':
991 complete("NaN", source);
992 return null;
993
994 case '/':
995 commentState = 1;
996 break;
997
998 default:
999 if (Character.isDigit(c))
1000 return parseNumber(source);
1001 else if (Character.isWhitespace(c))
1002 break;
1003 return handleUnknown(source, c);
1004 }
1005 }
1006 source.next();
1007 }
1008
1009 return null;
1010 }
1011
1012 protected Object handleUnknown(Source source, char c)
1013 {
1014 throw new IllegalStateException("unknown char '" + c + "'(" + (int)c + ") in " + source);
1015 }
1016
1017 protected Object parseObject(Source source)
1018 {
1019 if (source.next() != '{')
1020 throw new IllegalStateException();
1021 Map<String, Object> map = newMap();
1022
1023 char next = seekTo("\"}", source);
1024
1025 while (source.hasNext())
1026 {
1027 if (next == '}')
1028 {
1029 source.next();
1030 break;
1031 }
1032
1033 String name = parseString(source);
1034 seekTo(':', source);
1035 source.next();
1036
1037 Object value = contextFor(name).parse(source);
1038 map.put(name, value);
1039
1040 seekTo(",}", source);
1041 next = source.next();
1042 if (next == '}')
1043 break;
1044 else
1045 next = seekTo("\"}", source);
1046 }
1047
1048 String xclassname = (String)map.get("x-class");
1049 if (xclassname != null)
1050 {
1051 Convertor c = getConvertorFor(xclassname);
1052 if (c != null)
1053 return c.fromJSON(map);
1054 LOG.warn("No Convertor for x-class '{}'", xclassname);
1055 }
1056
1057 String classname = (String)map.get("class");
1058 if (classname != null)
1059 {
1060 try
1061 {
1062 Class<?> c = Loader.loadClass(classname);
1063 return convertTo(c, map);
1064 }
1065 catch (ClassNotFoundException e)
1066 {
1067 LOG.warn("No Class for '{}'", classname);
1068 }
1069 }
1070
1071 return map;
1072 }
1073
1074 private Object defaultArrayConverter(List<?> list)
1075 {
1076 // Call newArray() to keep backward compatibility.
1077 Object[] objects = newArray(list.size());
1078 IntStream.range(0, list.size()).forEach(i -> objects[i] = list.get(i));
1079 return objects;
1080 }
1081
1082 protected Object parseArray(Source source)
1083 {
1084 if (source.next() != '[')
1085 throw new IllegalStateException();
1086
1087 int size = 0;
1088 List<Object> list = null;
1089 Object item = null;
1090 boolean comma = true;
1091
1092 while (source.hasNext())
1093 {
1094 char c = source.peek();
1095 switch (c)
1096 {
1097 case ']':
1098 source.next();
1099 switch (size)
1100 {
1101 case 0:
1102 list = Collections.emptyList();
1103 break;
1104 case 1:
1105 list = Collections.singletonList(item);
1106 break;
1107 default:
1108 break;
1109 }
1110 return getArrayConverter().apply(list);
1111
1112 case ',':
1113 if (comma)
1114 throw new IllegalStateException();
1115 comma = true;
1116 source.next();
1117 break;
1118
1119 default:
1120 if (Character.isWhitespace(c))
1121 {
1122 source.next();
1123 }
1124 else
1125 {
1126 comma = false;
1127 if (size++ == 0)
1128 {
1129 item = contextForArray().parse(source);
1130 }
1131 else if (list == null)
1132 {
1133 list = new ArrayList<>();
1134 list.add(item);
1135 item = contextForArray().parse(source);
1136 list.add(item);
1137 item = null;
1138 }
1139 else
1140 {
1141 item = contextForArray().parse(source);
1142 list.add(item);
1143 item = null;
1144 }
1145 }
1146 break;
1147 }
1148 }
1149
1150 throw new IllegalStateException("unexpected end of array");
1151 }
1152
1153 protected String parseString(Source source)
1154 {
1155 if (source.next() != '"')
1156 throw new IllegalStateException();
1157
1158 boolean escape = false;
1159
1160 StringBuilder b = null;
1161 final char[] scratch = source.scratchBuffer();
1162
1163 if (scratch != null)
1164 {
1165 int i = 0;
1166 while (source.hasNext())
1167 {
1168 if (i >= scratch.length)
1169 {
1170 // we have filled the scratch buffer, so we must
1171 // use the StringBuffer for a large string
1172 b = new StringBuilder(scratch.length * 2);
1173 b.append(scratch, 0, i);
1174 break;
1175 }
1176
1177 char c = source.next();
1178
1179 if (escape)
1180 {
1181 escape = false;
1182 switch (c)
1183 {
1184 case '"':
1185 scratch[i++] = '"';
1186 break;
1187 case '\\':
1188 scratch[i++] = '\\';
1189 break;
1190 case '/':
1191 scratch[i++] = '/';
1192 break;
1193 case 'b':
1194 scratch[i++] = '\b';
1195 break;
1196 case 'f':
1197 scratch[i++] = '\f';
1198 break;
1199 case 'n':
1200 scratch[i++] = '\n';
1201 break;
1202 case 'r':
1203 scratch[i++] = '\r';
1204 break;
1205 case 't':
1206 scratch[i++] = '\t';
1207 break;
1208 case 'u':
1209 char uc = (char)((TypeUtil.convertHexDigit((byte)source.next()) << 12) + (TypeUtil.convertHexDigit((byte)source.next()) << 8) +
1210 (TypeUtil.convertHexDigit((byte)source.next()) << 4) + (TypeUtil.convertHexDigit((byte)source.next())));
1211 scratch[i++] = uc;
1212 break;
1213 default:
1214 scratch[i++] = c;
1215 }
1216 }
1217 else if (c == '\\')
1218 {
1219 escape = true;
1220 }
1221 else if (c == '\"')
1222 {
1223 // Return string that fits within scratch buffer
1224 return toString(scratch, 0, i);
1225 }
1226 else
1227 {
1228 scratch[i++] = c;
1229 }
1230 }
1231
1232 // Missing end quote, but return string anyway ?
1233 if (b == null)
1234 return toString(scratch, 0, i);
1235 }
1236 else
1237 b = new StringBuilder(getStringBufferSize());
1238
1239 // parse large string into string buffer
1240 final StringBuilder builder = b;
1241 while (source.hasNext())
1242 {
1243 char c = source.next();
1244
1245 if (escape)
1246 {
1247 escape = false;
1248 switch (c)
1249 {
1250 case '"':
1251 builder.append('"');
1252 break;
1253 case '\\':
1254 builder.append('\\');
1255 break;
1256 case '/':
1257 builder.append('/');
1258 break;
1259 case 'b':
1260 builder.append('\b');
1261 break;
1262 case 'f':
1263 builder.append('\f');
1264 break;
1265 case 'n':
1266 builder.append('\n');
1267 break;
1268 case 'r':
1269 builder.append('\r');
1270 break;
1271 case 't':
1272 builder.append('\t');
1273 break;
1274 case 'u':
1275 char uc = (char)((TypeUtil.convertHexDigit((byte)source.next()) << 12) + (TypeUtil.convertHexDigit((byte)source.next()) << 8) +
1276 (TypeUtil.convertHexDigit((byte)source.next()) << 4) + (TypeUtil.convertHexDigit((byte)source.next())));
1277 builder.append(uc);
1278 break;
1279 default:
1280 builder.append(c);
1281 }
1282 }
1283 else if (c == '\\')
1284 {
1285 escape = true;
1286 }
1287 else if (c == '\"')
1288 {
1289 break;
1290 }
1291 else
1292 {
1293 builder.append(c);
1294 }
1295 }
1296 return builder.toString();
1297 }
1298
1299 public Number parseNumber(Source source)
1300 {
1301 boolean minus = false;
1302 long number = 0;
1303 StringBuilder buffer = null;
1304
1305 longLoop:
1306 while (source.hasNext())
1307 {
1308 char c = source.peek();
1309 switch (c)
1310 {
1311 case '0':
1312 case '1':
1313 case '2':
1314 case '3':
1315 case '4':
1316 case '5':
1317 case '6':
1318 case '7':
1319 case '8':
1320 case '9':
1321 number = number * 10 + (c - '0');
1322 source.next();
1323 break;
1324
1325 case '-':
1326 case '+':
1327 if (number != 0)
1328 throw new IllegalStateException("bad number");
1329 minus = true;
1330 source.next();
1331 break;
1332
1333 case '.':
1334 case 'e':
1335 case 'E':
1336 buffer = new StringBuilder(16);
1337 if (minus)
1338 buffer.append('-');
1339 buffer.append(number);
1340 buffer.append(c);
1341 source.next();
1342 break longLoop;
1343
1344 default:
1345 break longLoop;
1346 }
1347 }
1348
1349 if (buffer == null)
1350 return minus ? -1 * number : number;
1351
1352 doubleLoop:
1353 while (source.hasNext())
1354 {
1355 char c = source.peek();
1356 switch (c)
1357 {
1358 case '0':
1359 case '1':
1360 case '2':
1361 case '3':
1362 case '4':
1363 case '5':
1364 case '6':
1365 case '7':
1366 case '8':
1367 case '9':
1368 case '-':
1369 case '.':
1370 case '+':
1371 case 'e':
1372 case 'E':
1373 buffer.append(c);
1374 source.next();
1375 break;
1376
1377 default:
1378 break doubleLoop;
1379 }
1380 }
1381 return Double.valueOf(buffer.toString());
1382 }
1383
1384 protected void seekTo(char seek, Source source)
1385 {
1386 while (source.hasNext())
1387 {
1388 char c = source.peek();
1389 if (c == seek)
1390 return;
1391
1392 if (!Character.isWhitespace(c))
1393 throw new IllegalStateException("Unexpected '" + c + " while seeking '" + seek + "'");
1394 source.next();
1395 }
1396
1397 throw new IllegalStateException("Expected '" + seek + "'");
1398 }
1399
1400 protected char seekTo(String seek, Source source)
1401 {
1402 while (source.hasNext())
1403 {
1404 char c = source.peek();
1405 if (seek.indexOf(c) >= 0)
1406 {
1407 return c;
1408 }
1409
1410 if (!Character.isWhitespace(c))
1411 throw new IllegalStateException("Unexpected '" + c + "' while seeking one of '" + seek + "'");
1412 source.next();
1413 }
1414
1415 throw new IllegalStateException("Expected one of '" + seek + "'");
1416 }
1417
1418 protected static void complete(String seek, Source source)
1419 {
1420 int i = 0;
1421 while (source.hasNext() && i < seek.length())
1422 {
1423 char c = source.next();
1424 if (c != seek.charAt(i++))
1425 throw new IllegalStateException("Unexpected '" + c + " while seeking \"" + seek + "\"");
1426 }
1427
1428 if (i < seek.length())
1429 throw new IllegalStateException("Expected \"" + seek + "\"");
1430 }
1431
1432 private final class ConvertableOutput implements Output
1433 {
1434 private final Appendable _buffer;
1435 char c = '{';
1436
1437 private ConvertableOutput(Appendable buffer)
1438 {
1439 _buffer = buffer;
1440 }
1441
1442 public void complete()
1443 {
1444 try
1445 {
1446 if (c == '{')
1447 _buffer.append("{}");
1448 else if (c != 0)
1449 _buffer.append("}");
1450 }
1451 catch (IOException e)
1452 {
1453 throw new RuntimeException(e);
1454 }
1455 }
1456
1457 @Override
1458 public void add(Object obj)
1459 {
1460 if (c == 0)
1461 throw new IllegalStateException();
1462 append(_buffer, obj);
1463 c = 0;
1464 }
1465
1466 @Override
1467 public void addClass(Class type)
1468 {
1469 try
1470 {
1471 if (c == 0)
1472 throw new IllegalStateException();
1473 _buffer.append(c);
1474 _buffer.append("\"class\":");
1475 append(_buffer, type.getName());
1476 c = ',';
1477 }
1478 catch (IOException e)
1479 {
1480 throw new RuntimeException(e);
1481 }
1482 }
1483
1484 @Override
1485 public void add(String name, Object value)
1486 {
1487 try
1488 {
1489 if (c == 0)
1490 throw new IllegalStateException();
1491 _buffer.append(c);
1492 quotedEscape(_buffer, name);
1493 _buffer.append(':');
1494 append(_buffer, value);
1495 c = ',';
1496 }
1497 catch (IOException e)
1498 {
1499 throw new RuntimeException(e);
1500 }
1501 }
1502
1503 @Override
1504 public void add(String name, double value)
1505 {
1506 try
1507 {
1508 if (c == 0)
1509 throw new IllegalStateException();
1510 _buffer.append(c);
1511 quotedEscape(_buffer, name);
1512 _buffer.append(':');
1513 appendNumber(_buffer, value);
1514 c = ',';
1515 }
1516 catch (IOException e)
1517 {
1518 throw new RuntimeException(e);
1519 }
1520 }
1521
1522 @Override
1523 public void add(String name, long value)
1524 {
1525 try
1526 {
1527 if (c == 0)
1528 throw new IllegalStateException();
1529 _buffer.append(c);
1530 quotedEscape(_buffer, name);
1531 _buffer.append(':');
1532 appendNumber(_buffer, value);
1533 c = ',';
1534 }
1535 catch (IOException e)
1536 {
1537 throw new RuntimeException(e);
1538 }
1539 }
1540
1541 @Override
1542 public void add(String name, boolean value)
1543 {
1544 try
1545 {
1546 if (c == 0)
1547 throw new IllegalStateException();
1548 _buffer.append(c);
1549 quotedEscape(_buffer, name);
1550 _buffer.append(':');
1551 appendBoolean(_buffer, value ? Boolean.TRUE : Boolean.FALSE);
1552 c = ',';
1553 }
1554 catch (IOException e)
1555 {
1556 throw new RuntimeException(e);
1557 }
1558 }
1559 }
1560
1561 public interface Source
1562 {
1563 boolean hasNext();
1564
1565 char next();
1566
1567 char peek();
1568
1569 char[] scratchBuffer();
1570 }
1571
1572 public static class StringSource implements Source
1573 {
1574 private final String string;
1575 private int index;
1576 private char[] scratch;
1577
1578 public StringSource(String s)
1579 {
1580 string = s;
1581 }
1582
1583 @Override
1584 public boolean hasNext()
1585 {
1586 if (index < string.length())
1587 return true;
1588 scratch = null;
1589 return false;
1590 }
1591
1592 @Override
1593 public char next()
1594 {
1595 return string.charAt(index++);
1596 }
1597
1598 @Override
1599 public char peek()
1600 {
1601 return string.charAt(index);
1602 }
1603
1604 @Override
1605 public String toString()
1606 {
1607 return string.substring(0, index) + "|||" + string.substring(index);
1608 }
1609
1610 @Override
1611 public char[] scratchBuffer()
1612 {
1613 if (scratch == null)
1614 scratch = new char[string.length()];
1615 return scratch;
1616 }
1617 }
1618
1619 public static class ReaderSource implements Source
1620 {
1621 private Reader _reader;
1622 private int _next = -1;
1623 private char[] scratch;
1624
1625 public ReaderSource(Reader r)
1626 {
1627 _reader = r;
1628 }
1629
1630 public void setReader(Reader reader)
1631 {
1632 _reader = reader;
1633 _next = -1;
1634 }
1635
1636 @Override
1637 public boolean hasNext()
1638 {
1639 getNext();
1640 if (_next < 0)
1641 {
1642 scratch = null;
1643 return false;
1644 }
1645 return true;
1646 }
1647
1648 @Override
1649 public char next()
1650 {
1651 getNext();
1652 char c = (char)_next;
1653 _next = -1;
1654 return c;
1655 }
1656
1657 @Override
1658 public char peek()
1659 {
1660 getNext();
1661 return (char)_next;
1662 }
1663
1664 private void getNext()
1665 {
1666 if (_next < 0)
1667 {
1668 try
1669 {
1670 _next = _reader.read();
1671 }
1672 catch (IOException e)
1673 {
1674 throw new RuntimeException(e);
1675 }
1676 }
1677 }
1678
1679 @Override
1680 public char[] scratchBuffer()
1681 {
1682 if (scratch == null)
1683 scratch = new char[1024];
1684 return scratch;
1685 }
1686 }
1687
1688 /**
1689 * JSON Output class for use by {@link Convertible}.
1690 */
1691 public interface Output
1692 {
1693 void addClass(Class c);
1694
1695 void add(Object obj);
1696
1697 void add(String name, Object value);
1698
1699 void add(String name, double value);
1700
1701 void add(String name, long value);
1702
1703 void add(String name, boolean value);
1704 }
1705
1706 /**
1707 * JSON Convertible object. Object can implement this interface in a similar
1708 * way to the {@link Externalizable} interface is used to allow classes to
1709 * provide their own serialization mechanism.
1710 * <p>
1711 * A JSON.Convertible object may be written to a JSONObject or initialized
1712 * from a Map of field names to values.
1713 * <p>
1714 * If the JSON is to be convertible back to an Object, then the method
1715 * {@link Output#addClass(Class)} must be called from within toJSON()
1716 */
1717 public interface Convertible
1718 {
1719 void toJSON(Output out);
1720
1721 void fromJSON(Map object);
1722 }
1723
1724 /**
1725 * Static JSON Convertor.
1726 * <p>
1727 * may be implemented to provide static convertors for objects that may be
1728 * registered with
1729 * {@link JSON#registerConvertor(Class, org.eclipse.jetty.util.ajax.JSON.Convertor)}
1730 * . These convertors are looked up by class, interface and super class by
1731 * {@link JSON#getConvertor(Class)}. Convertors should be used when the
1732 * classes to be converted cannot implement {@link Convertible} or
1733 * {@link Generator}.
1734 */
1735 public interface Convertor
1736 {
1737 void toJSON(Object obj, Output out);
1738
1739 Object fromJSON(Map object);
1740 }
1741
1742 /**
1743 * JSON Generator. A class that can add it's JSON representation directly to
1744 * a StringBuffer. This is useful for object instances that are frequently
1745 * converted and wish to avoid multiple Conversions
1746 */
1747 public interface Generator
1748 {
1749 void addJSON(Appendable buffer);
1750 }
1751
1752 /**
1753 * A Literal JSON generator A utility instance of {@link JSON.Generator}
1754 * that holds a pre-generated string on JSON text.
1755 */
1756 public static class Literal implements Generator
1757 {
1758 private final String _json;
1759
1760 /**
1761 * Construct a literal JSON instance for use by
1762 * {@link JSON#toString(Object)}. If {@link Logger#isDebugEnabled()} is
1763 * true, the JSON will be parsed to check validity
1764 *
1765 * @param json A literal JSON string.
1766 */
1767 public Literal(String json)
1768 {
1769 if (LOG.isDebugEnabled()) // TODO: Make this a configurable option on JSON instead!
1770 parse(json);
1771 _json = json;
1772 }
1773
1774 @Override
1775 public String toString()
1776 {
1777 return _json;
1778 }
1779
1780 @Override
1781 public void addJSON(Appendable buffer)
1782 {
1783 try
1784 {
1785 buffer.append(_json);
1786 }
1787 catch (IOException e)
1788 {
1789 throw new RuntimeException(e);
1790 }
1791 }
1792 }
1793 }