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