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