forked from FasterXML/jackson-dataformat-xml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXmlMapper.java
553 lines (476 loc) · 20.7 KB
/
XmlMapper.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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
package tools.jackson.dataformat.xml;
import java.io.Closeable;
import java.io.IOException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import tools.jackson.core.*;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.*;
import tools.jackson.databind.cfg.CoercionAction;
import tools.jackson.databind.cfg.CoercionInputShape;
import tools.jackson.databind.cfg.DeserializationContexts;
import tools.jackson.databind.cfg.MapperBuilder;
import tools.jackson.databind.cfg.MapperBuilderState;
import tools.jackson.databind.cfg.SerializationContexts;
import tools.jackson.databind.jsontype.PolymorphicTypeValidator;
import tools.jackson.databind.jsontype.TypeResolverBuilder;
import tools.jackson.databind.ser.SerializationContextExt;
import tools.jackson.databind.type.LogicalType;
import tools.jackson.dataformat.xml.deser.FromXmlParser;
import tools.jackson.dataformat.xml.deser.XmlDeserializationContexts;
import tools.jackson.dataformat.xml.ser.ToXmlGenerator;
import tools.jackson.dataformat.xml.ser.XmlSerializationContexts;
import tools.jackson.dataformat.xml.util.DefaultXmlPrettyPrinter;
/**
* Customized {@link ObjectMapper} that will read and write XML instead of JSON,
* using XML-backed {@link tools.jackson.core.TokenStreamFactory}
* implementation ({@link XmlFactory}), operation on STAX
* {@link javax.xml.stream.XMLStreamReader}s and
* {@link javax.xml.stream.XMLStreamWriter}s.
*<p>
* Mapper itself overrides some aspects of functionality to try to handle
* data binding aspects as similar to JAXB as possible.
*/
public class XmlMapper extends ObjectMapper
{
private static final long serialVersionUID = 1L;
protected final static DefaultXmlPrettyPrinter DEFAULT_XML_PRETTY_PRINTER = new DefaultXmlPrettyPrinter();
/**
* Builder implementation for constructing {@link XmlMapper} instances.
*
* @since 3.0
*/
public static class Builder extends MapperBuilder<XmlMapper, Builder>
{
protected boolean _defaultUseWrapper;
protected String _nameForTextElement;
/*
/******************************************************************
/* Life-cycle
/******************************************************************
*/
public Builder(XmlFactory f) {
super(f);
// 21-Jun-2017, tatu: Seems like there are many cases in XML where ability to coerce empty
// String into `null` (where it otherwise is an error) is very useful.
enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
_defaultUseWrapper = JacksonXmlAnnotationIntrospector.DEFAULT_USE_WRAPPER;
_nameForTextElement = FromXmlParser.DEFAULT_UNNAMED_TEXT_PROPERTY;
// as well as AnnotationIntrospector: note, however, that "use wrapper" may well
// change later on
annotationIntrospector(new JacksonXmlAnnotationIntrospector(_defaultUseWrapper));
// Need to mangle Type Ids (to avoid invalid XML Name characters); one way is this:
typeResolverProvider(new XmlTypeResolverProvider());
// Some changes easiest to apply via Module
addModule(new XmlModule());
// 04-May-2018, tatu: Important! Let's also default `String` `null` handling to coerce
// to empty string -- this lets us induce `null` from empty tags firs
// 08-Sep-2019, tatu: This causes [dataformat-xml#359] (follow-up for #354), but
// can not simply be removed.
// 19-Mar-2023, tatu: Nah. Let's not coerce to let `xsi:nil` works its magic
//_configOverrides.findOrCreateOverride(String.class)
// .setNullHandling(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));
// 13-May-2020, tatu: [dataformat-xml#377] Need to ensure we will keep XML-specific
// Base64 default as "MIME" (not MIME-NO-LINEFEEDS), to preserve pre-2.12
// behavior
defaultBase64Variant(Base64Variants.MIME);
// 04-Jun-2020, tatu: Use new (2.12) "CoercionConfigs" to support coercion
// from empty and blank Strings to "empty" POJOs etc
_coercionConfigs.defaultCoercions()
// To allow indentation without problems, need to accept blank String as empty:
.setAcceptBlankAsEmpty(Boolean.TRUE)
// and then coercion from empty String to empty value, in general
.setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsEmpty)
;
// 03-May-2021, tatu: ... except make sure to keep "empty to Null" for
// scalar types...
_coercionConfigs.findOrCreateCoercion(LogicalType.Integer)
.setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsNull);
_coercionConfigs.findOrCreateCoercion(LogicalType.Float)
.setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsNull);
_coercionConfigs.findOrCreateCoercion(LogicalType.Boolean)
.setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsNull);
}
@Override
public XmlMapper build() {
return new XmlMapper(this);
}
@Override
protected MapperBuilderState _saveState() {
return new XmlBuilderState(this);
}
/**
* NOTE: despite being public not exposed as part of API
*
* @param state State to restore builder from
*/
@SuppressWarnings("exports")
public Builder(XmlBuilderState state) {
super(state);
_defaultUseWrapper = state._defaultUseWrapper;
_nameForTextElement = state._nameForTextElement;
}
/*
/******************************************************************
/* Default value overrides
/******************************************************************
*/
@Override
protected SerializationContexts _defaultSerializationContexts() {
return new XmlSerializationContexts();
}
@Override
protected DeserializationContexts _defaultDeserializationContexts() {
return new XmlDeserializationContexts();
}
/**
* Overridden to (try to) ensure we use XML-compatible default indenter
*/
@Override
protected PrettyPrinter _defaultPrettyPrinter() {
return DEFAULT_XML_PRETTY_PRINTER;
}
/*
/******************************************************************
/* Overrides for polymorphic type handling
/******************************************************************
*/
@Override
protected TypeResolverBuilder<?> _defaultDefaultTypingResolver(PolymorphicTypeValidator ptv,
DefaultTyping applicability,
JsonTypeInfo.As includeAs) {
return new DefaultingXmlTypeResolverBuilder(ptv, applicability, includeAs);
}
@Override
protected TypeResolverBuilder<?> _defaultDefaultTypingResolver(PolymorphicTypeValidator ptv,
DefaultTyping applicability,
String propertyName) {
return new DefaultingXmlTypeResolverBuilder(ptv, applicability, propertyName);
}
// Since WRAPPER_ARRAY does not work well, map to WRAPPER_OBJECT
@Override
public Builder activateDefaultTyping(PolymorphicTypeValidator ptv, DefaultTyping dti) {
return activateDefaultTyping(ptv, dti, JsonTypeInfo.As.WRAPPER_OBJECT);
}
/*
/******************************************************************
/* XML format features
/******************************************************************
*/
public Builder enable(XmlReadFeature... features) {
for (XmlReadFeature f : features) {
_formatReadFeatures |= f.getMask();
}
return this;
}
public Builder disable(XmlReadFeature... features) {
for (XmlReadFeature f : features) {
_formatReadFeatures &= ~f.getMask();
}
return this;
}
public Builder configure(XmlReadFeature feature, boolean state)
{
if (state) {
_formatReadFeatures |= feature.getMask();
} else {
_formatReadFeatures &= ~feature.getMask();
}
return this;
}
public Builder enable(XmlWriteFeature... features) {
for (XmlWriteFeature f : features) {
_formatWriteFeatures |= f.getMask();
}
return this;
}
public Builder disable(XmlWriteFeature... features) {
for (XmlWriteFeature f : features) {
_formatWriteFeatures &= ~f.getMask();
}
return this;
}
public Builder configure(XmlWriteFeature feature, boolean state)
{
if (state) {
_formatWriteFeatures |= feature.getMask();
} else {
_formatWriteFeatures &= ~feature.getMask();
}
return this;
}
/**
* The builder returned uses default settings more closely
* matching the default configs used in Jackson 2.x versions.
* <p>
* This method is still a work in progress and may not yet fully replicate the
* default settings of Jackson 2.x.
* </p>
*/
@Override
public Builder configureForJackson2() {
return super.configureForJackson2()
.disable(XmlWriteFeature.WRITE_NULLS_AS_XSI_NIL)
.disable(XmlWriteFeature.UNWRAP_ROOT_OBJECT_NODE)
.disable(XmlWriteFeature.AUTO_DETECT_XSI_TYPE)
.disable(XmlWriteFeature.WRITE_XML_SCHEMA_CONFORMING_FLOATS)
.disable(XmlReadFeature.AUTO_DETECT_XSI_TYPE);
}
/*
/******************************************************************
/* XML specific additional config
/******************************************************************
*/
public boolean defaultUseWrapper() {
return _defaultUseWrapper;
}
/**
* Determination of whether indexed properties (arrays, Lists) that are not explicitly
* annotated (with {@link tools.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper}
* or equivalent) should default to using implicit wrapper (with same name as property) or not.
* If enabled, wrapping is used by default; if false, it is not.
*<p>
* Note that JAXB annotation introspector always assumes "do not wrap by default".
* Jackson annotations have different default due to backwards compatibility.
*/
public Builder defaultUseWrapper(boolean b) {
if (_defaultUseWrapper != b) {
_defaultUseWrapper = b;
AnnotationIntrospector ai0 = annotationIntrospector();
for (AnnotationIntrospector ai : ai0.allIntrospectors()) {
if (ai instanceof JacksonXmlAnnotationIntrospector) {
((JacksonXmlAnnotationIntrospector) ai).setDefaultUseWrapper(b);
}
}
}
return this;
}
public String nameForTextElement() {
return _nameForTextElement;
}
/**
* Name used for pseudo-property used for returning XML Text value (cdata within
* element, which does not have actual element name to use) as a named value (since
* JSON data model just has named values, except for arrays).
* Defaults to empty String, but may be changed for interoperability reasons:
* JAXB, for example, uses "value" as name.
*/
public Builder nameForTextElement(String elem) {
if (elem == null) {
elem = "";
}
_nameForTextElement = elem;
_streamFactory = ((XmlFactory) _streamFactory).withNameForTextElement(elem);
return this;
}
}
/**
* Saved configuration entity to use with builder for {@link XmlMapper} instances.
*
* @since 3.0
*/
protected static class XmlBuilderState extends MapperBuilderState
implements java.io.Serializable // important!
{
private static final long serialVersionUID = 3L;
protected final boolean _defaultUseWrapper;
protected final String _nameForTextElement;
public XmlBuilderState(Builder src) {
super(src);
_defaultUseWrapper = src._defaultUseWrapper;
_nameForTextElement = src._nameForTextElement;
}
// We also need actual instance of state as base class can not implement logic
// for reinstating mapper (via mapper builder) from state.
@Override
protected Object readResolve() {
return new Builder(this).build();
}
}
/*
/**********************************************************************
/* Life-cycle: construction 3.0 style
/**********************************************************************
*/
public XmlMapper(Builder b)
{
super(b);
}
public static XmlMapper.Builder xmlBuilder() {
return new XmlMapper.Builder(new XmlFactory());
}
public static XmlMapper.Builder builder() {
return new XmlMapper.Builder(new XmlFactory());
}
public static XmlMapper.Builder builder(XmlFactory streamFactory) {
return new XmlMapper.Builder(streamFactory);
}
/**
* The builder returned uses default settings more closely
* matching the default configs used in Jackson 2.x versions.
* <p>
* This method is still a work in progress and may not yet fully replicate the
* default settings of Jackson 2.x.
* </p>
*/
public static XmlMapper.Builder builderWithJackson2Defaults() {
return builder(XmlFactory.builderWithJackson2Defaults().build())
.configureForJackson2();
}
@SuppressWarnings("unchecked")
@Override
public XmlMapper.Builder rebuild() {
return new XmlMapper.Builder((XmlBuilderState) _savedBuilderState);
}
/*
/**********************************************************************
/* Life-cycle: JDK serialization support
/**********************************************************************
*/
// 27-Feb-2018, tatu: Not sure why but it seems base class definitions
// are not sufficient alone; sub-classes must re-define.
@Override
protected Object writeReplace() {
return _savedBuilderState;
}
@Override
protected Object readResolve() {
throw new IllegalStateException("Should never deserialize `"+getClass().getName()+"` directly");
}
/*
/**********************************************************************
/* Life-cycle: construction, legacy
/**********************************************************************
*/
public XmlMapper() {
this(new XmlFactory());
}
public XmlMapper(XmlFactory xmlFactory)
{
this(new Builder(xmlFactory));
/*
// Need to override serializer provider (due to root name handling);
// deserializer provider fine as is
super(xmlFactory, new XmlSerializationContext(xmlFactory, new XmlRootNameLookup()), null);
_xmlModule = module;
// but all the rest is done via Module interface!
if (module != null) {
registerModule(module);
}
// 19-May-2015, tatu: Must ensure we use XML-specific indenter
_serializationConfig = _serializationConfig.withDefaultPrettyPrinter(DEFAULT_XML_PRETTY_PRINTER);
// 21-Jun-2017, tatu: Seems like there are many cases in XML where ability to coerce empty
// String into `null` (where it otherwise is an error) is very useful.
enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
*/
}
/*
/**********************************************************************
/* Life-cycle, shared "vanilla" (default configuration) instance
/**********************************************************************
*/
/**
* Accessor method for getting globally shared "default" {@link XmlMapper}
* instance: one that has default configuration, no (custom) modules registered, no
* config overrides. Usable mostly when dealing "untyped" or Tree-style
* content reading and writing.
*/
public static XmlMapper shared() {
return SharedWrapper.wrapped();
}
/*
/**********************************************************************
/* Access to configuration settings
/**********************************************************************
*/
@Override
public Version version() {
return PackageVersion.VERSION;
}
@Override
public XmlFactory tokenStreamFactory() {
return (XmlFactory) _streamFactory;
}
/*
/**********************************************************************
/* XML-specific access
/**********************************************************************
*/
/**
* Overloaded variant that allows constructing {@link FromXmlParser}
* for given Stax {@link XMLStreamReader}.
*/
public FromXmlParser createParser(XMLStreamReader r) throws IOException {
DeserializationContext ctxt = _deserializationContext();
return tokenStreamFactory().createParser(ctxt, r);
}
/**
* Overloaded variant that allows constructing {@link ToXmlGenerator}
* for given Stax {@link XMLStreamWriter}.
*/
public ToXmlGenerator createGenerator(XMLStreamWriter w) throws IOException {
SerializationContextExt prov = _serializationContext(serializationConfig());
return tokenStreamFactory().createGenerator(prov, w);
}
/**
* Method for reading a single XML value from given XML-specific input
* source; useful for incremental data-binding, combining traversal using
* basic Stax {@link XMLStreamReader} with data-binding by Jackson.
*/
public <T> T readValue(XMLStreamReader r, Class<T> valueType) throws IOException {
return readValue(r, _typeFactory.constructType(valueType));
}
/**
* Method for reading a single XML value from given XML-specific input
* source; useful for incremental data-binding, combining traversal using
* basic Stax {@link XMLStreamReader} with data-binding by Jackson.
*/
public <T> T readValue(XMLStreamReader r, TypeReference<T> valueTypeRef) throws IOException {
return readValue(r, _typeFactory.constructType(valueTypeRef));
}
/**
* Method for reading a single XML value from given XML-specific input
* source; useful for incremental data-binding, combining traversal using
* basic Stax {@link XMLStreamReader} with data-binding by Jackson.
*/
@SuppressWarnings("resource")
public <T> T readValue(XMLStreamReader r, JavaType valueType) throws IOException
{
return super.readValue(createParser(r), valueType);
}
/**
* Method for serializing given value using specific {@link XMLStreamReader}:
* useful when building large XML files by binding individual items, one at
* a time.
*/
@SuppressWarnings("resource")
public void writeValue(XMLStreamWriter w, Object value) throws IOException
{
// 04-Oct-2017, tatu: Unfortunately can not simply delegate to super-class implementation
// because we need the context first...
ToXmlGenerator g = createGenerator(w);
final SerializationConfig config = serializationConfig();
if (config.isEnabled(SerializationFeature.CLOSE_CLOSEABLE) && (value instanceof Closeable)) {
_writeCloseableValue(g, value, config);
} else {
_serializationContext(config).serializeValue(g, value);
if (config.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) {
g.flush();
}
}
}
/*
/**********************************************************
/* Helper class(es)
/**********************************************************
*/
/**
* Helper class to contain dynamically constructed "shared" instance of
* mapper, should one be needed via {@link #shared}.
*/
private final static class SharedWrapper {
private final static XmlMapper MAPPER = XmlMapper.builder().build();
public static XmlMapper wrapped() { return MAPPER; }
}
}