1f81117ca383922ff246c9e10af36b708f84b26a
[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 org.w3c.dom.Document;
14 import org.w3c.dom.Element;
15 import org.w3c.dom.Node;
16 import org.xml.sax.SAXException;
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.TransformerFactory;
27 import javax.xml.transform.TransformerFactoryConfigurationError;
28 import javax.xml.transform.dom.DOMSource;
29 import javax.xml.transform.stream.StreamResult;
30 import javax.xml.transform.stream.StreamSource;
31 import javax.xml.validation.Schema;
32 import javax.xml.validation.SchemaFactory;
33 import javax.xml.xpath.XPathExpression;
34 import javax.xml.xpath.XPathExpressionException;
35 import java.io.ByteArrayInputStream;
36 import java.io.File;
37 import java.io.FileInputStream;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.StringWriter;
41
42 public final class XmlUtil {
43
44     public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
45     private 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 createPrefixedTextElement(Document document, String qName, String prefix, String content, Optional<String> namespace) {
122         return createTextElement(document, qName, createPrefixedValue(prefix, content), namespace);
123     }
124
125     public static String createPrefixedValue(String prefix, String value) {
126         return prefix + ":" + value;
127     }
128
129     public static String toString(Document document) {
130         return toString(document.getDocumentElement());
131     }
132
133     public static String toString(Element xml) {
134         return toString(xml, false);
135     }
136
137     public static String toString(XmlElement xmlElement) {
138         return toString(xmlElement.getDomElement(), false);
139     }
140
141     public static String toString(Element xml, boolean addXmlDeclaration) {
142         try {
143             Transformer transformer = TransformerFactory.newInstance().newTransformer();
144             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
145             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
146
147             StreamResult result = new StreamResult(new StringWriter());
148             DOMSource source = new DOMSource(xml);
149             transformer.transform(source, result);
150
151             return result.getWriter().toString();
152         } catch (Exception |  TransformerFactoryConfigurationError e) {
153             throw new IllegalStateException("Unable to serialize xml element " + xml, e);
154         }
155     }
156
157     public static String toString(Document doc, boolean addXmlDeclaration) {
158         return toString(doc.getDocumentElement(), addXmlDeclaration);
159     }
160
161     public static Schema loadSchema(InputStream... fromStreams) {
162         Source[] sources = new Source[fromStreams.length];
163         int i = 0;
164         for (InputStream stream : fromStreams) {
165             sources[i++] = new StreamSource(stream);
166         }
167
168         final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
169         try {
170             return schemaFactory.newSchema(sources);
171         } catch (SAXException e) {
172             throw new IllegalStateException("Failed to instantiate XML schema", e);
173         }
174     }
175
176     public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
177         try {
178             return expr.evaluate(rootNode, returnType);
179         } catch (XPathExpressionException e) {
180             throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
181         }
182     }
183
184     public static Document createDocumentCopy(Document original) {
185         final Document copiedDocument = newDocument();
186         final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
187         copiedDocument.appendChild(copiedRoot);
188         return copiedDocument;
189     }
190 }