Debian Codegraph @

src/main/org/h2/util/json/JsonConstructorUtils.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.util.json;
7
8 import java.io.ByteArrayOutputStream;
9
10 import org.h2.message.DbException;
11 import org.h2.value.TypeInfo;
12 import org.h2.value.Value;
13 import org.h2.value.ValueJson;
14 import org.h2.value.ValueNull;
15
16 /**
17 * Utilities for JSON constructors.
18 */
19 public final class JsonConstructorUtils {
20
21 /**
22 * The ABSENT ON NULL flag.
23 */
24 public static final int JSON_ABSENT_ON_NULL = 1;
25
26 /**
27 * The WITH UNIQUE KEYS flag.
28 */
29 public static final int JSON_WITH_UNIQUE_KEYS = 2;
30
31 private JsonConstructorUtils() {
32 }
33
34 /**
35 * Appends a value to a JSON object in the specified string builder.
36 *
37 * @param baos
38 * the output stream to append to
39 * @param key
40 * the name of the property
41 * @param value
42 * the value of the property
43 */
44 public static void jsonObjectAppend(ByteArrayOutputStream baos, String key, Value value) {
45 if (baos.size() > 1) {
46 baos.write(',');
47 }
48 JSONByteArrayTarget.encodeString(baos, key).write(':');
49 byte[] b = value.convertTo(TypeInfo.TYPE_JSON).getBytesNoCopy();
50 baos.write(b, 0, b.length);
51 }
52
53 /**
54 * Appends trailing closing brace to the specified string builder with a
55 * JSON object, validates it, and converts to a JSON value.
56 *
57 * @param baos
58 * the output stream with the object
59 * @param flags
60 * the flags ({@link #JSON_WITH_UNIQUE_KEYS})
61 * @return the JSON value
62 * @throws DbException
63 * if {@link #JSON_WITH_UNIQUE_KEYS} is specified and keys are
64 * not unique
65 */
66 public static Value jsonObjectFinish(ByteArrayOutputStream baos, int flags) {
67 baos.write('}');
68 byte[] result = baos.toByteArray();
69 if ((flags & JSON_WITH_UNIQUE_KEYS) != 0) {
70 try {
71 JSONBytesSource.parse(result, new JSONValidationTargetWithUniqueKeys());
72 } catch (RuntimeException ex) {
73 String s = JSONBytesSource.parse(result, new JSONStringTarget());
74 throw DbException.getInvalidValueException("JSON WITH UNIQUE KEYS",
75 s.length() < 128 ? result : s.substring(0, 128) + "...");
76 }
77 }
78 return ValueJson.getInternal(result);
79 }
80
81 /**
82 * Appends a value to a JSON array in the specified output stream.
83 *
84 * @param baos
85 * the output stream to append to
86 * @param value
87 * the value
88 * @param flags
89 * the flags ({@link #JSON_ABSENT_ON_NULL})
90 */
91 public static void jsonArrayAppend(ByteArrayOutputStream baos, Value value, int flags) {
92 if (value == ValueNull.INSTANCE) {
93 if ((flags & JSON_ABSENT_ON_NULL) != 0) {
94 return;
95 }
96 value = ValueJson.NULL;
97 }
98 if (baos.size() > 1) {
99 baos.write(',');
100 }
101 byte[] b = value.convertTo(TypeInfo.TYPE_JSON).getBytesNoCopy();
102 baos.write(b, 0, b.length);
103 }
104
105 }