-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathGsonUtils.java
More file actions
300 lines (272 loc) · 12.3 KB
/
GsonUtils.java
File metadata and controls
300 lines (272 loc) · 12.3 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
* Copyright (c) 2015-2025, NWO-I CWI and Swat.engineering
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rascalmpl.ideservices;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.function.Consumer;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.rascalmpl.debug.NullRascalMonitor;
import org.rascalmpl.library.lang.json.internal.JsonValueReader;
import org.rascalmpl.library.lang.json.internal.JsonValueWriter;
import org.rascalmpl.util.base64.StreamingBase64;
import org.rascalmpl.values.ValueFactoryFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.usethesource.vallang.IBool;
import io.usethesource.vallang.ICollection;
import io.usethesource.vallang.IConstructor;
import io.usethesource.vallang.IDateTime;
import io.usethesource.vallang.IExternalValue;
import io.usethesource.vallang.IInteger;
import io.usethesource.vallang.INode;
import io.usethesource.vallang.INumber;
import io.usethesource.vallang.IRational;
import io.usethesource.vallang.IReal;
import io.usethesource.vallang.ISourceLocation;
import io.usethesource.vallang.IString;
import io.usethesource.vallang.ITuple;
import io.usethesource.vallang.IValue;
import io.usethesource.vallang.IValueFactory;
import io.usethesource.vallang.io.StandardTextReader;
import io.usethesource.vallang.io.binary.stream.IValueInputStream;
import io.usethesource.vallang.io.binary.stream.IValueOutputStream;
import io.usethesource.vallang.type.Type;
import io.usethesource.vallang.type.TypeFactory;
import io.usethesource.vallang.type.TypeStore;
/**
* This class can be used to configure Gson to automatically encode and decode IValues to/from JSON.
* Only primitive IValues are supported; collections, tuples, and nodes are not supported as these values cannot be decoded automatically
*/
public class GsonUtils {
private static final JsonValueWriter writer = new JsonValueWriter();
private static final TypeFactory tf = TypeFactory.getInstance();
private static final IValueFactory vf = ValueFactoryFactory.getValueFactory();
private static final List<TypeMapping> typeMappings;
/* Mappings from Java types to `vallang` types are declared here.
* Subtypes should be declared before their supertypes; e.g., `Number` and `Value` appear last.
*/
static {
writer.setRationalsAsString(true);
writer.setFileLocationsAsPathOnly(false);
typeMappings = List.of(
new TypeMapping(IBool.class, tf.boolType()),
new TypeMapping(ICollection.class), // IList, IMap, ISet
new TypeMapping(IConstructor.class),
new TypeMapping(IDateTime.class, tf.dateTimeType()),
new TypeMapping(IExternalValue.class),
new TypeMapping(IInteger.class, tf.integerType()),
new TypeMapping(INode.class),
new TypeMapping(IRational.class, tf.rationalType()),
new TypeMapping(IReal.class, tf.realType()),
new TypeMapping(ISourceLocation.class, tf.sourceLocationType()),
new TypeMapping(IString.class, tf.stringType()),
new TypeMapping(ITuple.class),
new TypeMapping(INumber.class, tf.numberType()),
new TypeMapping(IValue.class, tf.valueType())
);
}
public static enum ComplexTypeMode {
/**
* Complex values are serialized as JSON objects. Automatic deserialization is only supported for primitive types (`bool`,
* `datetime`, `int`, `rat`, `real`, `loc`, `str`, `num`); more complex types cannot be automatically deserialized as
* the type is not available at deserialization time.
*/
ENCODE_AS_JSON_OBJECT,
/**
* Complex values are serialized as a Base64-encoded string. A properly filled {@link TypeStore} is required for deserialization.
*/
ENCODE_AS_BASE64_STRING,
/**
* Complex values are serialized as a string. A properly filled {@link TypeStore} is required for deserialization.
*/
ENCODE_AS_STRING,
/**
* Only values of primitive type are supported; more complex values are neither serialized nor deserialized.
*/
NOT_SUPPORTED
}
private static class TypeMapping {
private final Class<?> clazz;
private final @Nullable Type type;
private final boolean isPrimitive;
public TypeMapping(Class<?> clazz) {
this(clazz, null);
}
public TypeMapping(Class<?> clazz, Type type) {
this(clazz, type, type != null);
}
public TypeMapping(Class<?> clazz, Type type, boolean isPrimitive) {
this.clazz = clazz;
this.type = type;
this.isPrimitive = isPrimitive;
}
public boolean supports(Class<?> incoming) {
return clazz.isAssignableFrom(incoming);
}
public <T> TypeAdapter<T> createAdapter(ComplexTypeMode complexTypeMode, TypeStore ts) {
var reader = new JsonValueReader(vf, ts, new NullRascalMonitor(), null);
if (isPrimitive) {
return new TypeAdapter<T>() {
@Override
public void write(JsonWriter out, T value) throws IOException {
writer.write(out, (IValue) value);
}
@SuppressWarnings("unchecked")
@Override
public T read(JsonReader in) throws IOException {
return (T) reader.read(in, type);
}
};
}
return new TypeAdapter<T>() {
@Override
public void write(JsonWriter out, T value) throws IOException {
switch (complexTypeMode) {
case ENCODE_AS_JSON_OBJECT:
writer.write(out, (IValue) value);
break;
case ENCODE_AS_BASE64_STRING:
out.value(base64Encode((IValue) value));
break;
case ENCODE_AS_STRING:
out.value(((IValue) value).toString());
break;
case NOT_SUPPORTED:
throw new IOException("Cannot write complex type " + value);
default:
throw new IllegalArgumentException("Unsupported complex type mode " + complexTypeMode);
}
}
@SuppressWarnings("unchecked")
@Override
public T read(JsonReader in) throws IOException {
switch (complexTypeMode) {
case ENCODE_AS_BASE64_STRING:
return base64Decode(in.nextString(), ts);
case ENCODE_AS_STRING:
return (T) new StandardTextReader().read(vf, ts, tf.valueType(), new StringReader(in.nextString()));
default:
throw new IOException("Cannot handle complex type");
}
}
};
}
}
/**
* Configure Gson to encode complex (non-primitive) values as JSON objects.
*
* See {@link ComplexTypeMode.ENCODE_AS_JSON_OBJECT}.
*/
public static Consumer<GsonBuilder> complexAsJsonObject() {
return builder -> configureGson(builder, ComplexTypeMode.ENCODE_AS_JSON_OBJECT, new TypeStore());
}
/**
* Configure Gson to encode complex (non-primitive) values as Base64-encoded strings.
*
* This configurtion should only be used for serialization; deserialization requires a {@link TypeStore).
*/
public static Consumer<GsonBuilder> complexAsBase64String() {
return complexAsBase64String(new TypeStore());
}
/**
* Configure Gson to encode complex (non-primitive) values as Base64-encoded strings.
*
* This configuration can be used for both serialization and deserialization.
*
* @param ts The {@link TypeStore} to be used during deserialization.
*/
public static Consumer<GsonBuilder> complexAsBase64String(TypeStore ts) {
return builder -> configureGson(builder, ComplexTypeMode.ENCODE_AS_BASE64_STRING, ts);
}
/**
* Configure Gson to encode complex (non-primitive) values as plain strings.
*
* This configurtion should only be used for serialization; deserialization requires a {@link TypeStore).
*/
public static Consumer<GsonBuilder> complexAsString() {
return complexAsString(new TypeStore());
}
/**
* Configure Gson to encode complex (non-primitive) values as plain strings.
*
* This configuration can be used for both serialization and deserialization.
*
* @param ts The {@link TypeStore} to be used during deserialization.
*/
public static Consumer<GsonBuilder> complexAsString(TypeStore ts) {
return builder -> configureGson(builder, ComplexTypeMode.ENCODE_AS_STRING, ts);
}
/**
* Configure Gson to encode encode primitive values only. Complex values raise an exception.
*
* @param builder The {@link GsonBuilder} to be configured.
*/
public static Consumer<GsonBuilder> noComplexTypes() {
return builder -> configureGson(builder, ComplexTypeMode.NOT_SUPPORTED, new TypeStore());
}
public static void configureGson(GsonBuilder builder, ComplexTypeMode complexTypeMode, TypeStore ts) {
builder.registerTypeAdapterFactory(new TypeAdapterFactory() {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
var rawType = type.getRawType();
if (!IValue.class.isAssignableFrom(rawType)) {
return null;
}
return typeMappings.stream()
.filter(m -> m.supports(rawType))
.findFirst()
.map(m -> m.<T>createAdapter(complexTypeMode, ts))
.orElse(null);
}
});
}
public static String base64Encode(IValue value) {
var builder = new StringBuilder();
try (var encoder = StreamingBase64.encode(builder);
var out = new IValueOutputStream(encoder, vf)) {
out.write(value);
} catch (IOException e) {
throw new RuntimeException(e);
}
return builder.toString();
}
@SuppressWarnings("unchecked")
public static <T extends IValue> T base64Decode(String string, TypeStore ts) {
try (var decoder = StreamingBase64.decode(string);
var in = new IValueInputStream(decoder, vf, () -> ts)) {
return (T) in.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}