View Javadoc
1   /*
2    * Copyright 2011 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
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   * Various XML utilities.
35   *
36   * @author Dmytro Rud
37   */
38  @Slf4j
39  abstract public class XmlUtils {
40  
41      private static final Pattern ROOT_ELEMENT_PATTERN = Pattern.compile(
42              "(?:<\\?xml.+?\\?>)?" +                              // optional prolog
43                      "(?:\\s*<\\!--.*?-->)*" +                              // optional comments
44                      "\\s*<(?:[\\w\\.-]+?:)?([\\w\\.-]+)(?:\\s|(?:/?>))",   // open tag of the root element
45              Pattern.DOTALL
46      );
47  
48  
49      private XmlUtils() {
50          throw new IllegalStateException("Cannot instantiate helper class");
51      }
52  
53  
54      /**
55       * Creates an XML Source from the given XML String.
56       *
57       * @param s XML String.
58       * @return XML Source.
59       */
60      public static Source source(String s) {
61          return new StreamSource(new StringReader(s));
62      }
63  
64  
65      /**
66       * Returns local name of the root element of the XML document represented
67       * by the given string, or <code>null</code>, when the given string does
68       * not contain valid XML.
69       *
70       * @param s XML string.
71       * @return root element local name, or <code>null</code> when it could not be determined.
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       * Creates a String representation of a JAXB object.
83       *
84       * @param jaxbContext JAXB context corresponding to the object's type
85       * @param object      The JAXB object to be processed
86       * @param prettyPrint Whether the XML shall nbe pretty printed or not
87       * @return String representation of the given  JAXB object
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      * Simple method to serialize a DOM-bound XML object to a byte array (string)
104      *
105      * @param inputNode DOM Node to serialize
106      * @return Byte array of XML in ASCII form
107      * @throws Exception
108      */
109     public static byte[] serialize(Node inputNode) throws Exception {
110         // Initialize sources and targets
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 }