1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.xml.secure;
19
20 import static org.junit.jupiter.api.Assertions.assertNotNull;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.InputStream;
24 import java.nio.charset.StandardCharsets;
25
26 import javax.xml.bind.JAXBContext;
27 import javax.xml.bind.Unmarshaller;
28 import javax.xml.bind.annotation.XmlRootElement;
29 import javax.xml.parsers.SAXParserFactory;
30 import javax.xml.stream.XMLInputFactory;
31 import javax.xml.stream.XMLStreamReader;
32 import javax.xml.transform.sax.SAXSource;
33
34 import org.junit.jupiter.api.Test;
35 import org.xml.sax.InputSource;
36 import org.xml.sax.XMLReader;
37
38
39
40
41
42
43
44 public class JaxbTest {
45
46 @XmlRootElement
47 static class MyJaxbModel {
48
49 }
50
51 @Test
52 void testUnmarshalSecurelyWithSax() throws Exception {
53 try (InputStream xmlStream = new ByteArrayInputStream("<myJaxbModel/>".getBytes(StandardCharsets.UTF_8))) {
54 assertNotNull(new JaxbTest().unmarshalSecurelyWithSax(xmlStream));
55 }
56 }
57
58 @Test
59 void testUnmarshalSecurelyWithStax() throws Exception {
60 try (InputStream xmlStream = new ByteArrayInputStream("<myJaxbModel/>".getBytes(StandardCharsets.UTF_8))) {
61 assertNotNull(new JaxbTest().unmarshalSecurelyWithStax(xmlStream));
62 }
63 }
64
65 public MyJaxbModel unmarshalSecurelyWithSax(final InputStream xmlStream) throws Exception {
66 final JAXBContext context = JAXBContext.newInstance(MyJaxbModel.class);
67 final Unmarshaller unmarshaller = context.createUnmarshaller();
68
69 final SAXParserFactory spf = SecureSAXParserFactory.newDefaultNSInstance();
70
71 final XMLReader xmlReader = spf.newSAXParser().getXMLReader();
72 final SAXSource source = new SAXSource(xmlReader, new InputSource(xmlStream));
73
74
75
76 return (MyJaxbModel) unmarshaller.unmarshal(source);
77 }
78
79 public MyJaxbModel unmarshalSecurelyWithStax(final InputStream xmlStream) throws Exception {
80 final JAXBContext context = JAXBContext.newInstance(MyJaxbModel.class);
81 final Unmarshaller unmarshaller = context.createUnmarshaller();
82
83 final XMLInputFactory xif = SecureXMLInputFactory.newDefaultFactory();
84
85 final XMLStreamReader xmlReader = xif.createXMLStreamReader(xmlStream);
86 try {
87
88
89
90 return (MyJaxbModel) unmarshaller.unmarshal(xmlReader);
91 } finally {
92 xmlReader.close();
93 }
94 }
95 }