1 package eu.ehri.project.exporters.xml;
2
3 import com.google.common.collect.ImmutableList;
4 import com.google.common.io.Resources;
5 import eu.ehri.project.models.base.Entity;
6 import org.w3c.dom.Document;
7 import org.xml.sax.SAXException;
8
9 import javax.xml.parsers.ParserConfigurationException;
10 import javax.xml.stream.XMLOutputFactory;
11 import javax.xml.stream.XMLStreamException;
12 import javax.xml.transform.TransformerException;
13 import java.io.BufferedOutputStream;
14 import java.io.ByteArrayInputStream;
15 import java.io.ByteArrayOutputStream;
16 import java.io.IOException;
17 import java.io.OutputStream;
18 import java.nio.charset.StandardCharsets;
19 import java.util.List;
20
21 public abstract class AbstractStreamingXmlExporter<E extends Entity>
22 extends StreamingXmlDsl
23 implements StreamingXmlExporter<E>, XmlExporter<E> {
24
25 private static final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
26
27 @Override
28 public Document export(E item, String langCode) throws IOException {
29 try {
30 ByteArrayOutputStream baos = new ByteArrayOutputStream();
31 export(item, baos, langCode);
32 return new DocumentReader().read(new ByteArrayInputStream(baos.toByteArray()));
33 } catch (ParserConfigurationException | TransformerException | SAXException e) {
34 throw new RuntimeException(e);
35 }
36 }
37
38 @Override
39 public void export(E unit, OutputStream outputStream, String langCode)
40 throws IOException, TransformerException {
41 try (final IndentingXMLStreamWriter sw = new IndentingXMLStreamWriter(
42 xmlOutputFactory.createXMLStreamWriter(new BufferedOutputStream(outputStream)))) {
43 sw.writeStartDocument();
44 export(sw, unit, langCode);
45 sw.writeEndDocument();
46 } catch (XMLStreamException e) {
47 throw new RuntimeException(e);
48 }
49 }
50
51 protected List<Object> coerceList(Object value) {
52 return value == null ? ImmutableList.of()
53 : (value instanceof List ? (List) value : ImmutableList.of(value));
54 }
55
56 protected String resourceAsString(String resourceName) {
57 try {
58 return Resources.toString(Resources.getResource(resourceName),
59 StandardCharsets.UTF_8);
60 } catch (IOException e) {
61 throw new RuntimeException(e);
62 }
63 }
64 }