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