Merge "bug 741 - Make sure to stop threads on bundle stop on TopologyServiceShim"
[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 import com.google.common.base.Optional;
44
45 public final class XmlUtil {
46
47     public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
48     private static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
49     private static final DocumentBuilderFactory BUILDERFACTORY;
50
51     static {
52         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
53         factory.setNamespaceAware(true);
54         factory.setCoalescing(true);
55         factory.setIgnoringElementContentWhitespace(true);
56         factory.setIgnoringComments(true);
57         BUILDERFACTORY = factory;
58     }
59
60     private XmlUtil() {}
61
62     public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
63         Document doc = readXmlToDocument(xmlContent);
64         return doc.getDocumentElement();
65     }
66
67     public static Element readXmlToElement(InputStream xmlContent) throws SAXException, IOException {
68         Document doc = readXmlToDocument(xmlContent);
69         return doc.getDocumentElement();
70     }
71
72     public static Document readXmlToDocument(String xmlContent) throws SAXException, IOException {
73         return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
74     }
75
76     // TODO improve exceptions throwing
77     // along with XmlElement
78
79     public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
80         DocumentBuilder dBuilder;
81         try {
82             dBuilder = BUILDERFACTORY.newDocumentBuilder();
83         } catch (ParserConfigurationException e) {
84             throw new RuntimeException("Failed to parse XML document", e);
85         }
86         Document doc = dBuilder.parse(xmlContent);
87
88         doc.getDocumentElement().normalize();
89         return doc;
90     }
91
92     public static Element readXmlToElement(File xmlFile) throws SAXException, IOException {
93         return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
94     }
95
96     public static Document newDocument() {
97         try {
98             DocumentBuilder builder = BUILDERFACTORY.newDocumentBuilder();
99             Document document = builder.newDocument();
100             return document;
101         } catch (ParserConfigurationException e) {
102             throw new RuntimeException("Failed to create document", e);
103         }
104     }
105
106     public static Element createElement(final Document document, String qName, Optional<String> namespaceURI) {
107         if(namespaceURI.isPresent()) {
108             final Element element = document.createElementNS(namespaceURI.get(), qName);
109             String name = XMLNS_ATTRIBUTE_KEY;
110             if(element.getPrefix() != null) {
111                 name += ":" + element.getPrefix();
112             }
113             element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
114             return element;
115         }
116         return document.createElement(qName);
117     }
118
119     public static Element createTextElement(Document document, String qName, String content, Optional<String> namespaceURI) {
120         Element typeElement = createElement(document, qName, namespaceURI);
121         typeElement.appendChild(document.createTextNode(content));
122         return typeElement;
123     }
124
125     public static Element createPrefixedTextElement(Document document, String qName, String prefix, String content, Optional<String> namespace) {
126         return createTextElement(document, qName, createPrefixedValue(prefix, content), namespace);
127     }
128
129     public static String createPrefixedValue(String prefix, String value) {
130         return prefix + ":" + value;
131     }
132
133     public static String toString(Document document) {
134         return toString(document.getDocumentElement());
135     }
136
137     public static String toString(Element xml) {
138         return toString(xml, false);
139     }
140
141     public static String toString(XmlElement xmlElement) {
142         return toString(xmlElement.getDomElement(), false);
143     }
144
145     public static String toString(Element xml, boolean addXmlDeclaration) {
146         try {
147             Transformer transformer = TransformerFactory.newInstance().newTransformer();
148             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
149             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
150
151             StreamResult result = new StreamResult(new StringWriter());
152             DOMSource source = new DOMSource(xml);
153             transformer.transform(source, result);
154
155             return result.getWriter().toString();
156         } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
157             throw new RuntimeException("Unable to serialize xml element " + xml, e);
158         }
159     }
160
161     public static String toString(Document doc, boolean addXmlDeclaration) {
162         return toString(doc.getDocumentElement(), addXmlDeclaration);
163     }
164
165     public static Schema loadSchema(InputStream... fromStreams) {
166         Source[] sources = new Source[fromStreams.length];
167         int i = 0;
168         for (InputStream stream : fromStreams) {
169             sources[i++] = new StreamSource(stream);
170         }
171
172         final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
173         try {
174             return schemaFactory.newSchema(sources);
175         } catch (SAXException e) {
176             throw new IllegalStateException("Failed to instantiate XML schema", e);
177         }
178     }
179
180     public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
181         try {
182             return expr.evaluate(rootNode, returnType);
183         } catch (XPathExpressionException e) {
184             throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
185         }
186     }
187
188     public static Document createDocumentCopy(Document original) {
189         final Document copiedDocument = newDocument();
190         final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
191         copiedDocument.appendChild(copiedRoot);
192         return copiedDocument;
193     }
194 }