1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.openehealth.ipf.commons.xml;
17
18 import lombok.extern.slf4j.Slf4j;
19 import org.w3c.dom.Node;
20
21 import javax.xml.bind.JAXBContext;
22 import javax.xml.bind.Marshaller;
23 import javax.xml.transform.*;
24 import javax.xml.transform.dom.DOMSource;
25 import javax.xml.transform.stream.StreamResult;
26 import javax.xml.transform.stream.StreamSource;
27 import java.io.ByteArrayOutputStream;
28 import java.io.StringReader;
29 import java.io.StringWriter;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32
33
34
35
36
37
38 @Slf4j
39 abstract public class XmlUtils {
40
41 private static final Pattern ROOT_ELEMENT_PATTERN = Pattern.compile(
42 "(?:<\\?xml.+?\\?>)?" +
43 "(?:\\s*<\\!--.*?-->)*" +
44 "\\s*<(?:[\\w\\.-]+?:)?([\\w\\.-]+)(?:\\s|(?:/?>))",
45 Pattern.DOTALL
46 );
47
48
49 private XmlUtils() {
50 throw new IllegalStateException("Cannot instantiate helper class");
51 }
52
53
54
55
56
57
58
59
60 public static Source source(String s) {
61 return new StreamSource(new StringReader(s));
62 }
63
64
65
66
67
68
69
70
71
72
73 public static String rootElementName(String s) {
74 if (s == null) {
75 return null;
76 }
77 Matcher matcher = ROOT_ELEMENT_PATTERN.matcher(s);
78 return (matcher.find() && (matcher.start() == 0)) ? matcher.group(1) : null;
79 }
80
81
82
83
84
85
86
87
88
89 public static String renderJaxb(JAXBContext jaxbContext, Object object, Boolean prettyPrint) {
90 try {
91 Marshaller marshaller = jaxbContext.createMarshaller();
92 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
93 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, prettyPrint);
94 StringWriter writer = new StringWriter();
95 marshaller.marshal(object, writer);
96 return writer.toString();
97 } catch (Exception e) {
98 throw new RuntimeException(e);
99 }
100 }
101
102
103
104
105
106
107
108
109 public static byte[] serialize(Node inputNode) throws Exception {
110
111 ByteArrayOutputStream serializerOutput = new ByteArrayOutputStream();
112 Source sourceObject = new DOMSource(inputNode);
113 Result targetObject = new StreamResult(serializerOutput);
114
115
116 TransformerFactory serializerFactory = TransformerFactory.newInstance();
117 Transformer serializer = serializerFactory.newTransformer();
118 serializer.setOutputProperty(OutputKeys.INDENT, "yes");
119 serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
120 serializer.transform(sourceObject, targetObject);
121 return serializerOutput.toByteArray();
122 }
123 }