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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.