Do not instantiate multiple DocumentBuilderFactories
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / xml / XmlUtil.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.netconf.util.xml;
10
11 import java.io.ByteArrayInputStream;
12 import java.io.File;
13 import java.io.FileInputStream;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.StringWriter;
17
18 import javax.xml.XMLConstants;
19 import javax.xml.namespace.QName;
20 import javax.xml.parsers.DocumentBuilder;
21 import javax.xml.parsers.DocumentBuilderFactory;
22 import javax.xml.parsers.ParserConfigurationException;
23 import javax.xml.transform.OutputKeys;
24 import javax.xml.transform.Source;
25 import javax.xml.transform.Transformer;
26 import javax.xml.transform.TransformerException;
27 import javax.xml.transform.TransformerFactory;
28 import javax.xml.transform.TransformerFactoryConfigurationError;
29 import javax.xml.transform.dom.DOMSource;
30 import javax.xml.transform.stream.StreamResult;
31 import javax.xml.transform.stream.StreamSource;
32 import javax.xml.validation.Schema;
33 import javax.xml.validation.SchemaFactory;
34 import javax.xml.xpath.XPathExpression;
35 import javax.xml.xpath.XPathExpressionException;
36
37 import org.w3c.dom.Document;
38 import org.w3c.dom.Element;
39 import org.w3c.dom.Node;
40 import org.xml.sax.SAXException;
41
42 import com.google.common.base.Charsets;
43
44 public class XmlUtil {
45     public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
46     private static final DocumentBuilderFactory BUILDERFACTORY;
47
48     static {
49         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
50         factory.setNamespaceAware(true);
51         factory.setCoalescing(true);
52         factory.setIgnoringElementContentWhitespace(true);
53         factory.setIgnoringComments(true);
54         BUILDERFACTORY = factory;
55     }
56
57     public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
58         Document doc = readXmlToDocument(xmlContent);
59         return doc.getDocumentElement();
60     }
61
62     public static Element readXmlToElement(InputStream xmlContent) throws SAXException, IOException {
63         Document doc = readXmlToDocument(xmlContent);
64         return doc.getDocumentElement();
65     }
66
67     public static Document readXmlToDocument(String xmlContent) throws SAXException, IOException {
68         return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
69     }
70
71     public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
72         DocumentBuilder dBuilder;
73         try {
74             dBuilder = BUILDERFACTORY.newDocumentBuilder();
75         } catch (ParserConfigurationException e) {
76             throw new RuntimeException("Failed to parse XML document", e);
77         }
78         Document doc = dBuilder.parse(xmlContent);
79
80         doc.getDocumentElement().normalize();
81         return doc;
82     }
83
84     public static Element readXmlToElement(File xmlFile) throws SAXException, IOException {
85         return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
86     }
87
88     public static Document newDocument() {
89         try {
90             DocumentBuilder builder = BUILDERFACTORY.newDocumentBuilder();
91             Document document = builder.newDocument();
92             return document;
93         } catch (ParserConfigurationException e) {
94             throw new RuntimeException("Failed to create document", e);
95         }
96     }
97
98     public static Element createTextElement(Document document, String name, String content) {
99         Element typeElement = document.createElement(name);
100         typeElement.appendChild(document.createTextNode(content));
101         return typeElement;
102     }
103
104     public static void addNamespaceAttr(Element root, String namespace) {
105         root.setAttribute(XMLNS_ATTRIBUTE_KEY, namespace);
106     }
107
108     public static void addPrefixedNamespaceAttr(Element root, String prefix, String namespace) {
109         root.setAttribute(concat(XMLNS_ATTRIBUTE_KEY, prefix), namespace);
110     }
111
112     public static Element createPrefixedTextElement(Document document, String key, String prefix, String content) {
113         return createTextElement(document, key, concat(prefix, content));
114     }
115
116     private static String concat(String prefix, String value) {
117         return prefix + ":" + value;
118     }
119
120     public static String toString(Document document) {
121         return toString(document.getDocumentElement());
122     }
123
124     public static String toString(Element xml) {
125         return toString(xml, false);
126     }
127
128     public static String toString(XmlElement xmlElement) {
129         return toString(xmlElement.getDomElement(), false);
130     }
131
132     public static String toString(Element xml, boolean addXmlDeclaration) {
133         try {
134             Transformer transformer = TransformerFactory.newInstance().newTransformer();
135             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
136             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration == true ? "no" : "yes");
137
138             StreamResult result = new StreamResult(new StringWriter());
139             DOMSource source = new DOMSource(xml);
140             transformer.transform(source, result);
141
142             String xmlString = result.getWriter().toString();
143             return xmlString;
144         } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
145             throw new RuntimeException("Unable to serialize xml element " + xml, e);
146         }
147     }
148
149     public static String toString(Document doc, boolean addXmlDeclaration) {
150         return toString(doc.getDocumentElement(), addXmlDeclaration);
151     }
152
153     public static Schema loadSchema(InputStream... fromStreams) {
154         Source[] sources = new Source[fromStreams.length];
155         int i = 0;
156         for (InputStream stream : fromStreams) {
157             sources[i++] = new StreamSource(stream);
158         }
159
160         final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
161         try {
162             return schemaFactory.newSchema(sources);
163         } catch (SAXException e) {
164             throw new IllegalStateException("Failed to instantiate XML schema", e);
165         }
166     }
167
168     public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
169         try {
170             return expr.evaluate(rootNode, returnType);
171         } catch (XPathExpressionException e) {
172             throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
173         }
174     }
175
176     public static Document createDocumentCopy(Document original) {
177         final Document copiedDocument = newDocument();
178         final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
179         copiedDocument.appendChild(copiedRoot);
180         return copiedDocument;
181     }
182 }