-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Jackson2ExecutionContextStringSerializer.java
376 lines (336 loc) · 15.6 KB
/
Jackson2ExecutionContextStringSerializer.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
/*
* Copyright 2008-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.repository.dao;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.annotation.JacksonAnnotation;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder;
import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.repository.ExecutionContextSerializer;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
/**
* Implementation that uses Jackson2 to provide (de)serialization.
*
* By default, this implementation trusts a limited set of classes to be
* deserialized from the execution context. If a class is not trusted by default
* and is safe to deserialize, you can add it to the base set of trusted classes
* at {@link Jackson2ExecutionContextStringSerializer construction time} or provide
* an explicit mapping using Jackson annotations, as shown in the following example:
*
* <pre class="code">
* @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
* public class MyTrustedType implements Serializable {
*
* }
* </pre>
*
* It is also possible to provide a custom {@link ObjectMapper} with a mixin for
* the trusted type:
*
* <pre class="code">
* ObjectMapper objectMapper = new ObjectMapper();
* objectMapper.addMixIn(MyTrustedType.class, Object.class);
* Jackson2ExecutionContextStringSerializer serializer = new Jackson2ExecutionContextStringSerializer();
* serializer.setObjectMapper(objectMapper);
* // register serializer in JobRepositoryFactoryBean
* </pre>
*
* If the (de)serialization is only done by a trusted source, you can also enable
* default typing:
*
* <pre class="code">
* PolymorphicTypeValidator polymorphicTypeValidator = .. // configure your trusted PolymorphicTypeValidator
* ObjectMapper objectMapper = new ObjectMapper();
* objectMapper.activateDefaultTyping(polymorphicTypeValidator);
* Jackson2ExecutionContextStringSerializer serializer = new Jackson2ExecutionContextStringSerializer();
* serializer.setObjectMapper(objectMapper);
* // register serializer in JobRepositoryFactoryBean
* </pre>
*
* @author Marten Deinum
* @author Mahmoud Ben Hassine
* @since 3.0.7
*
* @see ExecutionContextSerializer
*/
public class Jackson2ExecutionContextStringSerializer implements ExecutionContextSerializer {
private ObjectMapper objectMapper;
/**
* Create a new {@link Jackson2ExecutionContextStringSerializer}.
*
* @param trustedClassNames fully qualified names of classes that are safe
* to deserialize from the execution context and which should be added to the
* default set of trusted classes.
*/
public Jackson2ExecutionContextStringSerializer(String... trustedClassNames) {
this.objectMapper = JsonMapper.builder()
.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
.configure(MapperFeature.BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES, true)
.setDefaultTyping(createTrustedDefaultTyping(trustedClassNames))
.addModule(new JobParametersModule())
.build();
}
public void setObjectMapper(ObjectMapper objectMapper) {
Assert.notNull(objectMapper, "ObjectMapper must not be null");
this.objectMapper = objectMapper.copy();
this.objectMapper.registerModule(new JobParametersModule());
}
public Map<String, Object> deserialize(InputStream in) throws IOException {
TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {};
return objectMapper.readValue(in, typeRef);
}
public void serialize(Map<String, Object> context, OutputStream out) throws IOException {
Assert.notNull(context, "A context is required");
Assert.notNull(out, "An OutputStream is required");
objectMapper.writeValue(out, context);
}
// BATCH-2680
/**
* Custom Jackson module to support {@link JobParameter} and {@link JobParameters}
* deserialization.
*/
private class JobParametersModule extends SimpleModule {
private static final long serialVersionUID = 1L;
private JobParametersModule() {
super("Job parameters module");
setMixInAnnotation(JobParameters.class, JobParametersMixIn.class);
addDeserializer(JobParameter.class, new JobParameterDeserializer());
}
private abstract class JobParametersMixIn {
@JsonIgnore
abstract boolean isEmpty();
}
private class JobParameterDeserializer extends StdDeserializer<JobParameter> {
private static final long serialVersionUID = 1L;
private static final String IDENTIFYING_KEY_NAME = "identifying";
private static final String TYPE_KEY_NAME = "type";
private static final String VALUE_KEY_NAME = "value";
JobParameterDeserializer() {
super(JobParameter.class);
}
@Override
public JobParameter deserialize(JsonParser parser, DeserializationContext context) throws IOException {
JsonNode node = parser.readValueAsTree();
boolean identifying = node.get(IDENTIFYING_KEY_NAME).asBoolean();
String type = node.get(TYPE_KEY_NAME).asText();
JsonNode value = node.get(VALUE_KEY_NAME);
Object parameterValue;
switch (JobParameter.ParameterType.valueOf(type)) {
case STRING: {
parameterValue = value.asText();
return new JobParameter((String) parameterValue, identifying);
}
case DATE: {
parameterValue = new Date(value.get(1).asLong());
return new JobParameter((Date) parameterValue, identifying);
}
case LONG: {
parameterValue = value.get(1).asLong();
return new JobParameter((Long) parameterValue, identifying);
}
case DOUBLE: {
parameterValue = value.asDouble();
return new JobParameter((Double) parameterValue, identifying);
}
}
return null;
}
}
}
/**
* Creates a TypeResolverBuilder that checks if a type is trusted.
* @return a TypeResolverBuilder that checks if a type is trusted.
* @param trustedClassNames array of fully qualified trusted class names
*/
private static TypeResolverBuilder<? extends TypeResolverBuilder> createTrustedDefaultTyping(String[] trustedClassNames) {
TypeResolverBuilder<StdTypeResolverBuilder> result = new TrustedTypeResolverBuilder(ObjectMapper.DefaultTyping.NON_FINAL, trustedClassNames);
result = result.init(JsonTypeInfo.Id.CLASS, null);
result = result.inclusion(JsonTypeInfo.As.PROPERTY);
return result;
}
/**
* An implementation of {@link ObjectMapper.DefaultTypeResolverBuilder}
* that inserts an {@code allow all} {@link PolymorphicTypeValidator}
* and overrides the {@code TypeIdResolver}
* @author Rob Winch
*/
static class TrustedTypeResolverBuilder extends ObjectMapper.DefaultTypeResolverBuilder {
private final String[] trustedClassNames;
TrustedTypeResolverBuilder(ObjectMapper.DefaultTyping defaultTyping, String[] trustedClassNames) {
super(
defaultTyping,
//we do explicit validation in the TypeIdResolver
BasicPolymorphicTypeValidator.builder()
.allowIfSubType(Object.class)
.build()
);
this.trustedClassNames =
trustedClassNames != null ? Arrays.copyOf(trustedClassNames, trustedClassNames.length) : null;
}
@Override
protected TypeIdResolver idResolver(MapperConfig<?> config,
JavaType baseType,
PolymorphicTypeValidator subtypeValidator,
Collection<NamedType> subtypes, boolean forSer, boolean forDeser) {
TypeIdResolver result = super.idResolver(config, baseType, subtypeValidator, subtypes, forSer, forDeser);
return new TrustedTypeIdResolver(result, this.trustedClassNames);
}
}
/**
* A {@link TypeIdResolver} that delegates to an existing implementation and throws an IllegalStateException if the
* class being looked up is not trusted, does not provide an explicit mixin, and is not annotated with Jackson
* mappings.
*/
static class TrustedTypeIdResolver implements TypeIdResolver {
private static final Set<String> TRUSTED_CLASS_NAMES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"java.util.UUID",
"java.util.ArrayList",
"java.util.Arrays$ArrayList",
"java.util.LinkedList",
"java.util.Collections$EmptyList",
"java.util.Collections$EmptyMap",
"java.util.Collections$EmptySet",
"java.util.Collections$UnmodifiableRandomAccessList",
"java.util.Collections$UnmodifiableList",
"java.util.Collections$UnmodifiableMap",
"java.util.Collections$UnmodifiableSet",
"java.util.Collections$SingletonList",
"java.util.Collections$SingletonMap",
"java.util.Collections$SingletonSet",
"java.util.Date",
"java.time.Instant",
"java.time.Duration",
"java.time.LocalDate",
"java.time.LocalTime",
"java.time.LocalDateTime",
"java.sql.Timestamp",
"java.net.URL",
"java.util.TreeMap",
"java.util.HashMap",
"java.util.LinkedHashMap",
"java.util.TreeSet",
"java.util.HashSet",
"java.util.LinkedHashSet",
"java.lang.Boolean",
"java.lang.Byte",
"java.lang.Short",
"java.lang.Integer",
"java.lang.Long",
"java.lang.Double",
"java.lang.Float",
"java.math.BigDecimal",
"java.math.BigInteger",
"java.lang.String",
"java.lang.Character",
"java.lang.CharSequence",
"java.util.Properties",
"[Ljava.util.Properties;",
"org.springframework.batch.core.JobParameter",
"org.springframework.batch.core.JobParameters"
)));
private final Set<String> trustedClassNames = new LinkedHashSet<>(TRUSTED_CLASS_NAMES);
private final TypeIdResolver delegate;
TrustedTypeIdResolver(TypeIdResolver delegate, String[] trustedClassNames) {
this.delegate = delegate;
if (trustedClassNames != null) {
this.trustedClassNames.addAll(Arrays.asList(trustedClassNames));
}
}
@Override
public void init(JavaType baseType) {
delegate.init(baseType);
}
@Override
public String idFromValue(Object value) {
return delegate.idFromValue(value);
}
@Override
public String idFromValueAndType(Object value, Class<?> suggestedType) {
return delegate.idFromValueAndType(value, suggestedType);
}
@Override
public String idFromBaseType() {
return delegate.idFromBaseType();
}
@Override
public JavaType typeFromId(DatabindContext context, String id) throws IOException {
DeserializationConfig config = (DeserializationConfig) context.getConfig();
JavaType result = delegate.typeFromId(context, id);
String className = result.getRawClass().getName();
if (isTrusted(className)) {
return result;
}
boolean isExplicitMixin = config.findMixInClassFor(result.getRawClass()) != null;
if (isExplicitMixin) {
return result;
}
Class<?> rawClass = result.getRawClass();
JacksonAnnotation jacksonAnnotation = AnnotationUtils.findAnnotation(rawClass, JacksonAnnotation.class);
if (jacksonAnnotation != null) {
return result;
}
throw new IllegalArgumentException("The class with " + id + " and name of " + className + " is not trusted. " +
"If you believe this class is safe to deserialize, you can add it to the base set of trusted classes " +
"at construction time or provide an explicit mapping using Jackson annotations or a custom ObjectMapper. " +
"If the serialization is only done by a trusted source, you can also enable default typing.");
}
private boolean isTrusted(String id) {
return this.trustedClassNames.contains(id);
}
@Override
public String getDescForKnownTypeIds() {
return delegate.getDescForKnownTypeIds();
}
@Override
public JsonTypeInfo.Id getMechanism() {
return delegate.getMechanism();
}
}
}