Debian Codegraph @

jetty-util-ajax/src/test/java/org/eclipse/jetty/util/ajax/AsyncJSONTest.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.Collections;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.function.Function;
28
29 import org.hamcrest.Matchers;
30 import org.junit.jupiter.api.Test;
31 import org.junit.jupiter.params.ParameterizedTest;
32 import org.junit.jupiter.params.provider.MethodSource;
33 import org.junit.jupiter.params.provider.ValueSource;
34
35 import static java.nio.charset.StandardCharsets.UTF_8;
36 import static org.hamcrest.MatcherAssert.assertThat;
37 import static org.junit.jupiter.api.Assertions.assertEquals;
38 import static org.junit.jupiter.api.Assertions.assertFalse;
39 import static org.junit.jupiter.api.Assertions.assertNotNull;
40 import static org.junit.jupiter.api.Assertions.assertSame;
41 import static org.junit.jupiter.api.Assertions.assertThrows;
42 import static org.junit.jupiter.api.Assertions.assertTrue;
43
44 public class AsyncJSONTest
45 {
46 private static AsyncJSON newAsyncJSON()
47 {
48 AsyncJSON.Factory factory = new AsyncJSON.Factory();
49 factory.setDetailedParseException(true);
50 return factory.newAsyncJSON();
51 }
52
53 @ParameterizedTest
54 @ValueSource(strings = {"|", "}", "]", "{]", "[}", "+", ".", "{} []"})
55 public void testParseInvalidJSON(String json)
56 {
57 byte[] bytes = json.getBytes(UTF_8);
58 AsyncJSON parser = newAsyncJSON();
59
60 // Parse the whole input.
61 assertThrows(IllegalArgumentException.class, () -> parser.parse(bytes));
62 assertTrue(parser.isEmpty());
63
64 // Parse byte by byte.
65 assertThrows(IllegalArgumentException.class, () ->
66 {
67 for (byte b : bytes)
68 {
69 parser.parse(new byte[]{b});
70 }
71 });
72 assertTrue(parser.isEmpty());
73 }
74
75 @ParameterizedTest(name = "[{index}] ''{0}'' -> ''{1}''")
76 @MethodSource("validStrings")
77 public void testParseString(String string, String expected)
78 {
79 String json = "\"${value}\"".replace("${value}", string);
80 byte[] bytes = json.getBytes(UTF_8);
81 AsyncJSON parser = newAsyncJSON();
82
83 // Parse the whole input.
84 assertTrue(parser.parse(bytes));
85 assertEquals(expected, parser.complete());
86 assertTrue(parser.isEmpty());
87
88 // Parse byte by byte.
89 for (int i = 0; i < bytes.length; ++i)
90 {
91 byte b = bytes[i];
92 if (i == bytes.length - 1)
93 assertTrue(parser.parse(new byte[]{b}));
94 else
95 assertFalse(parser.parse(new byte[]{b}));
96 }
97 assertEquals(expected, parser.complete());
98 assertTrue(parser.isEmpty());
99 }
100
101 public static List<Object[]> validStrings()
102 {
103 List<Object[]> result = new ArrayList<>();
104 result.add(new Object[]{"", ""});
105 result.add(new Object[]{" \t\r\n", " \t\r\n"});
106 result.add(new Object[]{"\u20AC", "\u20AC"}); // euro symbol
107 result.add(new Object[]{"\\u20AC", "\u20AC"}); // euro symbol
108 result.add(new Object[]{"/foo", "/foo"});
109 result.add(new Object[]{"123E+01", "123E+01"});
110 result.add(new Object[]{"A\\u20AC/foo\\t\\n", "A\u20AC/foo\t\n"}); // euro symbol
111 result.add(new Object[]{" ABC ", " ABC "});
112 return result;
113 }
114
115 @ParameterizedTest
116 @ValueSource(strings = {"\\u", "\\u0", "\\x"})
117 public void testParseInvalidString(String value)
118 {
119 String json = "\"${value}\"".replace("${value}", value);
120 byte[] bytes = json.getBytes(UTF_8);
121 AsyncJSON parser = newAsyncJSON();
122
123 // Parse the whole input.
124 assertThrows(IllegalArgumentException.class, () -> parser.parse(bytes));
125 assertTrue(parser.isEmpty());
126
127 // Parse byte by byte.
128 assertThrows(IllegalArgumentException.class, () ->
129 {
130 for (byte b : bytes)
131 {
132 parser.parse(new byte[]{b});
133 }
134 });
135 assertTrue(parser.isEmpty());
136 }
137
138 @ParameterizedTest(name = "[{index}] {0} -> {1}")
139 @MethodSource("validArrays")
140 public void testParseArray(String json, List<?> expected)
141 {
142 byte[] bytes = json.getBytes(UTF_8);
143 AsyncJSON parser = newAsyncJSON();
144
145 // Parse the whole input.
146 assertTrue(parser.parse(bytes));
147 assertEquals(expected, parser.complete());
148 assertTrue(parser.isEmpty());
149 ByteBuffer buffer = ByteBuffer.wrap(bytes);
150 assertTrue(parser.parse(buffer));
151 assertFalse(buffer.hasRemaining());
152 assertEquals(expected, parser.complete());
153 assertTrue(parser.isEmpty());
154
155 // Parse byte by byte.
156 for (byte b : bytes)
157 {
158 parser.parse(new byte[]{b});
159 }
160 assertEquals(expected, parser.complete());
161 assertTrue(parser.isEmpty());
162 }
163
164 public static List<Object[]> validArrays()
165 {
166 List<Object[]> result = new ArrayList<>();
167
168 List<Object> expected = Collections.emptyList();
169 result.add(new Object[]{"[]", expected});
170 result.add(new Object[]{"[] \n", expected});
171
172 expected = new ArrayList<>();
173 expected.add(Collections.emptyList());
174 result.add(new Object[]{"[[]]", expected});
175
176 expected = new ArrayList<>();
177 expected.add("first");
178 expected.add(5D);
179 expected.add(null);
180 expected.add(true);
181 expected.add(false);
182 expected.add(new HashMap<>());
183 HashMap<String, Object> last = new HashMap<>();
184 last.put("a", new ArrayList<>());
185 expected.add(last);
186 result.add(new Object[]{"[\"first\", 5E+0, null, true, false, {}, {\"a\":[]}]", expected});
187
188 return result;
189 }
190
191 @ParameterizedTest
192 @ValueSource(strings = {"[", "]", "[[,]", " [ 1,2,[ "})
193 public void testParseInvalidArray(String json)
194 {
195 byte[] bytes = json.getBytes(UTF_8);
196 AsyncJSON parser = newAsyncJSON();
197
198 // Parse the whole input.
199 assertThrows(IllegalArgumentException.class, () ->
200 {
201 parser.parse(bytes);
202 parser.complete();
203 });
204 assertTrue(parser.isEmpty());
205
206 // Parse byte by byte.
207 assertThrows(IllegalArgumentException.class, () ->
208 {
209 for (byte b : bytes)
210 {
211 parser.parse(new byte[]{b});
212 }
213 parser.complete();
214 });
215 assertTrue(parser.isEmpty());
216 }
217
218 @ParameterizedTest(name = "[{index}] {0} -> {1}")
219 @MethodSource("validObjects")
220 public void testParseObject(String json, Object expected)
221 {
222 byte[] bytes = json.getBytes(UTF_8);
223 AsyncJSON parser = newAsyncJSON();
224
225 // Parse the whole input.
226 assertTrue(parser.parse(bytes));
227 assertEquals(expected, parser.complete());
228 assertTrue(parser.isEmpty());
229
230 // Parse byte by byte.
231 for (int i = 0; i < bytes.length; ++i)
232 {
233 byte b = bytes[i];
234 if (i == bytes.length - 1)
235 {
236 assertTrue(parser.parse(new byte[]{b}));
237 }
238 else
239 {
240 assertFalse(parser.parse(new byte[]{b}));
241 }
242 }
243 assertEquals(expected, parser.complete());
244 assertTrue(parser.isEmpty());
245 }
246
247 public static List<Object[]> validObjects()
248 {
249 List<Object[]> result = new ArrayList<>();
250
251 HashMap<String, Object> expected = new HashMap<>();
252 result.add(new Object[]{"{}", expected});
253
254 expected = new HashMap<>();
255 expected.put("", 0L);
256 result.add(new Object[]{"{\"\":0}", expected});
257
258 expected = new HashMap<>();
259 expected.put("name", "value");
260 result.add(new Object[]{"{ \"name\": \"value\" }", expected});
261
262 expected = new HashMap<>();
263 expected.put("name", null);
264 expected.put("valid", true);
265 expected.put("secure", false);
266 expected.put("value", 42L);
267 result.add(new Object[]{
268 "{, \"name\": null, \"valid\": true\n , \"secure\": false\r\n,\n \"value\":42, }", expected
269 });
270
271 return result;
272 }
273
274 @ParameterizedTest
275 @ValueSource(strings = {"{", "}", "{{,}", "{:\"s\"}", "{[]:0}", "{1:0}", " {\": 0} ", "{\"a: \"b\"}"})
276 public void testParseInvalidObject(String json)
277 {
278 byte[] bytes = json.getBytes(UTF_8);
279 AsyncJSON parser = newAsyncJSON();
280
281 // Parse the whole input.
282 assertThrows(IllegalArgumentException.class, () ->
283 {
284 parser.parse(bytes);
285 parser.complete();
286 });
287 assertTrue(parser.isEmpty());
288
289 // Parse byte by byte.
290 assertThrows(IllegalArgumentException.class, () ->
291 {
292 for (byte b : bytes)
293 {
294 parser.parse(new byte[]{b});
295 }
296 parser.complete();
297 });
298 assertTrue(parser.isEmpty());
299 }
300
301 @ParameterizedTest(name = "[{index}] {0} -> {1}")
302 @MethodSource("validNumbers")
303 public void testParseNumber(String json, Number expected)
304 {
305 byte[] bytes = json.getBytes(UTF_8);
306 AsyncJSON parser = newAsyncJSON();
307
308 // Parse the whole input.
309 parser.parse(bytes);
310 assertEquals(expected, parser.complete());
311 assertTrue(parser.isEmpty());
312 ByteBuffer buffer = ByteBuffer.wrap(bytes);
313 parser.parse(buffer);
314 assertEquals(expected, parser.complete());
315 assertFalse(buffer.hasRemaining());
316 assertTrue(parser.isEmpty());
317
318 // Parse byte by byte.
319 for (byte b : bytes)
320 {
321 parser.parse(new byte[]{b});
322 }
323 assertEquals(expected, parser.complete());
324 assertTrue(parser.isEmpty());
325 }
326
327 public static List<Object[]> validNumbers()
328 {
329 List<Object[]> result = new ArrayList<>();
330
331 result.add(new Object[]{"0", 0L});
332 result.add(new Object[]{"-0", -0L});
333 result.add(new Object[]{"13\n", 13L});
334 result.add(new Object[]{"-42", -42L});
335 result.add(new Object[]{"123.456", 123.456D});
336 result.add(new Object[]{"-234.567", -234.567D});
337 result.add(new Object[]{"9e0", 9D});
338 result.add(new Object[]{"8E+1\t", 80D});
339 result.add(new Object[]{"-7E-2 ", -0.07D});
340 result.add(new Object[]{"70.5E-1", 7.05D});
341
342 return result;
343 }
344
345 @ParameterizedTest
346 @ValueSource(strings = {"--", "--1", ".5", "e0", "1a1", "3-7", "1+2", "1e0e1", "1.2.3"})
347 public void testParseInvalidNumber(String json)
348 {
349 byte[] bytes = json.getBytes(UTF_8);
350 AsyncJSON parser = newAsyncJSON();
351
352 // Parse the whole input.
353 assertThrows(IllegalArgumentException.class, () ->
354 {
355 parser.parse(bytes);
356 parser.complete();
357 });
358 assertTrue(parser.isEmpty());
359
360 // Parse byte by byte.
361 assertThrows(IllegalArgumentException.class, () ->
362 {
363 for (byte b : bytes)
364 {
365 parser.parse(new byte[]{b});
366 }
367 parser.complete();
368 });
369 assertTrue(parser.isEmpty());
370 }
371
372 @Test
373 public void testParseObjectWithConvertor()
374 {
375 AsyncJSON.Factory factory = new AsyncJSON.Factory();
376 CustomConvertor convertor = new CustomConvertor();
377 factory.putConvertor(CustomConvertor.class.getName(), convertor);
378
379 String json = "{" +
380 "\"f1\": {\"class\":\"" + CustomConvertible.class.getName() + "\", \"field\": \"value\"}," +
381 "\"f2\": {\"class\":\"" + CustomConvertor.class.getName() + "\"}" +
382 "}";
383
384 AsyncJSON parser = factory.newAsyncJSON();
385 assertTrue(parser.parse(UTF_8.encode(json)));
386 Map<String, Object> result = parser.complete();
387
388 Object value1 = result.get("f1");
389 assertTrue(value1 instanceof CustomConvertible);
390 assertEquals("value", ((CustomConvertible)value1).field);
391 Object value2 = result.get("f2");
392 assertTrue(value2 instanceof CustomConvertor.Custom);
393
394 assertSame(convertor, factory.removeConvertor(CustomConvertor.class.getName()));
395 assertTrue(parser.parse(UTF_8.encode(json)));
396 result = parser.complete();
397
398 value1 = result.get("f1");
399 assertTrue(value1 instanceof CustomConvertible);
400 assertEquals("value", ((CustomConvertible)value1).field);
401 value2 = result.get("f2");
402 assertTrue(value2 instanceof Map);
403 @SuppressWarnings("unchecked")
404 Map<String, Object> map2 = (Map<String, Object>)value2;
405 assertEquals(CustomConvertor.class.getName(), map2.get("class"));
406 }
407
408 public static class CustomConvertible implements JSON.Convertible
409 {
410 private Object field;
411
412 @Override
413 public void toJSON(JSON.Output out)
414 {
415 }
416
417 @Override
418 public void fromJSON(Map map)
419 {
420 this.field = map.get("field");
421 }
422 }
423
424 public static class CustomConvertor implements JSON.Convertor
425 {
426 @Override
427 public void toJSON(Object obj, JSON.Output out)
428 {
429 }
430
431 @Override
432 public Object fromJSON(Map map)
433 {
434 return new Custom();
435 }
436
437 public static class Custom
438 {
439 }
440 }
441
442 @Test
443 public void testContext()
444 {
445 AsyncJSON.Factory factory = new AsyncJSON.Factory()
446 {
447 @Override
448 public AsyncJSON newAsyncJSON()
449 {
450 return new AsyncJSON(this)
451 {
452 @Override
453 protected Map<String, Object> newObject(Context context)
454 {
455 if (context.depth() == 1)
456 {
457 return new CustomMap();
458 }
459 return super.newObject(context);
460 }
461 };
462 }
463 };
464 AsyncJSON parser = factory.newAsyncJSON();
465
466 String json = "[{" +
467 "\"channel\": \"/meta/handshake\"," +
468 "\"version\": \"1.0\"," +
469 "\"supportedConnectionTypes\": [\"long-polling\"]," +
470 "\"advice\": {\"timeout\": 0}" +
471 "}]";
472
473 assertTrue(parser.parse(UTF_8.encode(json)));
474 List<CustomMap> messages = parser.complete();
475
476 for (CustomMap message : messages)
477 {
478 @SuppressWarnings("unchecked")
479 Map<String, Object> advice = (Map<String, Object>)message.get("advice");
480 assertFalse(advice instanceof CustomMap);
481 }
482 }
483
484 public static class CustomMap extends HashMap<String, Object>
485 {
486 }
487
488 @Test
489 public void testCaching()
490 {
491 AsyncJSON.Factory factory = new AsyncJSON.Factory();
492 String foo = "foo";
493 factory.cache(foo);
494 AsyncJSON parser = factory.newAsyncJSON();
495
496 String json = "{\"foo\": [\"foo\", \"foo\"]}";
497 parser.parse(UTF_8.encode(json));
498 Map<String, Object> object = parser.complete();
499
500 Map.Entry<String, Object> entry = object.entrySet().iterator().next();
501 assertSame(foo, entry.getKey());
502 @SuppressWarnings("unchecked")
503 List<String> array = (List<String>)entry.getValue();
504 for (String item : array)
505 {
506 assertSame(foo, item);
507 }
508 }
509
510 @Test
511 public void testEncodedCaching()
512 {
513 AsyncJSON.Factory factory = new AsyncJSON.Factory();
514 assertFalse(factory.cache("yèck"));
515 String foo = "foo\\yuck";
516 assertTrue(factory.cache(foo));
517 AsyncJSON parser = factory.newAsyncJSON();
518
519 String json = "{\"foo\\\\yuck\": [\"foo\\\\yuck\", \"foo\\\\yuck\"]}";
520 parser.parse(UTF_8.encode(json));
521 Map<String, Object> object = parser.complete();
522
523 Map.Entry<String, Object> entry = object.entrySet().iterator().next();
524 assertSame(foo, entry.getKey());
525 @SuppressWarnings("unchecked")
526 List<String> array = (List<String>)entry.getValue();
527 for (String item : array)
528 {
529 assertSame(foo, item);
530 }
531 }
532
533 @Test
534 public void testArrayConverter()
535 {
536 // Test root arrays.
537 testArrayConverter("[1]", Function.identity());
538
539 // Test non-root arrays.
540 testArrayConverter("{\"array\": [1]}", object ->
541 {
542 @SuppressWarnings("unchecked")
543 Map<String, Object> map = (Map<String, Object>)object;
544 return map.get("array");
545 });
546 }
547
548 private void testArrayConverter(String json, Function<Object, Object> extractor)
549 {
550 AsyncJSON.Factory factory = new AsyncJSON.Factory();
551 AsyncJSON async = factory.newAsyncJSON();
552 JSON sync = new JSON();
553
554 async.parse(UTF_8.encode(json));
555 Object result = extractor.apply(async.complete());
556 // AsyncJSON historically defaults to list.
557 assertThat(result, Matchers.instanceOf(List.class));
558 // JSON historically defaults to array.
559 result = extractor.apply(sync.parse(new JSON.StringSource(json)));
560 assertNotNull(result);
561 assertTrue(result.getClass().isArray(), json + " -> " + result);
562
563 // Configure AsyncJSON to return arrays.
564 factory.setArrayConverter(List::toArray);
565 async.parse(UTF_8.encode(json));
566 result = extractor.apply(async.complete());
567 assertNotNull(result);
568 assertTrue(result.getClass().isArray(), json + " -> " + result);
569
570 // Configure JSON to return lists.
571 sync.setArrayConverter(list -> list);
572 result = extractor.apply(sync.parse(new JSON.StringSource(json)));
573 assertThat(result, Matchers.instanceOf(List.class));
574 }
575 }