View Javadoc

1   /**
2   The contents of this file are subject to the Mozilla Public License Version 1.1 
3   (the "License"); you may not use this file except in compliance with the License. 
4   You may obtain a copy of the License at http://www.mozilla.org/MPL/ 
5   Software distributed under the License is distributed on an "AS IS" basis, 
6   WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the 
7   specific language governing rights and limitations under the License. 
8   
9   The Original Code is "XMLUtils.java".  Description: 
10  "XML utilities" 
11  
12  The Initial Developer of the Original Code is University Health Network. Copyright (C) 
13  2001.  All Rights Reserved. 
14  
15  Contributor(s): ______________________________________. 
16  
17  Alternatively, the contents of this file may be used under the terms of the 
18  GNU General Public License (the  "GPL"), in which case the provisions of the GPL are 
19  applicable instead of those above.  If you wish to allow use of your version of this 
20  file only under the terms of the GPL and not to allow others to use your version 
21  of this file under the MPL, indicate your decision by deleting  the provisions above 
22  and replace  them with the notice and other provisions required by the GPL License.  
23  If you do not delete the provisions above, a recipient may use your version of 
24  this file under either the MPL or the GPL. 
25   */
26  package ca.uhn.hl7v2.util;
27  
28  import java.io.InputStream;
29  import java.io.StringWriter;
30  import java.io.Writer;
31  
32  import org.w3c.dom.DOMConfiguration;
33  import org.w3c.dom.DOMErrorHandler;
34  import org.w3c.dom.DOMImplementation;
35  import org.w3c.dom.Document;
36  import org.w3c.dom.bootstrap.DOMImplementationRegistry;
37  import org.w3c.dom.ls.DOMImplementationLS;
38  import org.w3c.dom.ls.LSInput;
39  import org.w3c.dom.ls.LSOutput;
40  import org.w3c.dom.ls.LSParser;
41  import org.w3c.dom.ls.LSResourceResolver;
42  import org.w3c.dom.ls.LSSerializer;
43  
44  public class XMLUtils {
45  
46      private static DOMImplementation IMPL;
47  
48      @SuppressWarnings("unchecked")
49      public synchronized static <T> T getDOMImpl() {
50          if (IMPL == null) {
51              try {
52                  DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
53                  IMPL = registry.getDOMImplementation("LS 3.0");
54              } catch (Exception e) {
55                  throw new RuntimeException(e);
56              }
57          }
58          return (T) IMPL;
59      }
60  
61      @SuppressWarnings("unchecked")
62      public static <T> T getDOMImplUncached() {
63          try {
64              DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
65              return (T) registry.getDOMImplementation("LS 3.0");
66          } catch (Exception e) {
67              throw new RuntimeException(e);
68          }
69      }
70  
71      public static Document parse(String s) {
72          return parse(s, false);
73      }
74  
75      public static Document parse(String s, boolean validateIfSchema) {
76          DOMImplementationLS impl = getDOMImpl();
77          LSInput input = impl.createLSInput();
78          input.setStringData(s);
79          return parse(input, validateIfSchema);
80      }
81  
82      public static Document parse(InputStream s, boolean validateIfSchema) {
83          DOMImplementationLS impl = getDOMImpl();
84          LSInput input = impl.createLSInput();
85          input.setByteStream(s);
86          return parse(input, validateIfSchema);
87      }
88  
89      private static Document parse(LSInput input, boolean validateIfSchema) {
90          DOMImplementationLS impl = getDOMImpl();
91          LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
92          DOMConfiguration config = parser.getDomConfig();
93          config.setParameter("element-content-whitespace", false);
94          config.setParameter("namespaces", true);
95          config.setParameter("validate-if-schema", validateIfSchema);
96          return parser.parse(input);
97      }
98  
99      public static void validate(Document d, String schema, DOMErrorHandler handler) {
100         DOMConfiguration config = d.getDomConfig();
101         config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
102         config.setParameter("validate", true);
103         config.setParameter("schema-location", schema);
104         config.setParameter("resource-resolver", new ClasspathResourceResolver());
105         config.setParameter("error-handler", handler);
106         d.normalizeDocument();
107     }
108 
109     public static String serialize(Document document, boolean prettyPrint) {
110         DOMImplementationLS impl = getDOMImpl();
111         LSSerializer serializer = impl.createLSSerializer();
112         // document.normalizeDocument();
113         DOMConfiguration config = serializer.getDomConfig();
114         if (prettyPrint && config.canSetParameter("format-pretty-print", Boolean.TRUE)) {
115             config.setParameter("format-pretty-print", true);
116         }
117         config.setParameter("xml-declaration", true);        
118         LSOutput output = impl.createLSOutput();
119         output.setEncoding("UTF-8");
120         Writer writer = new StringWriter();
121         output.setCharacterStream(writer);
122         serializer.write(document, output);
123         return writer.toString();
124     }
125 
126     public static Document emptyDocument(String title) {
127         DOMImplementation impl = getDOMImpl();
128         Document doc = impl.createDocument("urn:hl7-org:v2xml", title, null);
129         return doc;
130     }
131 
132     /**
133      * This is an implementation of LSResourceResolver that can resolve XML schemas from the
134      * classpath
135      */
136     private static class ClasspathResourceResolver implements LSResourceResolver {
137         private DOMImplementationLS impl;
138 
139         ClasspathResourceResolver() {
140             impl = getDOMImpl();
141         }
142 
143         public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
144                 String baseURI) {
145             LSInput lsInput = impl.createLSInput();
146             InputStream is = getClass().getResourceAsStream("/" + systemId);
147             if (is == null)
148                 return null;
149             lsInput.setByteStream(is);
150             return lsInput;
151         }
152     }
153 
154 }