-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
XmlConverter.java
1189 lines (1074 loc) · 47.3 KB
/
XmlConverter.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://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.apache.camel.converter.jaxp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPathConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.apache.camel.Converter;
import org.apache.camel.Exchange;
import org.apache.camel.StreamCache;
import org.apache.camel.support.CamelContextHelper;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.xml.BytesSource;
import org.apache.camel.util.xml.StringSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A helper class to transform to and from various JAXB types such as {@link Source} and {@link Document}
*/
@Converter(generateBulkLoader = true)
public class XmlConverter {
public static final String OUTPUT_PROPERTIES_PREFIX = "org.apache.camel.xmlconverter.output.";
public static final String DOCUMENT_BUILDER_FACTORY_FEATURE
= "org.apache.camel.xmlconverter.documentBuilderFactory.feature";
public static final String defaultCharset = ObjectHelper.getSystemProperty(Exchange.DEFAULT_CHARSET_PROPERTY, "UTF-8");
private static final String JDK_FALLBACK_TRANSFORMER_FACTORY
= "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
private static final Logger LOG = LoggerFactory.getLogger(XmlConverter.class);
private static final ErrorHandler DOCUMENT_BUILDER_LOGGING_ERROR_HANDLER = new DocumentBuilderLoggingErrorHandler();
private volatile DocumentBuilderFactory documentBuilderFactory;
private volatile TransformerFactory transformerFactory;
private volatile XMLReaderPool xmlReaderPool;
public XmlConverter() {
}
public XmlConverter(DocumentBuilderFactory documentBuilderFactory) {
this.documentBuilderFactory = documentBuilderFactory;
}
/**
* Returns the default set of output properties for conversions.
*/
public Properties defaultOutputProperties() {
Properties properties = new Properties();
properties.put(OutputKeys.ENCODING, defaultCharset);
properties.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
return properties;
}
/**
* Converts the given input Source into the required result
*/
public void toResult(Source source, Result result) throws TransformerException {
toResult(source, result, defaultOutputProperties());
}
/**
* Converts the given input Source into the required result
*/
public void toResult(Source source, Result result, Properties outputProperties) throws TransformerException {
if (source == null) {
return;
}
Transformer transformer = createTransformer();
if (transformer == null) {
throw new TransformerException("Could not create a transformer - JAXP is misconfigured!");
}
transformer.setOutputProperties(outputProperties);
transformer.transform(source, result);
}
/**
* Converts the given string to a QName.
*/
@Converter(order = 1)
public QName toQName(String str) {
if ("NUMBER".equalsIgnoreCase(str)) {
return XPathConstants.NUMBER;
} else if ("STRING".equalsIgnoreCase(str)) {
return XPathConstants.STRING;
} else if ("BOOLEAN".equalsIgnoreCase(str)) {
return XPathConstants.BOOLEAN;
} else if ("NODESET".equalsIgnoreCase(str)) {
return XPathConstants.NODESET;
} else if ("NODE".equalsIgnoreCase(str)) {
return XPathConstants.NODE;
}
return QName.valueOf(str);
}
/**
* Converts the given NodeList to a boolean
*/
@Converter(order = 2)
public Boolean toBoolean(NodeList list) {
return list.getLength() > 0;
}
/**
* Converts the given byte[] to a Source
*/
@Converter(order = 3)
public BytesSource toBytesSource(byte[] data) {
return new BytesSource(data);
}
/**
* Converts the given String to a Source
*/
@Converter(order = 4)
public StringSource toStringSource(String data) {
return new StringSource(data);
}
/**
* Converts the given Document to a DOMSource
*/
@Converter(order = 5)
public DOMSource toDOMSource(Document document) {
return new DOMSource(document);
}
/**
* Converts the given Node to a Source
*/
@Converter(order = 6)
public DOMSource toDOMSource(Node node) throws ParserConfigurationException, TransformerException {
Document document = toDOMDocument(node);
return new DOMSource(document);
}
/**
* Converts the given String to a Source
*/
@Converter(order = 7)
public Source toSource(String data) {
return new StringSource(data);
}
@Converter(order = 8)
public Source toSource(byte[] in) {
return new BytesSource(in);
}
/**
* Converts the given Document to a Source
*/
@Converter(order = 9)
public Source toSource(Document document) {
return new DOMSource(document);
}
@Converter(order = 10)
public Source toSource(StreamCache cache, Exchange exchange) {
byte[] arr = exchange.getContext().getTypeConverter().convertTo(byte[].class, exchange, cache);
return toSource(arr);
}
/**
* Converts the given input Source into text
*/
@Converter(order = 11)
public String toString(Source source, Exchange exchange) throws TransformerException {
if (source == null) {
return null;
} else if (source instanceof StringSource) {
return ((StringSource) source).getText();
} else if (source instanceof BytesSource) {
return new String(((BytesSource) source).getData());
} else {
StringWriter buffer = new StringWriter();
if (exchange != null) {
// check the camelContext properties first
Properties properties
= CamelContextHelper.getCamelPropertiesWithPrefix(OUTPUT_PROPERTIES_PREFIX, exchange.getContext());
if (!properties.isEmpty()) {
toResult(source, new StreamResult(buffer), properties);
return buffer.toString();
}
}
// using the old way to deal with it
toResult(source, new StreamResult(buffer));
return buffer.toString();
}
}
/**
* Converts the given input Source into bytes
*/
@Converter(order = 12)
public byte[] toByteArray(Source source, Exchange exchange) throws TransformerException {
if (source instanceof BytesSource) {
return ((BytesSource) source).getData();
} else {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
if (exchange != null) {
// check the camelContext properties first
Properties properties = CamelContextHelper.getCamelPropertiesWithPrefix(OUTPUT_PROPERTIES_PREFIX,
exchange.getContext());
if (!properties.isEmpty()) {
toResult(source, new StreamResult(buffer), properties);
return buffer.toByteArray();
}
}
// using the old way to deal with it
toResult(source, new StreamResult(buffer));
return buffer.toByteArray();
}
}
/**
* Converts the source instance to a {@link DOMSource} or returns null if the conversion is not supported (making it
* easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 13)
public DOMSource toDOMSource(String text)
throws ParserConfigurationException, IOException, SAXException, TransformerException {
Source source = toSource(text);
return toDOMSourceFromStream((StreamSource) source, null);
}
/**
* Converts the source instance to a {@link DOMSource} or returns null if the conversion is not supported (making it
* easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 14)
public DOMSource toDOMSource(byte[] bytes) throws IOException, SAXException, ParserConfigurationException {
InputStream is = new ByteArrayInputStream(bytes);
try {
return toDOMSource(is, null);
} finally {
IOHelper.close(is);
}
}
/**
* Converts the source instance to a {@link SAXSource} or returns null if the conversion is not supported (making it
* easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 15)
public SAXSource toSAXSource(String source, Exchange exchange) throws SAXException, TransformerException {
return toSAXSource(toSource(source), exchange);
}
/**
* Converts the source instance to a {@link StAXSource} or returns null if the conversion is not supported (making
* it easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 16)
public StAXSource toStAXSource(String source, Exchange exchange) throws XMLStreamException {
XMLStreamReader r = new StaxConverter().createXMLStreamReader(new StringReader(source));
return new StAXSource(r);
}
/**
* Converts the source instance to a {@link StAXSource} or returns null if the conversion is not supported (making
* it easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 17)
public StAXSource toStAXSource(byte[] in, Exchange exchange) throws XMLStreamException {
XMLStreamReader r = new StaxConverter().createXMLStreamReader(new ByteArrayInputStream(in), exchange);
return new StAXSource(r);
}
/**
* Converts the source instance to a {@link SAXSource} or returns null if the conversion is not supported (making it
* easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 18)
public SAXSource toSAXSource(InputStream source, Exchange exchange) throws SAXException, TransformerException {
return toSAXSource(toStreamSource(source), exchange);
}
/**
* Converts the source instance to a {@link SAXSource} or returns null if the conversion is not supported (making it
* easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 19)
public SAXSource toSAXSource(byte[] in, Exchange exchange) throws SAXException, TransformerException {
return toSAXSource(toStreamSource(in, exchange), exchange);
}
/**
* Converts the source instance to a {@link StAXSource} or returns null if the conversion is not supported (making
* it easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 20)
public StAXSource toStAXSource(InputStream source, Exchange exchange) throws XMLStreamException {
XMLStreamReader r = new StaxConverter().createXMLStreamReader(source, exchange);
return new StAXSource(r);
}
/**
* Converts the source instance to a {@link SAXSource} or returns null if the conversion is not supported (making it
* easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 21)
public SAXSource toSAXSource(File file, Exchange exchange) throws IOException, SAXException, TransformerException {
InputStream is = IOHelper.buffered(new FileInputStream(file));
return toSAXSource(is, exchange);
}
/**
* Converts the source instance to a {@link StAXSource} or returns null if the conversion is not supported (making
* it easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 22)
public StAXSource toStAXSource(File file, Exchange exchange) throws FileNotFoundException, XMLStreamException {
InputStream is = IOHelper.buffered(new FileInputStream(file));
XMLStreamReader r = new StaxConverter().createXMLStreamReader(is, exchange);
return new StAXSource(r);
}
@Converter(order = 23)
public StreamSource toStreamSource(String in) {
return new StreamSource(new ByteArrayInputStream(in.getBytes()));
}
@Converter(order = 24)
public StreamSource toStreamSource(InputStream in) {
return new StreamSource(in);
}
@Converter(order = 25)
public StreamSource toStreamSource(Reader in) {
return new StreamSource(in);
}
@Converter(order = 26)
public StreamSource toStreamSource(File in) {
return new StreamSource(in);
}
@Converter(order = 27)
public StreamSource toStreamSource(byte[] in, Exchange exchange) {
InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, exchange, in);
return new StreamSource(is);
}
@Converter(order = 28)
public StreamSource toStreamSource(ByteBuffer in, Exchange exchange) {
InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, exchange, in);
return new StreamSource(is);
}
@Converter(order = 29)
public StreamSource toStreamSourceFromSAX(SAXSource source, Exchange exchange) throws TransformerException {
InputSource inputSource = source.getInputSource();
if (inputSource != null) {
if (inputSource.getCharacterStream() != null) {
return new StreamSource(inputSource.getCharacterStream());
}
if (inputSource.getByteStream() != null) {
return new StreamSource(inputSource.getByteStream());
}
}
String result = toString(source, exchange);
return new StringSource(result);
}
@Converter(order = 30)
public StreamSource toStreamSourceFromDOM(DOMSource source, Exchange exchange) throws TransformerException {
String result = toString(source, exchange);
return new StringSource(result);
}
@Converter(order = 31)
public StreamSource toStreamSourceFromStAX(StAXSource source, Exchange exchange) throws TransformerException {
String result = toString(source, exchange);
return new StringSource(result);
}
@Converter(order = 32)
public SAXSource toSAXSourceFromStream(StreamSource source, Exchange exchange) throws SAXException {
InputSource inputSource;
if (source.getReader() != null) {
inputSource = new InputSource(source.getReader());
} else {
inputSource = new InputSource(source.getInputStream());
}
inputSource.setSystemId(source.getSystemId());
inputSource.setPublicId(source.getPublicId());
XMLReader xmlReader = null;
try {
// use the SAXPaserFactory which is set from exchange
if (exchange != null) {
SAXParserFactory sfactory = exchange.getProperty(Exchange.SAXPARSER_FACTORY, SAXParserFactory.class);
if (sfactory != null) {
if (!sfactory.isNamespaceAware()) {
sfactory.setNamespaceAware(true);
}
xmlReader = sfactory.newSAXParser().getXMLReader();
}
}
if (xmlReader == null) {
if (xmlReaderPool == null) {
xmlReaderPool = new XMLReaderPool(createSAXParserFactory());
}
xmlReader = xmlReaderPool.createXMLReader();
}
} catch (Exception ex) {
LOG.warn("Cannot create the SAXParser XMLReader, due to {}", ex.getMessage(), ex);
}
return new SAXSource(xmlReader, inputSource);
}
@Converter(order = 33)
public Reader toReader(StreamSource source) {
Reader r = source.getReader();
if (r == null) {
r = new InputStreamReader(source.getInputStream());
}
return r;
}
@Converter(order = 34)
public Reader toReaderFromSource(Source src, Exchange exchange) throws TransformerException {
StreamSource stSrc = toStreamSource(src, exchange);
Reader r = stSrc.getReader();
if (r == null) {
r = new InputStreamReader(stSrc.getInputStream());
}
return r;
}
@Converter(order = 35)
public DOMSource toDOMSource(StreamCache cache, Exchange exchange)
throws ParserConfigurationException, IOException, SAXException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
cache.writeTo(bos);
return toDOMSource(new ByteArrayInputStream(bos.toByteArray()), exchange);
}
@Converter(order = 36)
public DOMSource toDOMSource(InputStream is, Exchange exchange)
throws ParserConfigurationException, IOException, SAXException {
InputSource source = new InputSource(is);
String systemId = source.getSystemId();
DocumentBuilder builder = createDocumentBuilder(getDocumentBuilderFactory(exchange));
Document document = builder.parse(source);
return new DOMSource(document, systemId);
}
@Converter(order = 37)
public DOMSource toDOMSource(File file, Exchange exchange) throws ParserConfigurationException, IOException, SAXException {
InputStream is = IOHelper.buffered(new FileInputStream(file));
return toDOMSource(is, exchange);
}
@Converter(order = 38)
public DOMSource toDOMSourceFromStream(StreamSource source, Exchange exchange)
throws ParserConfigurationException, IOException, SAXException {
Document document;
String systemId = source.getSystemId();
DocumentBuilder builder = createDocumentBuilder(getDocumentBuilderFactory(exchange));
Reader reader = source.getReader();
if (reader != null) {
document = builder.parse(new InputSource(reader));
} else {
InputStream inputStream = source.getInputStream();
if (inputStream != null) {
InputSource inputsource = new InputSource(inputStream);
inputsource.setSystemId(systemId);
document = builder.parse(inputsource);
} else {
throw new IOException("No input stream or reader available on StreamSource: " + source);
}
}
return new DOMSource(document, systemId);
}
@Converter(order = 39)
public SAXSource toSAXSourceFromDOM(DOMSource source, Exchange exchange) throws TransformerException {
String str = toString(source, exchange);
StringReader reader = new StringReader(str);
return new SAXSource(new InputSource(reader));
}
@Converter(order = 40)
public SAXSource toSAXSourceFromStAX(StAXSource source, Exchange exchange) throws TransformerException {
String str = toString(source, exchange);
StringReader reader = new StringReader(str);
return new SAXSource(new InputSource(reader));
}
@Converter(order = 41)
public DOMSource toDOMSourceFromSAX(SAXSource source)
throws TransformerException {
return new DOMSource(toDOMNodeFromSAX(source));
}
@Converter(order = 42)
public DOMSource toDOMSourceFromStAX(StAXSource source)
throws TransformerException {
return new DOMSource(toDOMNodeFromStAX(source));
}
@Converter(order = 43)
public Node toDOMNodeFromSAX(SAXSource source)
throws TransformerException {
DOMResult result = new DOMResult();
toResult(source, result);
return result.getNode();
}
@Converter(order = 44)
public Node toDOMNodeFromStAX(StAXSource source)
throws TransformerException {
DOMResult result = new DOMResult();
toResult(source, result);
return result.getNode();
}
/**
* Convert a NodeList consisting of just 1 node to a DOM Node.
*
* @param nl the NodeList
* @return the DOM Node
*/
@Converter(order = 45, allowNull = true)
public Node toDOMNodeFromSingleNodeList(NodeList nl) {
return nl.getLength() == 1 ? nl.item(0) : null;
}
/**
* Create a DOM document from the given Node.
*
* If the node is a document, just cast it, if the node is an root element, retrieve its owner element or create a
* new document and import the node.
*/
@Converter(order = 46)
public Document toDOMDocument(final Node node) throws ParserConfigurationException, TransformerException {
ObjectHelper.notNull(node, "node");
// If the node is the document, just cast it
if (node instanceof Document) {
return (Document) node;
// If the node is an element
} else if (node instanceof Element elem) {
// If this is the root element, return its owner document
if (elem.getOwnerDocument().getDocumentElement() == elem) {
return elem.getOwnerDocument();
// else, create a new doc and copy the element inside it
} else {
Document doc = createDocument();
// import node must not occur concurrent on the same node (must be its owner)
// so we need to synchronize on it
synchronized (node.getOwnerDocument()) {
doc.appendChild(doc.importNode(node, true));
}
return doc;
}
// other element types are not handled
} else {
throw new TransformerException("Unable to convert DOM node to a Document: " + node);
}
}
/**
* Converts the given Source into a W3C DOM node
*/
@Converter(order = 47, allowNull = true)
public Node toDOMNode(Source source) throws TransformerException, ParserConfigurationException, IOException, SAXException {
DOMSource domSrc = toDOMSource(source, null);
return domSrc != null ? domSrc.getNode() : null;
}
/**
* Create a DOM element from the given source.
*/
@Converter(order = 48)
public Element toDOMElement(Source source)
throws TransformerException, ParserConfigurationException, IOException, SAXException {
Node node = toDOMNode(source);
return toDOMElement(node);
}
/**
* Create a DOM element from the DOM node. Simply cast if the node is an Element, or return the root element if it
* is a Document.
*/
@Converter(order = 49)
public Element toDOMElement(Node node) throws TransformerException {
// If the node is an document, return the root element
if (node instanceof Document) {
return ((Document) node).getDocumentElement();
// If the node is an element, just cast it
} else if (node instanceof Element) {
return (Element) node;
// Other node types are not handled
} else {
throw new TransformerException("Unable to convert DOM node to an Element");
}
}
/**
* Converts the given data to a DOM document
*
* @param data is the data to be parsed
* @param exchange is the exchange to be used when calling the converter
* @return the parsed document
*/
@Converter(order = 50)
public Document toDOMDocument(byte[] data, Exchange exchange)
throws IOException, SAXException, ParserConfigurationException {
DocumentBuilder documentBuilder = createDocumentBuilder(getDocumentBuilderFactory(exchange));
return documentBuilder.parse(new ByteArrayInputStream(data));
}
@Converter(order = 51)
public Document toDOMDocument(StreamCache cache, Exchange exchange)
throws IOException, SAXException, ParserConfigurationException {
InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, exchange, cache);
return toDOMDocument(is, exchange);
}
/**
* Converts the given {@link InputStream} to a DOM document
*
* @param in is the data to be parsed
* @param exchange is the exchange to be used when calling the converter
* @return the parsed document
*/
@Converter(order = 52)
public Document toDOMDocument(InputStream in, Exchange exchange)
throws IOException, SAXException, ParserConfigurationException {
DocumentBuilder documentBuilder = createDocumentBuilder(getDocumentBuilderFactory(exchange));
if (in instanceof IOHelper.EncodingInputStream encIn) {
// DocumentBuilder detects encoding from XML declaration, so we need to
// revert the converted encoding for the input stream
return documentBuilder.parse(encIn.toOriginalInputStream());
} else {
return documentBuilder.parse(in);
}
}
/**
* Converts the given {@link Reader} to a DOM document
*
* @param in is the data to be parsed
* @param exchange is the exchange to be used when calling the converter
* @return the parsed document
*/
@Converter(order = 53)
public Document toDOMDocument(Reader in, Exchange exchange) throws IOException, SAXException, ParserConfigurationException {
return toDOMDocument(new InputSource(in), exchange);
}
/**
* Converts the given {@link InputSource} to a DOM document
*
* @param in is the data to be parsed
* @param exchange is the exchange to be used when calling the converter
* @return the parsed document
*/
@Converter(order = 54)
public Document toDOMDocument(InputSource in, Exchange exchange)
throws IOException, SAXException, ParserConfigurationException {
DocumentBuilder documentBuilder = createDocumentBuilder(getDocumentBuilderFactory(exchange));
return documentBuilder.parse(in);
}
/**
* Converts the given {@link String} to a DOM document
*
* @param text is the data to be parsed
* @param exchange is the exchange to be used when calling the converter
* @return the parsed document
*/
@Converter(order = 55)
public Document toDOMDocument(String text, Exchange exchange)
throws IOException, SAXException, ParserConfigurationException {
return toDOMDocument(new StringReader(text), exchange);
}
/**
* Converts the given {@link File} to a DOM document
*
* @param file is the data to be parsed
* @param exchange is the exchange to be used when calling the converter
* @return the parsed document
*/
@Converter(order = 56)
public Document toDOMDocument(File file, Exchange exchange) throws IOException, SAXException, ParserConfigurationException {
DocumentBuilder documentBuilder = createDocumentBuilder(getDocumentBuilderFactory(exchange));
return documentBuilder.parse(file);
}
/**
* Create a DOM document from the given source.
*/
@Converter(order = 57)
public Document toDOMDocument(Source source)
throws TransformerException, ParserConfigurationException, IOException, SAXException {
Node node = toDOMNode(source);
if (node != null) {
return toDOMDocument(node);
} else {
return null;
}
}
/**
* Convert a NodeList consisting of just 1 node to a DOM Document. Cannot convert NodeList with length > 1 because
* they require a root node.
*
* @param nl the NodeList
* @return the DOM Document
*/
@Converter(order = 58, allowNull = true)
public Document toDOMDocumentFromSingleNodeList(NodeList nl) throws ParserConfigurationException, TransformerException {
if (nl.getLength() == 1) {
return toDOMDocument(nl.item(0));
} else if (nl instanceof Node) {
// as XML parsers may often have nodes that implement both Node and NodeList then the type converter lookup
// may lookup either a type converter from NodeList or Node. So let's fallback and try with Node
return toDOMDocument((Node) nl);
} else {
return null;
}
}
@Converter(order = 59)
public InputStream toInputStream(DOMSource source, Exchange exchange) throws TransformerException {
return new ByteArrayInputStream(toByteArray(source, exchange));
}
@Converter(order = 60)
public InputStream toInputStream(Document dom, Exchange exchange) throws TransformerException {
return toInputStream(new DOMSource(dom), exchange);
}
@Converter(order = 61)
public InputSource toInputSource(InputStream is, Exchange exchange) {
return new InputSource(is);
}
@Converter(order = 62)
public InputSource toInputSource(File file, Exchange exchange) throws FileNotFoundException {
InputStream is = IOHelper.buffered(new FileInputStream(file));
return new InputSource(is);
}
/**
* Converts the source instance to a {@link DOMSource} or returns null if the conversion is not supported (making it
* easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 63)
public DOMSource toDOMSource(Source source, Exchange exchange)
throws ParserConfigurationException, IOException, SAXException, TransformerException {
if (source instanceof DOMSource) {
return (DOMSource) source;
} else if (source instanceof SAXSource) {
return toDOMSourceFromSAX((SAXSource) source);
} else if (source instanceof StreamSource) {
return toDOMSourceFromStream((StreamSource) source, exchange);
} else if (source instanceof StAXSource) {
return toDOMSourceFromStAX((StAXSource) source);
} else {
return null;
}
}
/**
* Converts the source instance to a {@link SAXSource} or returns null if the conversion is not supported (making it
* easy to derive from this class to add new kinds of conversion).
*/
@Converter(order = 64)
public SAXSource toSAXSource(Source source, Exchange exchange) throws SAXException, TransformerException {
if (source instanceof SAXSource) {
return (SAXSource) source;
} else if (source instanceof DOMSource) {
return toSAXSourceFromDOM((DOMSource) source, exchange);
} else if (source instanceof StreamSource) {
return toSAXSourceFromStream((StreamSource) source, exchange);
} else if (source instanceof StAXSource) {
return toSAXSourceFromStAX((StAXSource) source, exchange);
} else {
return null;
}
}
@Converter(order = 65)
public StreamSource toStreamSource(Source source, Exchange exchange) throws TransformerException {
if (source instanceof StreamSource) {
return (StreamSource) source;
} else if (source instanceof DOMSource) {
return toStreamSourceFromDOM((DOMSource) source, exchange);
} else if (source instanceof SAXSource) {
return toStreamSourceFromSAX((SAXSource) source, exchange);
} else if (source instanceof StAXSource) {
return toStreamSourceFromStAX((StAXSource) source, exchange);
} else {
return null;
}
}
@Converter(order = 66)
public InputStream toInputStream(StreamSource source) throws IOException {
InputStream is = source.getInputStream();
if (is == null) {
Reader r = source.getReader();
String s = IOHelper.toString(r);
is = new ByteArrayInputStream(s.getBytes());
}
return is;
}
/**
* Converts the given Document to into text
*
* @param document The document to convert
* @param outputOptions The {@link OutputKeys} properties to control various aspects of the XML output
* @return The string representation of the document
*/
public String toStringFromDocument(Document document, Properties outputOptions) throws TransformerException {
if (document == null) {
return null;
}
DOMSource source = new DOMSource(document);
StringWriter buffer = new StringWriter();
toResult(source, new StreamResult(buffer), outputOptions);
return buffer.toString();
}
// Properties
//-------------------------------------------------------------------------
public DocumentBuilderFactory getDocumentBuilderFactory() {
if (documentBuilderFactory == null) {
documentBuilderFactory = createDocumentBuilderFactory();
}
return documentBuilderFactory;
}
public void setDocumentBuilderFactory(DocumentBuilderFactory documentBuilderFactory) {
this.documentBuilderFactory = documentBuilderFactory;
}
public TransformerFactory getTransformerFactory() {
if (transformerFactory == null) {
transformerFactory = createTransformerFactory();
}
return transformerFactory;
}
public void setTransformerFactory(TransformerFactory transformerFactory) {
if (transformerFactory != null) {
configureSaxonTransformerFactory(transformerFactory);
}
this.transformerFactory = transformerFactory;
}
// Helper methods
//-------------------------------------------------------------------------
protected void setupFeatures(DocumentBuilderFactory factory) {
// must do defensive copy in case of concurrency
Properties properties = new Properties();
properties.putAll(System.getProperties());
List<String> features = new ArrayList<>();
for (Map.Entry<Object, Object> prop : properties.entrySet()) {
String key = (String) prop.getKey();
if (key.startsWith(XmlConverter.DOCUMENT_BUILDER_FACTORY_FEATURE)) {
String uri = StringHelper.after(key, ":");
boolean value = Boolean.parseBoolean((String) prop.getValue());
try {
factory.setFeature(uri, value);
features.add("feature " + uri + " value " + value);
} catch (ParserConfigurationException e) {
LOG.warn("DocumentBuilderFactory doesn't support the feature {} with value {}, due to {}.", uri,
value, e.getMessage(), e);
}
}
}
if (!features.isEmpty()) {
StringBuilder featureString = new StringBuilder();
// just log the configured feature
for (String feature : features) {
if (!featureString.isEmpty()) {
featureString.append(", ");
}
featureString.append(feature);
}
LOG.info("DocumentBuilderFactory has been set with features {{}}.", featureString);
}
}
public DocumentBuilderFactory getDocumentBuilderFactory(Exchange exchange) {
DocumentBuilderFactory answer = getDocumentBuilderFactory();
// Get the DocumentBuilderFactory from the exchange header first
if (exchange != null) {
DocumentBuilderFactory factory
= exchange.getProperty(Exchange.DOCUMENT_BUILDER_FACTORY, DocumentBuilderFactory.class);
if (factory != null) {
answer = factory;
}
}
return answer;
}
public DocumentBuilderFactory createDocumentBuilderFactory() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setIgnoringElementContentWhitespace(true);
factory.setIgnoringComments(true);
try {
// Set secure processing
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
} catch (ParserConfigurationException e) {
LOG.warn("DocumentBuilderFactory doesn't support the feature {} with value {}, due to {}.",
XMLConstants.FEATURE_SECURE_PROCESSING, true, e.getMessage(), e);
}
try {
// disable DOCTYPE declaration
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", Boolean.TRUE);
} catch (ParserConfigurationException e) {
LOG.warn("DocumentBuilderFactory doesn't support the feature {} with value {}, due to {}.",
"http://apache.org/xml/features/disallow-doctype-decl", true, e.getMessage(), e);
}
try {
// Disable the external-general-entities by default