Debian Codegraph @

src/org/eclipse/parsson/JsonGeneratorImpl.java

raw symbols SCIP
1 /*
2 * Copyright (c) 2012, 2023 Oracle and/or its affiliates. All rights reserved.
3 *
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v. 2.0, which is available at
6 * http://www.eclipse.org/legal/epl-2.0.
7 *
8 * This Source Code may also be made available under the following Secondary
9 * Licenses when the conditions for such availability set forth in the
10 * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
11 * version 2 with the GNU Classpath Exception, which is available at
12 * https://www.gnu.org/software/classpath/license.html.
13 *
14 * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15 */
16
17 package org.eclipse.parsson;
18
19 import org.eclipse.parsson.api.BufferPool;
20
21 import jakarta.json.*;
22 import jakarta.json.stream.JsonGenerationException;
23 import jakarta.json.stream.JsonGenerator;
24 import java.io.*;
25 import java.math.BigDecimal;
26 import java.math.BigInteger;
27 import java.nio.charset.Charset;
28 import java.nio.charset.StandardCharsets;
29 import java.util.ArrayDeque;
30 import java.util.Deque;
31 import java.util.Map;
32
33 /**
34 * @author Jitendra Kotamraju
35 */
36 class JsonGeneratorImpl implements JsonGenerator {
37
38 private static final char[] INT_MIN_VALUE_CHARS = "-2147483648".toCharArray();
39 private static final int[] INT_CHARS_SIZE_TABLE = { 9, 99, 999, 9999, 99999,
40 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE };
41
42 private static final char [] DIGIT_TENS = {
43 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
44 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
45 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
46 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
47 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
48 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
49 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
50 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
51 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
52 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
53 } ;
54
55 private static final char [] DIGIT_ONES = {
56 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
57 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
58 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
59 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
60 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
61 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
62 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
63 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
64 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
65 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
66 } ;
67
68 /**
69 * All possible chars for representing a number as a String
70 */
71 private static final char[] DIGITS = {
72 '0' , '1' , '2' , '3' , '4' , '5' ,
73 '6' , '7' , '8' , '9'
74 };
75
76 private static enum Scope {
77 IN_NONE,
78 IN_OBJECT,
79 IN_FIELD,
80 IN_ARRAY
81 }
82
83 private final BufferPool bufferPool;
84 private final Writer writer;
85 private Context currentContext = new Context(Scope.IN_NONE);
86 private final Deque<Context> stack = new ArrayDeque<>();
87
88 // Using own buffering mechanism as JDK's BufferedWriter uses synchronized
89 // methods. Also, flushBuffer() is useful when you don't want to actually
90 // flush the underlying output source
91 private final char buf[]; // capacity >= INT_MIN_VALUE_CHARS.length
92 private int len = 0;
93 private boolean closed = false;
94
95 JsonGeneratorImpl(Writer writer, JsonContext jsonContext) {
96 this.bufferPool = jsonContext.bufferPool();
97 this.writer = writer;
98 this.buf = jsonContext.bufferPool().take();
99 }
100
101 JsonGeneratorImpl(OutputStream out, JsonContext jsonContext) {
102 this(out, StandardCharsets.UTF_8, jsonContext);
103 }
104
105 JsonGeneratorImpl(OutputStream out, Charset encoding, JsonContext jsonContext) {
106 this(new OutputStreamWriter(out, encoding), jsonContext);
107 }
108
109 @Override
110 public void flush() {
111 flushBuffer();
112 try {
113 writer.flush();
114 } catch (IOException ioe) {
115 throw new JsonException(JsonMessages.GENERATOR_FLUSH_IO_ERR(), ioe);
116 }
117 }
118
119 @Override
120 public JsonGenerator writeStartObject() {
121 if (currentContext.scope == Scope.IN_OBJECT) {
122 throw new JsonGenerationException(JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
123 }
124 if (currentContext.scope == Scope.IN_NONE && !currentContext.first) {
125 throw new JsonGenerationException(JsonMessages.GENERATOR_ILLEGAL_MULTIPLE_TEXT());
126 }
127 writeComma();
128 writeChar('{');
129 stack.push(currentContext);
130 currentContext = new Context(Scope.IN_OBJECT);
131 return this;
132 }
133
134 @Override
135 public JsonGenerator writeStartObject(String name) {
136 if (currentContext.scope != Scope.IN_OBJECT) {
137 throw new JsonGenerationException(
138 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
139 }
140 writeName(name);
141 writeChar('{');
142 stack.push(currentContext);
143 currentContext = new Context(Scope.IN_OBJECT);
144 return this;
145 }
146
147 private JsonGenerator writeName(String name) {
148 writeComma();
149 writeEscapedString(name);
150 writeColon();
151 return this;
152 }
153
154 @Override
155 public JsonGenerator write(String name, String fieldValue) {
156 write(name, (CharSequence) fieldValue);
157 return this;
158 }
159
160 @Override
161 public JsonGenerator write(String name, int value) {
162 if (currentContext.scope != Scope.IN_OBJECT) {
163 throw new JsonGenerationException(
164 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
165 }
166 writeName(name);
167 writeInt(value);
168 return this;
169 }
170
171 @Override
172 public JsonGenerator write(String name, long value) {
173 if (currentContext.scope != Scope.IN_OBJECT) {
174 throw new JsonGenerationException(
175 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
176 }
177 writeName(name);
178 writeString(String.valueOf(value));
179 return this;
180 }
181
182 @Override
183 public JsonGenerator write(String name, double value) {
184 if (currentContext.scope != Scope.IN_OBJECT) {
185 throw new JsonGenerationException(
186 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
187 }
188 if (Double.isInfinite(value) || Double.isNaN(value)) {
189 throw new NumberFormatException(JsonMessages.GENERATOR_DOUBLE_INFINITE_NAN());
190 }
191 writeName(name);
192 writeString(String.valueOf(value));
193 return this;
194 }
195
196 @Override
197 public JsonGenerator write(String name, BigInteger value) {
198 if (currentContext.scope != Scope.IN_OBJECT) {
199 throw new JsonGenerationException(
200 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
201 }
202 writeName(name);
203 writeString(String.valueOf(value));
204 return this;
205 }
206
207 @Override
208 public JsonGenerator write(String name, BigDecimal value) {
209 if (currentContext.scope != Scope.IN_OBJECT) {
210 throw new JsonGenerationException(
211 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
212 }
213 writeName(name);
214 writeString(String.valueOf(value));
215 return this;
216 }
217
218 @Override
219 public JsonGenerator write(String name, boolean value) {
220 if (currentContext.scope != Scope.IN_OBJECT) {
221 throw new JsonGenerationException(
222 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
223 }
224 writeName(name);
225 writeString(value? "true" : "false");
226 return this;
227 }
228
229 @Override
230 public JsonGenerator writeNull(String name) {
231 if (currentContext.scope != Scope.IN_OBJECT) {
232 throw new JsonGenerationException(
233 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
234 }
235 writeName(name);
236 writeString("null");
237 return this;
238 }
239
240 @Override
241 public JsonGenerator write(JsonValue value) {
242 checkContextForValue();
243
244 switch (value.getValueType()) {
245 case ARRAY:
246 JsonArray array = (JsonArray)value;
247 writeStartArray();
248 for(JsonValue child: array) {
249 write(child);
250 }
251 writeEnd();
252 break;
253 case OBJECT:
254 JsonObject object = (JsonObject)value;
255 writeStartObject();
256 for(Map.Entry<String, JsonValue> member: object.entrySet()) {
257 write(member.getKey(), member.getValue());
258 }
259 writeEnd();
260 break;
261 case STRING:
262 JsonString str = (JsonString)value;
263 write(str.getString());
264 break;
265 case NUMBER:
266 JsonNumber number = (JsonNumber)value;
267 writeValue(number.toString());
268 popFieldContext();
269 break;
270 case TRUE:
271 write(true);
272 break;
273 case FALSE:
274 write(false);
275 break;
276 case NULL:
277 writeNull();
278 break;
279 }
280
281 return this;
282 }
283
284 @Override
285 public JsonGenerator writeStartArray() {
286 if (currentContext.scope == Scope.IN_OBJECT) {
287 throw new JsonGenerationException(JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
288 }
289 if (currentContext.scope == Scope.IN_NONE && !currentContext.first) {
290 throw new JsonGenerationException(JsonMessages.GENERATOR_ILLEGAL_MULTIPLE_TEXT());
291 }
292 writeComma();
293 writeChar('[');
294 stack.push(currentContext);
295 currentContext = new Context(Scope.IN_ARRAY);
296 return this;
297 }
298
299 @Override
300 public JsonGenerator writeStartArray(String name) {
301 if (currentContext.scope != Scope.IN_OBJECT) {
302 throw new JsonGenerationException(
303 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
304 }
305 writeName(name);
306 writeChar('[');
307 stack.push(currentContext);
308 currentContext = new Context(Scope.IN_ARRAY);
309 return this;
310 }
311
312 @Override
313 public JsonGenerator write(String name, JsonValue value) {
314 if (currentContext.scope != Scope.IN_OBJECT) {
315 throw new JsonGenerationException(
316 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
317 }
318 switch (value.getValueType()) {
319 case ARRAY:
320 JsonArray array = (JsonArray)value;
321 writeStartArray(name);
322 for(JsonValue child: array) {
323 write(child);
324 }
325 writeEnd();
326 break;
327 case OBJECT:
328 JsonObject object = (JsonObject)value;
329 writeStartObject(name);
330 for(Map.Entry<String, JsonValue> member: object.entrySet()) {
331 write(member.getKey(), member.getValue());
332 }
333 writeEnd();
334 break;
335 case STRING:
336 JsonString str = (JsonString)value;
337 write(name, str.getChars());
338 break;
339 case NUMBER:
340 JsonNumber number = (JsonNumber)value;
341 writeValue(name, number.toString());
342 break;
343 case TRUE:
344 write(name, true);
345 break;
346 case FALSE:
347 write(name, false);
348 break;
349 case NULL:
350 writeNull(name);
351 break;
352 }
353 return this;
354 }
355
356 @Override
357 public JsonGenerator write(String value) {
358 checkContextForValue();
359 writeComma();
360 writeEscapedString(value);
361 popFieldContext();
362 return this;
363 }
364
365
366 @Override
367 public JsonGenerator write(int value) {
368 checkContextForValue();
369 writeComma();
370 writeInt(value);
371 popFieldContext();
372 return this;
373 }
374
375 @Override
376 public JsonGenerator write(long value) {
377 checkContextForValue();
378 writeValue(String.valueOf(value));
379 popFieldContext();
380 return this;
381 }
382
383 @Override
384 public JsonGenerator write(double value) {
385 checkContextForValue();
386 if (Double.isInfinite(value) || Double.isNaN(value)) {
387 throw new NumberFormatException(JsonMessages.GENERATOR_DOUBLE_INFINITE_NAN());
388 }
389 writeValue(String.valueOf(value));
390 popFieldContext();
391 return this;
392 }
393
394 @Override
395 public JsonGenerator write(BigInteger value) {
396 checkContextForValue();
397 writeValue(value.toString());
398 popFieldContext();
399 return this;
400 }
401
402 private void checkContextForValue() {
403 if ((!currentContext.first && currentContext.scope != Scope.IN_ARRAY && currentContext.scope != Scope.IN_FIELD)
404 || (currentContext.first && currentContext.scope == Scope.IN_OBJECT)) {
405 throw new JsonGenerationException(
406 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
407 }
408 }
409
410 @Override
411 public JsonGenerator write(BigDecimal value) {
412 checkContextForValue();
413 writeValue(value.toString());
414 popFieldContext();
415
416 return this;
417 }
418
419 private void popFieldContext() {
420 if (currentContext.scope == Scope.IN_FIELD) {
421 currentContext = stack.pop();
422 }
423 }
424
425 @Override
426 public JsonGenerator write(boolean value) {
427 checkContextForValue();
428 writeComma();
429 writeString(value ? "true" : "false");
430 popFieldContext();
431 return this;
432 }
433
434 @Override
435 public JsonGenerator writeNull() {
436 checkContextForValue();
437 writeComma();
438 writeString("null");
439 popFieldContext();
440 return this;
441 }
442
443 private void writeValue(String value) {
444 writeComma();
445 writeString(value);
446 }
447
448 private void writeValue(String name, String value) {
449 writeComma();
450 writeEscapedString(name);
451 writeColon();
452 writeString(value);
453 }
454
455 @Override
456 public JsonGenerator writeKey(String name) {
457 if (currentContext.scope != Scope.IN_OBJECT) {
458 throw new JsonGenerationException(
459 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
460 }
461 writeName(name);
462 stack.push(currentContext);
463 currentContext = new Context(Scope.IN_FIELD);
464 currentContext.first = false;
465 return this;
466 }
467
468 @Override
469 public JsonGenerator writeEnd() {
470 if (currentContext.scope == Scope.IN_NONE) {
471 throw new JsonGenerationException("writeEnd() cannot be called in no context");
472 }
473 writeChar(currentContext.scope == Scope.IN_ARRAY ? ']' : '}');
474 currentContext = stack.pop();
475 popFieldContext();
476 return this;
477 }
478
479 void write(String name, CharSequence fieldValue) {
480 if (currentContext.scope != Scope.IN_OBJECT) {
481 throw new JsonGenerationException(
482 JsonMessages.GENERATOR_ILLEGAL_METHOD(currentContext.scope));
483 }
484 writeName(name);
485 writeEscapedString(fieldValue);
486 }
487
488 protected void writeComma() {
489 if (isCommaAllowed()) {
490 writeChar(',');
491 }
492 currentContext.first = false;
493 }
494
495 protected boolean inNone() {
496 return currentContext.scope == Scope.IN_NONE;
497 }
498
499 boolean isCommaAllowed() {
500 return !currentContext.first && currentContext.scope != Scope.IN_FIELD;
501 }
502
503 protected void writeColon() {
504 writeChar(':');
505 }
506
507 private static class Context {
508 boolean first = true;
509 final Scope scope;
510
511 Context(Scope scope) {
512 this.scope = scope;
513 }
514
515 }
516
517 @Override
518 public void close() {
519 if (!closed) {
520 if (currentContext.scope != Scope.IN_NONE || currentContext.first) {
521 throw new JsonGenerationException(JsonMessages.GENERATOR_INCOMPLETE_JSON());
522 }
523 flushBuffer();
524 try {
525 writer.close();
526 } catch (IOException ioe) {
527 throw new JsonException(JsonMessages.GENERATOR_CLOSE_IO_ERR(), ioe);
528 }
529 bufferPool.recycle(buf);
530 closed = true;
531 }
532 }
533
534 // begin, end-1 indexes represent characters that need not
535 // be escaped
536 //
537 // XXXssssssssssssXXXXXXXXXXXXXXXXXXXXXXrrrrrrrrrrrrrrXXXXXX
538 // ^ ^ ^ ^
539 // | | | |
540 // begin end begin end
541 void writeEscapedString(CharSequence string) {
542 writeChar('"');
543 int len = string.length();
544 for(int i = 0; i < len; i++) {
545 int begin = i, end = i;
546 char c = string.charAt(i);
547 // find all the characters that need not be escaped
548 // unescaped = %x20-21 | %x23-5B | %x5D-10FFFF
549 while(c >= 0x20 && c <= 0x10ffff && c != 0x22 && c != 0x5c) {
550 i++; end = i;
551 if (i < len) {
552 c = string.charAt(i);
553 } else {
554 break;
555 }
556 }
557 // Write characters without escaping
558 if (begin < end) {
559 writeString(string, begin, end);
560 if (i == len) {
561 break;
562 }
563 }
564
565 switch (c) {
566 case '"':
567 case '\\':
568 writeChar('\\'); writeChar(c);
569 break;
570 case '\b':
571 writeChar('\\'); writeChar('b');
572 break;
573 case '\f':
574 writeChar('\\'); writeChar('f');
575 break;
576 case '\n':
577 writeChar('\\'); writeChar('n');
578 break;
579 case '\r':
580 writeChar('\\'); writeChar('r');
581 break;
582 case '\t':
583 writeChar('\\'); writeChar('t');
584 break;
585 default:
586 String hex = "000" + Integer.toHexString(c);
587 writeString("\\u" + hex.substring(hex.length() - 4));
588 }
589 }
590 writeChar('"');
591 }
592
593 void writeString(CharSequence str, int begin, int end) {
594 while (begin < end) { // source begin and end indexes
595 int no = Math.min(buf.length - len, end - begin);
596 if (str instanceof String) {
597 ((String)str).getChars(begin, begin + no, buf, len);
598 } else {
599 // if passed a non-string, assume this is deliberate
600 getChars(str, begin, begin + no, buf, len);
601 }
602 begin += no; // Increment source index
603 len += no; // Increment dest index
604 if (len >= buf.length) {
605 flushBuffer();
606 }
607 }
608 }
609
610 void writeString(CharSequence str) {
611 writeString(str, 0, str.length());
612 }
613
614 void writeChar(char c) {
615 if (len >= buf.length) {
616 flushBuffer();
617 }
618 buf[len++] = c;
619 }
620
621 // Not using Integer.toString() since it creates intermediary String
622 // Also, we want the chars to be copied to our buffer directly
623 void writeInt(int num) {
624 int size;
625 if (num == Integer.MIN_VALUE) {
626 size = INT_MIN_VALUE_CHARS.length;
627 } else {
628 size = (num < 0) ? stringSize(-num) + 1 : stringSize(num);
629 }
630 if (len+size >= buf.length) {
631 flushBuffer();
632 }
633 if (num == Integer.MIN_VALUE) {
634 System.arraycopy(INT_MIN_VALUE_CHARS, 0, buf, len, size);
635 } else {
636 fillIntChars(num, buf, len+size);
637 }
638 len += size;
639 }
640
641 // flushBuffer writes the buffered contents to writer. But incase of
642 // byte stream, an OuputStreamWriter is created and that buffers too.
643 // We may need to call OutputStreamWriter#flushBuffer() using
644 // reflection if that is really required (commented out below)
645 void flushBuffer() {
646 try {
647 if (len > 0) {
648 writer.write(buf, 0, len);
649 len = 0;
650 }
651 } catch (IOException ioe) {
652 throw new JsonException(JsonMessages.GENERATOR_WRITE_IO_ERR(), ioe);
653 }
654 }
655
656 // private static final Method flushBufferMethod;
657 // static {
658 // Method m = null;
659 // try {
660 // m = OutputStreamWriter.class.getDeclaredMethod("flushBuffer");
661 // m.setAccessible(true);
662 // } catch (Exception e) {
663 // // no-op
664 // }
665 // flushBufferMethod = m;
666 // }
667 // void flushBufferOSW() {
668 // flushBuffer();
669 // if (writer instanceof OutputStreamWriter) {
670 // try {
671 // flushBufferMethod.invoke(writer);
672 // } catch (Exception e) {
673 // // no-op
674 // }
675 // }
676 // }
677
678 // Requires positive x
679 private static int stringSize(int x) {
680 for (int i=0; ; i++)
681 if (x <= INT_CHARS_SIZE_TABLE[i])
682 return i+1;
683 }
684
685 void getChars(CharSequence str, int srcBegin, int srcEnd, char[] dst, int dstBegin) {
686 int length = srcEnd - srcBegin;
687 for (int i = 0 ; i < length ; i++) {
688 int srcIdx = srcBegin + i;
689 int dstIdx = dstBegin + i;
690 dst[dstIdx] = str.charAt(srcIdx);
691 }
692 }
693
694 /**
695 * Places characters representing the integer i into the
696 * character array buf. The characters are placed into
697 * the buffer backwards starting with the least significant
698 * digit at the specified index (exclusive), and working
699 * backwards from there.
700 *
701 * Will fail if i == Integer.MIN_VALUE
702 */
703 private static void fillIntChars(int i, char[] buf, int index) {
704 int q, r;
705 int charPos = index;
706 char sign = 0;
707
708 if (i < 0) {
709 sign = '-';
710 i = -i;
711 }
712
713 // Generate two digits per iteration
714 while (i >= 65536) {
715 q = i / 100;
716 // really: r = i - (q * 100);
717 r = i - ((q << 6) + (q << 5) + (q << 2));
718 i = q;
719 buf [--charPos] = DIGIT_ONES[r];
720 buf [--charPos] = DIGIT_TENS[r];
721 }
722
723 // Fall thru to fast mode for smaller numbers
724 // assert(i <= 65536, i);
725 for (;;) {
726 q = (i * 52429) >>> (16+3);
727 r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
728 buf [--charPos] = DIGITS[r];
729 i = q;
730 if (i == 0) break;
731 }
732 if (sign != 0) {
733 buf [--charPos] = sign;
734 }
735 }
736
737 }