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