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