-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.java
More file actions
285 lines (263 loc) · 10.2 KB
/
Utils.java
File metadata and controls
285 lines (263 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.sandbox.internal.util.json;
import java.util.List;
import java.util.Map;
import jdk.sandbox.java.util.json.JsonArray;
import jdk.sandbox.java.util.json.JsonAssertionException;
import jdk.sandbox.java.util.json.JsonBoolean;
import jdk.sandbox.java.util.json.JsonNull;
import jdk.sandbox.java.util.json.JsonNumber;
import jdk.sandbox.java.util.json.JsonObject;
import jdk.sandbox.java.util.json.JsonString;
import jdk.sandbox.java.util.json.JsonValue;
/**
* Shared utilities for Json classes.
*/
public class Utils {
// Non instantiable
private Utils() {}
// Equivalent to JsonObject/Array.of() factories without the need for defensive copy
// and other input validation
public static JsonArray arrayOf(List<JsonValue> list) {
return new JsonArrayImpl(list);
}
public static JsonObject objectOf(Map<String, JsonValue> map) {
return new JsonObjectImpl(map);
}
/*
* Escapes a String to ensure it is a valid JSON String.
* Backslash, double quote, and control chars are escaped.
* Providing this method in Utils allows for a bypass of `JsonString.of(str).value()`
* for the toString representation of JsonObject member names.
*/
public static String escape(String str) {
StringBuilder sb = null; // Lazy init
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// Does not require escaping
if (c >= 32 && c != '\\' && c != '"') {
if (sb != null) {
sb.append(c);
}
// Requires escaping
} else {
if (sb == null) {
sb = new StringBuilder().append(str, 0, i);
}
// 2 Char escapes (Non-control characters)
if (c == '\\') {
sb.append('\\').append(c);
} else if (c == '"') {
sb.append('\\').append(c);
// 2 Char escapes (Control characters)
} else if (c == '\b') {
sb.append('\\').append('b');
} else if (c == '\f') {
sb.append('\\').append('f');
} else if (c == '\n') {
sb.append('\\').append('n');
} else if (c == '\r') {
sb.append('\\').append('r');
} else if (c == '\t') {
sb.append('\\').append('t');
// All other chars requiring Unicode escape sequence
} else {
sb.append('\\').append('u').append(String.format("%04X", (int) c));
}
}
}
return sb == null ? str : sb.toString();
}
// Use to compose an exception when casting to an incorrect type
public static JsonAssertionException composeTypeError(JsonValue jv, String expected) {
var actual = switch (jv) {
case JsonObject obj -> "JsonObject";
case JsonArray arr -> "JsonArray";
case JsonBoolean b -> "JsonBoolean";
case JsonNull n -> "JsonNull";
case JsonNumber num -> "JsonNumber";
case JsonString str -> "JsonString";
};
return new JsonAssertionException("%s is not a %s.".formatted(actual, expected)
+ ((jv instanceof JsonValueImpl jvi && jvi.doc() != null) ? JsonPath.getPath(jvi) : ""));
}
static String getPath(JsonValueImpl jvi) {
return JsonPath.getPath(jvi);
}
private static final class JsonPath {
private final int offset;
private final char[] doc;
// Tracked and incremented during path creation
private int row;
private int col;
private JsonPath(JsonValueImpl jvi) {
this.offset = jvi.offset();
this.doc = jvi.doc();
}
private static String getPath(JsonValueImpl jvi) {
return new JsonPath(jvi).parseToRoot();
}
private String parseToRoot() {
var sb = new StringBuilder();
// Updates the sb
toPath(offset, sb);
// If no new line encountered, col is the starting offset value
if (row == 0) {
col = offset;
}
return " Path: \"%s\". Location: row %d, col %d.".formatted(sb.toString(), row, col);
}
private void addRow(int curr) {
row++;
if (row == 1) {
col = offset - curr - 1;
}
}
// Void return type, builds the passed StringBuilder
private void toPath(int offset, StringBuilder sb) {
// Walk past starting char and white space
offset = walkWhitespace(offset - 1);
// If offset is -1, we found the root and are finished
if (offset != -1) {
// Node case
offset = switch (doc[offset]) {
// Does the actual appending
// Walks to the node's starting [ or {
case ',', '[' -> arrayNode(offset, sb);
case ':' -> objectNode(offset, sb);
default -> throw new InternalError();
};
toPath(offset, sb);
}
}
private int walkWhitespace(int offset) {
while (offset >= 0) {
var ws = switch (doc[offset]) {
case ' ', '\t','\r' -> true;
case '\n' -> {
addRow(offset);
yield true;
}
default -> false;
};
if (!ws) {
break;
}
offset--;
}
return offset;
}
// Backtracking from an element in a JsonArray either expects a ',' or '['
// E.g. " [ val ... " or " [ foo, val "
private int arrayNode(int offset, StringBuilder sb) {
int aDepth = 0;
int oDepth = 0;
int values = 0;
boolean inString = false;
while (offset > 0) {
var c = doc[offset];
if (inString) {
if (c == '"' && doc[offset - 1] != '\\') {
inString = false;
}
} else {
if (c == '[') {
aDepth++;
} else if (c == ']') {
aDepth--;
} else if (c == '{') {
oDepth++;
} else if (c == '}') {
oDepth--;
} else if (c == ',' && aDepth == 0 && oDepth == 0) {
values++;
} else if (c == '"') {
inString = true;
} else if (c == '\n') {
addRow(offset);
}
if (aDepth > 0) {
break;
}
}
offset--;
}
sb.insert(0, '[' + String.valueOf(values));
return offset;
}
// Unlike arrayNode, always expects a ':'
// Regardless of value position, always preceded by a member name and colon
private int objectNode(int offset, StringBuilder sb) {
offset--; // Walk past ':'
int depth = 0;
int nameStart = 0;
int nameEnd = 0;
boolean inName = false;
// Append member name first
while (offset > 0) {
var c = doc[offset];
if (c == '"' && !inName) {
nameEnd = offset;
inName = true;
} else if (c == '"' && doc[offset - 1] != '\\') {
// Pre-escape check should not throw AIOOBE because guaranteed
// to have enclosing opening bracket
nameStart = offset + 1;
offset--; // Walk past quote
break;
}
offset--;
}
// Add the name
sb.insert(0, '{' + new String(doc, nameStart, nameEnd - nameStart));
boolean inString = false;
// Move to parent offset
while (offset > 0) {
var c = doc[offset];
if (inString) {
if (c == '"' && doc[offset - 1] != '\\') {
inString = false;
}
} else {
if (c == '{') {
depth++;
} else if (c == '}') {
depth--;
} else if (c == '"') {
inString = true;
} else if (c == '\n') {
addRow(offset);
}
if (depth > 0) {
break;
}
}
offset--;
}
return offset;
}
}
}