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