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