-
Notifications
You must be signed in to change notification settings - Fork 37
/
Json.java
453 lines (425 loc) · 16 KB
/
Json.java
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
package tlc2.overrides;
/*******************************************************************************
* Copyright (c) 2019 Microsoft Research. All rights reserved.
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Contributors:
* Markus Alexander Kuppe - initial API and implementation
******************************************************************************/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import tlc2.output.EC;
import tlc2.tool.EvalException;
import tlc2.value.IValue;
import tlc2.value.Values;
import tlc2.value.impl.BoolValue;
import tlc2.value.impl.EnumerableValue;
import tlc2.value.impl.FcnLambdaValue;
import tlc2.value.impl.FcnRcdValue;
import tlc2.value.impl.IntValue;
import tlc2.value.impl.ModelValue;
import tlc2.value.impl.RecordValue;
import tlc2.value.impl.SetEnumValue;
import tlc2.value.impl.StringValue;
import tlc2.value.impl.TupleValue;
import tlc2.value.impl.Value;
import util.UniqueString;
/**
* Module overrides for operators to read and write JSON.
*/
public class Json {
/**
* Encodes the given value as a JSON string.
*
* @param value the value to encode
* @return the JSON string value
*/
@TLAPlusOperator(identifier = "ToJson", module = "Json", warn = false)
public static StringValue toJson(final IValue value) throws IOException {
return new StringValue(getNode(value).toString());
}
/**
* Encodes the given value as a JSON array string.
*
* @param value the value to encode
* @return the JSON array string value
*/
@TLAPlusOperator(identifier = "ToJsonArray", module = "Json", warn = false)
public static StringValue toJsonArray(final IValue value) throws IOException {
return new StringValue(getArrayNode(value).toString());
}
/**
* Encodes the given value as a JSON object string.
*
* @param value the value to encode
* @return the JSON object string value
*/
@TLAPlusOperator(identifier = "ToJsonObject", module = "Json", warn = false)
public static StringValue toJsonObject(final IValue value) throws IOException {
return new StringValue(getObjectNode(value).toString());
}
/**
* Deserializes a tuple of newline delimited JSON values from the given path.
*
* @param path the JSON file path
* @return a tuple of JSON values
*/
@TLAPlusOperator(identifier = "ndJsonDeserialize", module = "Json", warn = false)
public static IValue ndDeserialize(final StringValue path) throws IOException {
List<Value> values = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(path.val.toString())))) {
String line = reader.readLine();
while (line != null) {
// Ignore empty lines in the newline delimited Json file.
// see https://github.com/ndjson/ndjson-spec#32-parsing
line = line.trim();
if (!"".equals(line)) {
JsonElement node = JsonParser.parseString(line);
values.add(getValue(node));
}
line = reader.readLine();
}
}
return new TupleValue(values.toArray(new Value[values.size()]));
}
/**
* Deserializes a tuple of *plain* JSON values from the given path.
*
* @param path the JSON file path
* @return a tuple of JSON values
*/
@TLAPlusOperator(identifier = "JsonDeserialize", module = "Json", warn = false)
public static IValue deserialize(final StringValue path) throws IOException {
JsonElement node = JsonParser.parseReader(new FileReader(new File(path.val.toString())));
return getValue(node);
}
/**
* Serializes a tuple of values to newline delimited JSON.
*
* @param path the file to which to write the values
* @param value the values to write
* @return a boolean value indicating whether the serialization was successful
*/
@TLAPlusOperator(identifier = "ndJsonSerialize", module = "Json", warn = false)
public synchronized static BoolValue ndSerialize(final StringValue path, final Value v) throws IOException {
final TupleValue value = (TupleValue) v.toTuple();
if (value == null) {
throw new EvalException(EC.TLC_MODULE_ARGUMENT_ERROR,
new String[] { "second", "ndJsonSerialize", "sequence", Values.ppr(v.toString()) });
}
File file = new File(path.val.toString());
if (file.getParentFile() != null) {file.getParentFile().mkdirs();} // Cannot create parent dir for relative path.
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path.val.toString())))) {
for (int i = 0; i < value.elems.length; i++) {
writer.write(getNode(value.elems[i]).toString() + "\n");
}
}
return BoolValue.ValTrue;
}
/**
* Serializes a TLA+ TupleValue or RecordValue to JSON.
*
* @param path the file to which to write the values
* @param value the values to write
* @return a boolean value indicating whether the serialization was successful
*/
@TLAPlusOperator(identifier = "JsonSerialize", module = "Json", warn = false)
public synchronized static BoolValue serialize(final StringValue path, final Value v) throws IOException {
Value value = v.toTuple();
if (value == null) {
value = v.toRcd();
}
if (value == null) {
throw new EvalException(EC.TLC_MODULE_ARGUMENT_ERROR,
new String[] { "second", "JsonSerialize", "sequence or record", Values.ppr(v.toString()) });
}
final File file = new File(path.val.toString());
if (file.getParentFile() != null) {file.getParentFile().mkdirs();} // Cannot create parent dir for relative path.
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path.val.toString())))) {
writer.write(getNode(v).toString());
}
return BoolValue.ValTrue;
}
/**
* Recursively converts the given value to a {@code JsonElement}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getNode(IValue value) throws IOException {
if (value instanceof RecordValue) {
return getObjectNode((RecordValue) value);
} else if (value instanceof TupleValue) {
return getArrayNode((TupleValue) value);
} else if (value instanceof StringValue) {
return new JsonPrimitive(((StringValue) value).val.toString());
} else if (value instanceof ModelValue) {
return new JsonPrimitive(((ModelValue) value).val.toString());
} else if (value instanceof IntValue) {
return new JsonPrimitive(((IntValue) value).val);
} else if (value instanceof BoolValue) {
return new JsonPrimitive(((BoolValue) value).val);
} else if (value instanceof FcnRcdValue) {
return getObjectNode((FcnRcdValue) value);
} else if (value instanceof FcnLambdaValue) {
return getObjectNode((FcnRcdValue) ((FcnLambdaValue) value).toFcnRcd());
} else if (value instanceof SetEnumValue) {
return getArrayNode((SetEnumValue) value);
} else if (value instanceof EnumerableValue) {
return getArrayNode((SetEnumValue) ((EnumerableValue) value).toSetEnum());
} else {
throw new IOException("Cannot convert value: unsupported value type " + value.getClass().getName());
}
}
/**
* Returns a boolean indicating whether the given value is a valid sequence.
*
* @param value the value to check
* @return indicates whether the value is a valid sequence
*/
private static boolean isValidSequence(FcnRcdValue value) {
final Value[] domain = value.getDomainAsValues();
for (Value d : domain) {
if (!(d instanceof IntValue)) {
return false;
}
}
value.normalize();
for (int i = 0; i < domain.length; i++) {
if (((IntValue) domain[i]).val != (i + 1)) {
return false;
}
}
return true;
}
/**
* Recursively converts the given value to an {@code JsonObject}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getObjectNode(IValue value) throws IOException {
if (value instanceof RecordValue) {
return getObjectNode((RecordValue) value);
} else if (value instanceof TupleValue) {
return getObjectNode((TupleValue) value);
} else if (value instanceof FcnRcdValue) {
return getObjectNode((FcnRcdValue) value);
} else if (value instanceof FcnLambdaValue) {
return getObjectNode((FcnRcdValue) ((FcnLambdaValue) value).toFcnRcd());
} else {
throw new IOException("Cannot convert value: unsupported value type " + value.getClass().getName());
}
}
/**
* Converts the given record value to a {@code JsonObject}, recursively converting values.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getObjectNode(FcnRcdValue value) throws IOException {
if (isValidSequence(value)) {
return getArrayNode(value);
}
final Value[] domain = value.getDomainAsValues();
JsonObject jsonObject = new JsonObject();
for (int i = 0; i < domain.length; i++) {
Value domainValue = domain[i];
if (domainValue instanceof StringValue) {
jsonObject.add(((StringValue) domainValue).val.toString(), getNode(value.values[i]));
} else {
jsonObject.add(domainValue.toString(), getNode(value.values[i]));
}
}
return jsonObject;
}
/**
* Converts the given record value to an {@code JsonObject}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getObjectNode(RecordValue value) throws IOException {
JsonObject jsonObject = new JsonObject();
for (int i = 0; i < value.names.length; i++) {
jsonObject.add(value.names[i].toString(), getNode(value.values[i]));
}
return jsonObject;
}
/**
* Converts the given tuple value to an {@code JsonObject}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getObjectNode(TupleValue value) throws IOException {
JsonObject jsonObject = new JsonObject();
for (int i = 0; i < value.elems.length; i++) {
jsonObject.add(String.valueOf(i), getNode(value.elems[i]));
}
return jsonObject;
}
/**
* Recursively converts the given value to an {@code JsonArray}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getArrayNode(IValue value) throws IOException {
if (value instanceof TupleValue) {
return getArrayNode((TupleValue) value);
} else if (value instanceof FcnRcdValue) {
return getArrayNode((FcnRcdValue) value);
} else if (value instanceof FcnLambdaValue) {
return getArrayNode((FcnRcdValue) ((FcnLambdaValue) value).toFcnRcd());
} else if (value instanceof SetEnumValue) {
return getArrayNode((SetEnumValue) value);
} else if (value instanceof EnumerableValue) {
return getArrayNode((SetEnumValue) ((EnumerableValue) value).toSetEnum());
} else {
throw new IOException("Cannot convert value: unsupported value type " + value.getClass().getName());
}
}
/**
* Converts the given tuple value to an {@code JsonArray}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getArrayNode(TupleValue value) throws IOException {
JsonArray jsonArray = new JsonArray(value.elems.length);
for (int i = 0; i < value.elems.length; i++) {
jsonArray.add(getNode(value.elems[i]));
}
return jsonArray;
}
/**
* Converts the given record value to an {@code JsonArray}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getArrayNode(FcnRcdValue value) throws IOException {
if (!isValidSequence(value)) {
return getObjectNode(value);
}
value.normalize();
JsonArray jsonArray = new JsonArray(value.values.length);
for (int i = 0; i < value.values.length; i++) {
jsonArray.add(getNode(value.values[i]));
}
return jsonArray;
}
/**
* Converts the given tuple value to an {@code JsonArray}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getArrayNode(SetEnumValue value) throws IOException {
value.normalize();
Value[] values = value.elems.toArray();
JsonArray jsonArray = new JsonArray(values.length);
for (int i = 0; i < values.length; i++) {
jsonArray.add(getNode(values[i]));
}
return jsonArray;
}
/**
* Recursively converts the given {@code JsonElement} to a TLC value.
*
* @param node the {@code JsonElement} to convert
* @return the converted value
*/
private static Value getValue(JsonElement node) throws IOException {
if (node.isJsonArray()) {
return getTupleValue(node);
}
else if (node.isJsonObject()) {
return getRecordValue(node);
}
else if (node.isJsonPrimitive()) {
JsonPrimitive primitive = node.getAsJsonPrimitive();
if (primitive.isNumber()) {
return IntValue.gen(primitive.getAsInt());
}
else if (primitive.isBoolean()) {
return new BoolValue(primitive.getAsBoolean());
}
else if (primitive.isString()) {
return new StringValue(primitive.getAsString());
}
}
throw new IOException("Cannot convert value: unsupported JSON value " + node.toString());
}
/**
* Converts the given {@code JsonElement} to a tuple.
*
* @param node the {@code JsonElement} to convert
* @return the tuple value
*/
private static TupleValue getTupleValue(JsonElement node) throws IOException {
List<Value> values = new ArrayList<>();
JsonArray jsonArray = node.getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
values.add(getValue(jsonArray.get(i)));
}
return new TupleValue(values.toArray(new Value[values.size()]));
}
/**
* Converts the given {@code JsonElement} to a record.
*
* @param node the {@code JsonElement} to convert
* @return the record value
*/
private static RecordValue getRecordValue(JsonElement node) throws IOException {
List<UniqueString> keys = new ArrayList<>();
List<Value> values = new ArrayList<>();
Iterator<Map.Entry<String, JsonElement>> iterator = node.getAsJsonObject().entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();
keys.add(UniqueString.uniqueStringOf(entry.getKey()));
values.add(getValue(entry.getValue()));
}
return new RecordValue(keys.toArray(new UniqueString[keys.size()]), values.toArray(new Value[values.size()]),
false);
}
/**
* @deprecated It will be removed when this Class is moved to `TLC`.
*/
@Deprecated
final static void resolves() {
// See TLCOverrides.java
}
}