1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package de.smartics.testdoc.core.export;
17
18 import java.io.IOException;
19 import java.io.OutputStream;
20
21 import javax.xml.parsers.DocumentBuilder;
22 import javax.xml.parsers.DocumentBuilderFactory;
23 import javax.xml.parsers.ParserConfigurationException;
24 import javax.xml.transform.OutputKeys;
25 import javax.xml.transform.Transformer;
26 import javax.xml.transform.TransformerException;
27 import javax.xml.transform.TransformerFactory;
28 import javax.xml.transform.dom.DOMSource;
29 import javax.xml.transform.stream.StreamResult;
30
31 import org.w3c.dom.Document;
32
33 import de.smartics.testdoc.core.doc.UnitTestDoc;
34
35
36
37
38
39
40
41 public class XmlExporter implements UnitTestDocExporter
42 {
43
44
45
46
47
48
49
50
51
52 private final DocumentBuilder builder;
53
54
55
56
57
58 private final boolean prettyPrint;
59
60
61
62
63
64
65
66
67
68
69
70 public XmlExporter() throws ParserConfigurationException
71 {
72 this(true);
73 }
74
75
76
77
78
79
80
81
82
83
84 public XmlExporter(final boolean prettyPrint)
85 throws ParserConfigurationException
86 {
87 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
88 this.builder = factory.newDocumentBuilder();
89 this.prettyPrint = prettyPrint;
90 }
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106 @Override
107 public String getFileExtension()
108 {
109 return "xml";
110 }
111
112
113
114
115
116
117
118
119
120 @Override
121 public void export(final UnitTestDoc testDoc, final OutputStream output)
122 throws IOException, NullPointerException
123 {
124 if (testDoc == null)
125 {
126 throw new NullPointerException("The test doc instance must not be 'null'");
127 }
128 if (output == null)
129 {
130 throw new NullPointerException("The test doc instance must not be 'null'");
131 }
132
133 final XmlDocumentBuilder docBuilder = createBuilder();
134 final Document document = docBuilder.build(testDoc);
135 serialize(document, output);
136 }
137
138 private XmlDocumentBuilder createBuilder()
139 {
140 final Document document = builder.newDocument();
141 final XmlDocumentBuilder builder = new XmlDocumentBuilder(document);
142 return builder;
143 }
144
145
146
147
148
149
150
151
152 private void serialize(final Document document, final OutputStream out)
153 throws IOException
154 {
155 try
156 {
157 final TransformerFactory factory = TransformerFactory.newInstance();
158 final Transformer serializer = factory.newTransformer();
159 if (prettyPrint)
160 {
161 serializer.setOutputProperty(OutputKeys.INDENT, "yes");
162 serializer.setOutputProperty(
163 "{http://xml.apache.org/xslt}indent-amount", "2");
164 }
165
166 serializer.transform(new DOMSource(document), new StreamResult(out));
167 }
168 catch (final TransformerException e)
169 {
170 throw new IOException("Cannot write XML document.", e);
171 }
172 }
173
174
175
176 }