-
-
Notifications
You must be signed in to change notification settings - Fork 220
/
ToXmlGenerator.java
1413 lines (1291 loc) · 49.1 KB
/
ToXmlGenerator.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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.fasterxml.jackson.dataformat.xml.ser;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import com.fasterxml.jackson.dataformat.xml.XmlNameProcessor;
import org.codehaus.stax2.XMLStreamWriter2;
import org.codehaus.stax2.ri.Stax2WriterAdapter;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.base.GeneratorBase;
import com.fasterxml.jackson.core.io.IOContext;
import com.fasterxml.jackson.core.json.JsonWriteContext;
import com.fasterxml.jackson.core.util.JacksonFeatureSet;
import com.fasterxml.jackson.dataformat.xml.XmlPrettyPrinter;
import com.fasterxml.jackson.dataformat.xml.util.DefaultXmlPrettyPrinter;
import com.fasterxml.jackson.dataformat.xml.util.StaxUtil;
/**
* {@link JsonGenerator} that outputs JAXB-style XML output instead of JSON content.
* Operation requires calling code (usually either standard Jackson serializers,
* or in some cases (like <code>BeanSerializer</code>) customized ones) to do
* additional configuration calls beyond regular {@link JsonGenerator} API,
* mostly to pass namespace information.
*/
public class ToXmlGenerator
// non-final since 2.12 but only sub-class if you really know what you are doing...
extends GeneratorBase
{
/**
* If we support optional definition of element names, this is the element
* name to use...
*/
protected final static String DEFAULT_UNKNOWN_ELEMENT = "unknown";
/**
* Enumeration that defines all togglable extra XML-specific features
*/
public enum Feature implements FormatFeature
{
/**
* Feature that controls whether XML declaration should be written before
* when generator is initialized (true) or not (false)
*/
WRITE_XML_DECLARATION(false),
/**
* Feature that controls whether output should be done as XML 1.1; if so,
* certain aspects may differ from default (1.0) processing: for example,
* XML declaration will be automatically added (regardless of setting
* <code>WRITE_XML_DECLARATION</code>) as this is required for reader to
* know to use 1.1 compliant handling. XML 1.1 can be used to allow quoted
* control characters (Ascii codes 0 through 31) as well as additional linefeeds
* and name characters.
*/
WRITE_XML_1_1(false),
/**
* Feature that controls whether serialization of Java {@code null} values adds
* XML attribute of `xsi:nil`, as defined by XML Schema (see
* <a href="https://www.oreilly.com/library/view/xml-in-a/0596007647/re166.html">this article</a>
* for details) or not.
* If enabled, `xsi:nil` attribute will be added to the empty element; if disabled,
* it will not.
*<p>
* Feature is disabled by default for backwards compatibility.
*
* @since 2.10
*/
WRITE_NULLS_AS_XSI_NIL(false),
/**
* Feature that determines writing of root values of type {@code ObjectNode}
* ({@code JsonNode} subtype that represents Object content values),
* regarding XML output.
* If enabled and {@code ObjectNode} has exactly one entry (key/value pair),
* then key of that entry is used as the root element name (and value
* is written as contents. Otherwise (if feature disabled, or if root
* {@code ObjectNode} has any other number of key/value entries,
* root element name is determined using normal logic (either explicitly
* configured, or {@code ObjectNode} otherwise).
*<p>
* Default setting is {@code disabled} in Jackson 2.x, for backwards compatibility:
* likely to be changed in 3.0 to {@code enabled}.
*
* @since 2.13
*/
UNWRAP_ROOT_OBJECT_NODE(false),
;
final boolean _defaultState;
final int _mask;
/**
* Method that calculates bit set (flags) of all features that
* are enabled by default.
*/
public static int collectDefaults()
{
int flags = 0;
for (Feature f : values()) {
if (f.enabledByDefault()) {
flags |= f.getMask();
}
}
return flags;
}
private Feature(boolean defaultState) {
_defaultState = defaultState;
_mask = (1 << ordinal());
}
@Override public boolean enabledByDefault() { return _defaultState; }
@Override public int getMask() { return _mask; }
@Override public boolean enabledIn(int flags) { return (flags & getMask()) != 0; }
}
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
protected final XMLStreamWriter2 _xmlWriter;
protected final XMLStreamWriter _originalXmlWriter;
/**
* Marker flag set if the underlying stream writer has to emulate
* Stax2 API: this is problematic if trying to use {@link #writeRaw} calls.
*/
protected final boolean _stax2Emulation;
/**
* @since 2.16
*/
protected final StreamWriteConstraints _streamWriteConstraints;
/**
* Bit flag composed of bits that indicate which
* {@link ToXmlGenerator.Feature}s
* are enabled.
*/
protected int _formatFeatures;
/**
* We may need to use XML-specific indentation as well
*/
protected XmlPrettyPrinter _xmlPrettyPrinter;
/**
* Escapes names with invalid XML characters
*
* @since 2.14
*/
protected XmlNameProcessor _nameProcessor;
/*
/**********************************************************
/* XML Output state
/**********************************************************
*/
/**
* Marker set when {@link #initGenerator()} has been called or not.
*
* @since 2.2
*/
protected boolean _initialized;
/**
* Element or attribute name to use for next output call.
* Assigned by either code that initiates serialization
* or bean serializer.
*/
protected QName _nextName = null;
/**
* Marker flag that indicates whether next name to write
* implies an attribute (true) or element (false)
*/
protected boolean _nextIsAttribute = false;
/**
* Marker flag used to indicate that the next write of a (property)
* value should be done without using surrounding start/end
* elements. Flag is to be cleared once unwrapping has been triggered
* once.
*/
protected boolean _nextIsUnwrapped = false;
/**
* Marker flag used to indicate that the next write of a (property)
* value should be as CData
*/
protected boolean _nextIsCData = false;
/**
* To support proper serialization of arrays it is necessary to keep
* stack of element names, so that we can "revert" to earlier
*/
protected LinkedList<QName> _elementNameStack = new LinkedList<QName>();
/**
* Reusable internal value object
*
* @since 2.14
*/
protected XmlNameProcessor.XmlName _nameToEncode = new XmlNameProcessor.XmlName();
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
public ToXmlGenerator(IOContext ctxt, int stdFeatures, int xmlFeatures,
ObjectCodec codec, XMLStreamWriter sw, XmlNameProcessor nameProcessor)
{
super(stdFeatures, codec, ctxt);
_formatFeatures = xmlFeatures;
_streamWriteConstraints = ctxt.streamWriteConstraints();
_originalXmlWriter = sw;
_xmlWriter = Stax2WriterAdapter.wrapIfNecessary(sw);
_stax2Emulation = (_xmlWriter != sw);
_nameProcessor = nameProcessor;
_xmlPrettyPrinter = (_cfgPrettyPrinter instanceof XmlPrettyPrinter) ?
(XmlPrettyPrinter) _cfgPrettyPrinter : null;
}
/**
* Method called before writing any other output, to optionally
* output XML declaration.
*/
public void initGenerator() throws IOException
{
if (_initialized) {
return;
}
_initialized = true;
try {
if (Feature.WRITE_XML_1_1.enabledIn(_formatFeatures)) {
_xmlWriter.writeStartDocument("UTF-8", "1.1");
} else if (Feature.WRITE_XML_DECLARATION.enabledIn(_formatFeatures)) {
_xmlWriter.writeStartDocument("UTF-8", "1.0");
} else {
return;
}
// as per [dataformat-xml#172], try adding indentation
if (_xmlPrettyPrinter != null) {
// ... but only if it is likely to succeed:
if (!_stax2Emulation) {
_xmlPrettyPrinter.writePrologLinefeed(_xmlWriter);
}
}
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
/*
/**********************************************************
/* Overridden methods, configuration
/**********************************************************
*/
@Override
protected PrettyPrinter _constructDefaultPrettyPrinter() {
return new DefaultXmlPrettyPrinter();
}
@Override
public JsonGenerator setPrettyPrinter(PrettyPrinter pp) {
_cfgPrettyPrinter = pp;
_xmlPrettyPrinter = (pp instanceof XmlPrettyPrinter) ?
(XmlPrettyPrinter) pp : null;
return this;
}
@Override
public Object getOutputTarget() {
// Stax2 does not expose underlying target, so best we can do is to return
// the Stax XMLStreamWriter instance:
return _originalXmlWriter;
}
/**
* Stax2 does not expose buffered content amount, so we can only return
* <code>-1</code> from here
*/
@Override
public int getOutputBuffered() {
return -1;
}
@Override
public int getFormatFeatures() {
return _formatFeatures;
}
@Override // since 2.7
public JsonGenerator overrideFormatFeatures(int values, int mask)
{
int oldF = _formatFeatures;
int newF = (_formatFeatures & ~mask) | (values & mask);
if (oldF != newF) {
_formatFeatures = newF;
}
return this;
}
/*
/**********************************************************
/* Extended API, configuration
/**********************************************************
*/
@Override
public StreamWriteConstraints streamWriteConstraints() {
return _streamWriteConstraints;
}
public ToXmlGenerator enable(Feature f) {
_formatFeatures |= f.getMask();
return this;
}
public ToXmlGenerator disable(Feature f) {
_formatFeatures &= ~f.getMask();
return this;
}
public final boolean isEnabled(Feature f) {
return (_formatFeatures & f.getMask()) != 0;
}
public ToXmlGenerator configure(Feature f, boolean state) {
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
@Override
public boolean canWriteFormattedNumbers() { return true; }
@Override // @since 2.12
public JacksonFeatureSet<StreamWriteCapability> getWriteCapabilities() {
return DEFAULT_TEXTUAL_WRITE_CAPABILITIES;
}
// @since 2.7.5
public boolean inRoot() {
return _writeContext.inRoot();
}
/*
/**********************************************************
/* Extended API, access to some internal components
/**********************************************************
*/
/**
* Method that allows application direct access to underlying
* Stax {@link XMLStreamWriter}. Note that use of writer is
* discouraged, and may interfere with processing of this writer;
* however, occasionally it may be necessary.
*<p>
* Note: writer instance will always be of type
* {@link org.codehaus.stax2.XMLStreamWriter2} (including
* Typed Access API) so upcasts are safe.
*/
public XMLStreamWriter getStaxWriter() {
return _xmlWriter;
}
/*
/**********************************************************
/* Extended API, passing XML specific settings
/**********************************************************
*/
public void setNextIsAttribute(boolean isAttribute)
{
_nextIsAttribute = isAttribute;
}
public void setNextIsUnwrapped(boolean isUnwrapped)
{
_nextIsUnwrapped = isUnwrapped;
}
public void setNextIsCData(boolean isCData)
{
_nextIsCData = isCData;
}
public final void setNextName(QName name)
{
_nextName = name;
}
/**
* Method that does same as {@link #setNextName}, unless
* a name has already been set.
*
* @since 2.1.2
*/
public final boolean setNextNameIfMissing(QName name)
{
if (_nextName == null) {
_nextName = name;
return true;
}
return false;
}
/**
* Methdod called when a structured (collection, array, map) is being
* output.
*
* @param wrapperName Element used as wrapper around elements, if any (null if none)
* @param wrappedName Element used around individual content items (can not
* be null)
*/
public void startWrappedValue(QName wrapperName, QName wrappedName) throws IOException
{
if (wrapperName != null) {
try {
if (_xmlPrettyPrinter != null) {
_xmlPrettyPrinter.writeStartElement(_xmlWriter,
wrapperName.getNamespaceURI(), wrapperName.getLocalPart());
} else {
_xmlWriter.writeStartElement(wrapperName.getNamespaceURI(), wrapperName.getLocalPart());
}
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
this.setNextName(wrappedName);
}
/**
* Method called after a structured collection output has completed
*/
public void finishWrappedValue(QName wrapperName, QName wrappedName) throws IOException
{
// First: wrapper to close?
if (wrapperName != null) {
try {
if (_xmlPrettyPrinter != null) {
_xmlPrettyPrinter.writeEndElement(_xmlWriter, _writeContext.getEntryCount());
} else {
_xmlWriter.writeEndElement();
}
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
}
/**
* Trivial helper method called when to add a replicated wrapper name
*
* @since 2.2
*/
public void writeRepeatedFieldName() throws IOException
{
if (_writeContext.writeFieldName(_nextName.getLocalPart()) == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
}
/*
/**********************************************************
/* JsonGenerator method overrides
/**********************************************************
*/
/* Most overrides in this section are just to make methods final,
* to allow better inlining...
*/
@Override
public final void writeFieldName(String name) throws IOException
{
if (_writeContext.writeFieldName(name) == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
// Should this ever get called?
String ns = (_nextName == null) ? "" : _nextName.getNamespaceURI();
_nameToEncode.namespace = ns;
_nameToEncode.localPart = name;
_nameProcessor.encodeName(_nameToEncode);
setNextName(new QName(_nameToEncode.namespace, _nameToEncode.localPart));
}
@Override
public final void writeStringField(String fieldName, String value) throws IOException
{
writeFieldName(fieldName);
writeString(value);
}
// 03-Aug-2017, tatu: We could use this as mentioned in comment below BUT
// since there is no counterpart for deserialization this will not
// help us. Approaches that could/would help probably require different
// handling...
//
// See [dataformat-xml#4] for more context.
/*
// @since 2.9
public WritableTypeId writeTypePrefix(WritableTypeId typeIdDef) throws IOException
{
// 03-Aug-2017, tatu: Due to XML oddities, we do need to massage things
// a bit: specifically, change WRAPPER_ARRAY into WRAPPER_OBJECT, always
if (typeIdDef.include == WritableTypeId.Inclusion.WRAPPER_ARRAY) {
typeIdDef.include = WritableTypeId.Inclusion.WRAPPER_OBJECT;
}
return super.writeTypePrefix(typeIdDef);
}
*/
/*
/**********************************************************
/* JsonGenerator output method implementations, structural
/**********************************************************
*/
@Override
public final void writeStartArray() throws IOException
{
_verifyValueWrite("start an array");
_writeContext = _writeContext.createChildArrayContext();
streamWriteConstraints().validateNestingDepth(_writeContext.getNestingDepth());
if (_cfgPrettyPrinter != null) {
_cfgPrettyPrinter.writeStartArray(this);
} else {
// nothing to do here; no-operation
}
}
@Override
public final void writeEndArray() throws IOException
{
if (!_writeContext.inArray()) {
_reportError("Current context not Array but "+_writeContext.typeDesc());
}
if (_cfgPrettyPrinter != null) {
_cfgPrettyPrinter.writeEndArray(this, _writeContext.getEntryCount());
} else {
// nothing to do here; no-operation
}
_writeContext = _writeContext.getParent();
}
@Override
public final void writeStartObject() throws IOException
{
_verifyValueWrite("start an object");
_writeContext = _writeContext.createChildObjectContext();
streamWriteConstraints().validateNestingDepth(_writeContext.getNestingDepth());
if (_cfgPrettyPrinter != null) {
_cfgPrettyPrinter.writeStartObject(this);
} else {
_handleStartObject();
}
}
@Override
public final void writeEndObject() throws IOException
{
if (!_writeContext.inObject()) {
_reportError("Current context not Object but "+_writeContext.typeDesc());
}
_writeContext = _writeContext.getParent();
if (_cfgPrettyPrinter != null) {
// as per [Issue#45], need to suppress indentation if only attributes written:
int count = _nextIsAttribute ? 0 : _writeContext.getEntryCount();
_cfgPrettyPrinter.writeEndObject(this, count);
} else {
_handleEndObject();
}
}
// note: public just because pretty printer needs to make a callback
public final void _handleStartObject() throws IOException
{
if (_nextName == null) {
handleMissingName();
}
// Need to keep track of names to make Lists work correctly
_elementNameStack.addLast(_nextName);
try {
_xmlWriter.writeStartElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
// note: public just because pretty printer needs to make a callback
public final void _handleEndObject() throws IOException
{
// We may want to repeat same element, so:
if (_elementNameStack.isEmpty()) {
throw new JsonGenerationException("Can not write END_ELEMENT without open START_ELEMENT", this);
}
_nextName = _elementNameStack.removeLast();
try {
// note: since attributes don't nest, can only have one attribute active, so:
_nextIsAttribute = false;
_xmlWriter.writeEndElement();
// [databind-xml#172]: possibly also need indentation
if (_elementNameStack.isEmpty() && (_xmlPrettyPrinter != null)) {
// ... but only if it is likely to succeed:
if (!_stax2Emulation) {
_xmlPrettyPrinter.writePrologLinefeed(_xmlWriter);
}
}
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
/*
/**********************************************************
/* Output method implementations, textual
/**********************************************************
*/
@Override
public void writeFieldName(SerializableString name) throws IOException
{
writeFieldName(name.getValue());
}
@Override
public void writeString(String text) throws IOException
{
if (text == null) { // [dataformat-xml#413]
writeNull();
return;
}
_verifyValueWrite("write String value");
if (_nextName == null) {
handleMissingName();
}
try {
if (_nextIsAttribute) { // must write attribute name and value with one call
_xmlWriter.writeAttribute(_nextName.getNamespaceURI(), _nextName.getLocalPart(), text);
} else if (checkNextIsUnwrapped()) {
// [dataformat-xml#56] Should figure out how to prevent indentation for end element
// but for now, let's just make sure structure is correct
//if (_xmlPrettyPrinter != null) { ... }
if(_nextIsCData) {
_xmlWriter.writeCData(text);
} else {
_xmlWriter.writeCharacters(text);
}
} else if (_xmlPrettyPrinter != null) {
_xmlPrettyPrinter.writeLeafElement(_xmlWriter,
_nextName.getNamespaceURI(), _nextName.getLocalPart(),
text, _nextIsCData);
} else {
_xmlWriter.writeStartElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
if(_nextIsCData) {
_xmlWriter.writeCData(text);
} else {
_xmlWriter.writeCharacters(text);
}
_xmlWriter.writeEndElement();
}
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
@Override
public void writeString(char[] text, int offset, int len) throws IOException
{
_verifyValueWrite("write String value");
if (_nextName == null) {
handleMissingName();
}
try {
if (_nextIsAttribute) {
_xmlWriter.writeAttribute(_nextName.getNamespaceURI(), _nextName.getLocalPart(), new String(text, offset, len));
} else if (checkNextIsUnwrapped()) {
// should we consider pretty-printing or not?
if(_nextIsCData) {
_xmlWriter.writeCData(text, offset, len);
} else {
_xmlWriter.writeCharacters(text, offset, len);
}
} else if (_xmlPrettyPrinter != null) {
_xmlPrettyPrinter.writeLeafElement(_xmlWriter,
_nextName.getNamespaceURI(), _nextName.getLocalPart(),
text, offset, len, _nextIsCData);
} else {
_xmlWriter.writeStartElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
if(_nextIsCData) {
_xmlWriter.writeCData(text, offset, len);
} else {
_xmlWriter.writeCharacters(text, offset, len);
}
_xmlWriter.writeEndElement();
}
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
@Override
public void writeString(SerializableString text) throws IOException {
writeString(text.getValue());
}
@Override
public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException
{
// could add support for this case if we really want it (and can make Stax2 support it)
_reportUnsupportedOperation();
}
@Override
public void writeUTF8String(byte[] text, int offset, int length) throws IOException
{
// could add support for this case if we really want it (and can make Stax2 support it)
_reportUnsupportedOperation();
}
/*
/**********************************************************
/* Output method implementations, unprocessed ("raw")
/**********************************************************
*/
@Override
public void writeRawValue(String text) throws IOException {
// [dataformat-xml#39]
if (_stax2Emulation) {
_reportUnimplementedStax2("writeRawValue");
}
try {
_verifyValueWrite("write raw value");
if (_nextName == null) {
handleMissingName();
}
if (_nextIsAttribute) {
_xmlWriter.writeAttribute(_nextName.getNamespaceURI(), _nextName.getLocalPart(), text);
} else if (checkNextIsUnwrapped()) {
_xmlWriter.writeRaw(text);
} else {
_xmlWriter.writeStartElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
_xmlWriter.writeRaw(text);
_xmlWriter.writeEndElement();
}
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
@Override
public void writeRawValue(String text, int offset, int len) throws IOException {
// [dataformat-xml#39]
if (_stax2Emulation) {
_reportUnimplementedStax2("writeRawValue");
}
try {
_verifyValueWrite("write raw value");
if (_nextName == null) {
handleMissingName();
}
if (_nextIsAttribute) {
_xmlWriter.writeAttribute(_nextName.getNamespaceURI(), _nextName.getLocalPart(), text.substring(offset, offset + len));
} else if (checkNextIsUnwrapped()) {
_xmlWriter.writeRaw(text, offset, len);
} else {
_xmlWriter.writeStartElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
_xmlWriter.writeRaw(text, offset, len);
_xmlWriter.writeEndElement();
}
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
@Override
public void writeRawValue(char[] text, int offset, int len) throws IOException {
// [dataformat-xml#39]
if (_stax2Emulation) {
_reportUnimplementedStax2("writeRawValue");
}
_verifyValueWrite("write raw value");
if (_nextName == null) {
handleMissingName();
}
try {
if (_nextIsAttribute) {
_xmlWriter.writeAttribute(_nextName.getNamespaceURI(), _nextName.getLocalPart(), new String(text, offset, len));
} else if (checkNextIsUnwrapped()) {
_xmlWriter.writeRaw(text, offset, len);
} else {
_xmlWriter.writeStartElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
_xmlWriter.writeRaw(text, offset, len);
_xmlWriter.writeEndElement();
}
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
@Override
public void writeRawValue(SerializableString text) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(String text) throws IOException
{
// [dataformat-xml#39]
if (_stax2Emulation) {
_reportUnimplementedStax2("writeRaw");
}
try {
_xmlWriter.writeRaw(text);
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
@Override
public void writeRaw(String text, int offset, int len) throws IOException
{
// [dataformat-xml#39]
if (_stax2Emulation) {
_reportUnimplementedStax2("writeRaw");
}
try {
_xmlWriter.writeRaw(text, offset, len);
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
@Override
public void writeRaw(char[] text, int offset, int len) throws IOException
{
// [dataformat-xml#39]
if (_stax2Emulation) {
_reportUnimplementedStax2("writeRaw");
}
try {
_xmlWriter.writeRaw(text, offset, len);
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
@Override
public void writeRaw(char c) throws IOException
{
writeRaw(String.valueOf(c));
}
/*
/**********************************************************
/* Output method implementations, base64-encoded binary
/**********************************************************
*/
@Override
public void writeBinary(Base64Variant b64variant,
byte[] data, int offset, int len) throws IOException
{
if (data == null) {
writeNull();
return;
}
_verifyValueWrite("write Binary value");
if (_nextName == null) {
handleMissingName();
}
final org.codehaus.stax2.typed.Base64Variant stax2base64v = StaxUtil.toStax2Base64Variant(b64variant);
try {
if (_nextIsAttribute) {
// Stax2 API only has 'full buffer' write method:
byte[] fullBuffer = toFullBuffer(data, offset, len);
_xmlWriter.writeBinaryAttribute(stax2base64v,
"", _nextName.getNamespaceURI(), _nextName.getLocalPart(), fullBuffer);
} else if (checkNextIsUnwrapped()) {
// should we consider pretty-printing or not?
_xmlWriter.writeBinary(stax2base64v, data, offset, len);
} else {
if (_xmlPrettyPrinter != null) {
_xmlPrettyPrinter.writeLeafElement(_xmlWriter,
_nextName.getNamespaceURI(), _nextName.getLocalPart(),
stax2base64v, data, offset, len);
} else {
_xmlWriter.writeStartElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
_xmlWriter.writeBinary(stax2base64v, data, offset, len);
_xmlWriter.writeEndElement();
}
}
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
}
@Override
public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength) throws IOException
{
if (data == null) {
writeNull();
return 0;
}
_verifyValueWrite("write Binary value");
if (_nextName == null) {
handleMissingName();
}
final org.codehaus.stax2.typed.Base64Variant stax2base64v = StaxUtil.toStax2Base64Variant(b64variant);
try {
if (_nextIsAttribute) {
// Stax2 API only has 'full buffer' write method:
byte[] fullBuffer = toFullBuffer(data, dataLength);
_xmlWriter.writeBinaryAttribute(stax2base64v,
"", _nextName.getNamespaceURI(), _nextName.getLocalPart(), fullBuffer);
} else if (checkNextIsUnwrapped()) {
// should we consider pretty-printing or not?
writeStreamAsBinary(stax2base64v, data, dataLength);
} else {
if (_xmlPrettyPrinter != null) {
_xmlPrettyPrinter.writeLeafElement(_xmlWriter,
_nextName.getNamespaceURI(), _nextName.getLocalPart(),
stax2base64v, toFullBuffer(data, dataLength), 0, dataLength);
} else {
_xmlWriter.writeStartElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
writeStreamAsBinary(stax2base64v, data, dataLength);
_xmlWriter.writeEndElement();
}
}
} catch (XMLStreamException e) {
StaxUtil.throwAsGenerationException(e, this);
}
return dataLength;
}
private void writeStreamAsBinary(org.codehaus.stax2.typed.Base64Variant stax2base64v,
InputStream data, int len) throws IOException, XMLStreamException
{
// base64 encodes up to 3 bytes into a 4 bytes string
byte[] tmp = new byte[3];
int offset = 0;
int read;
while((read = data.read(tmp, offset, Math.min(3 - offset, len))) != -1) {
offset += read;
len -= read;
if(offset == 3) {
offset = 0;
_xmlWriter.writeBinary(stax2base64v, tmp, 0, 3);
}
if (len == 0) {
break;
}
}
// we still have < 3 bytes in the buffer
if(offset > 0) {
_xmlWriter.writeBinary(stax2base64v, tmp, 0, offset);
}
}
private byte[] toFullBuffer(byte[] data, int offset, int len)
{
// might already be ok:
if (offset == 0 && len == data.length) {
return data;
}
byte[] result = new byte[len];
if (len > 0) {
System.arraycopy(data, offset, result, 0, len);
}
return result;
}