Merge "fix failure during connecting device when channelActive happens later than...
[netconf.git] / netconf / netconf-api / src / main / java / org / opendaylight / netconf / api / 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.netconf.api.xml;
10
11 import com.google.common.base.Optional;
12 import java.io.ByteArrayInputStream;
13 import java.io.File;
14 import java.io.FileInputStream;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.StringWriter;
18 import java.nio.charset.StandardCharsets;
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.TransformerException;
28 import javax.xml.transform.TransformerFactory;
29 import javax.xml.transform.TransformerFactoryConfigurationError;
30 import javax.xml.transform.dom.DOMSource;
31 import javax.xml.transform.stream.StreamResult;
32 import javax.xml.transform.stream.StreamSource;
33 import javax.xml.validation.Schema;
34 import javax.xml.validation.SchemaFactory;
35 import javax.xml.xpath.XPathExpression;
36 import javax.xml.xpath.XPathExpressionException;
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             // Performance improvement for messages with size <10k according to
59             // https://xerces.apache.org/xerces2-j/faq-performance.html
60             factory.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
61         } catch (final ParserConfigurationException e) {
62             throw new ExceptionInInitializerError(e);
63         }
64         factory.setNamespaceAware(true);
65         factory.setCoalescing(true);
66         factory.setIgnoringElementContentWhitespace(true);
67         factory.setIgnoringComments(true);
68         BUILDER_FACTORY = factory;
69     }
70
71     private static final ThreadLocal<DocumentBuilder> DEFAULT_DOM_BUILDER = new ThreadLocal<DocumentBuilder>() {
72         @Override
73         protected DocumentBuilder initialValue() {
74             try {
75                 return BUILDER_FACTORY.newDocumentBuilder();
76             } catch (final ParserConfigurationException e) {
77                 throw new IllegalStateException("Failed to create threadLocal dom builder", e);
78             }
79         }
80
81         @Override
82         public void set(final DocumentBuilder value) {
83             throw new UnsupportedOperationException();
84         }
85     };
86
87     private XmlUtil() {
88         throw new UnsupportedOperationException("Utility class");
89     }
90
91     public static Element readXmlToElement(final File xmlFile) throws SAXException, IOException {
92         return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
93     }
94
95     public static Element readXmlToElement(final String xmlContent) throws SAXException, IOException {
96         Document doc = readXmlToDocument(xmlContent);
97         return doc.getDocumentElement();
98     }
99
100     public static Element readXmlToElement(final InputStream xmlContent) throws SAXException, IOException {
101         Document doc = readXmlToDocument(xmlContent);
102         return doc.getDocumentElement();
103     }
104
105     public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
106         return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)));
107     }
108
109     // TODO improve exceptions throwing
110     // along with XmlElement
111
112     public static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
113         Document doc = DEFAULT_DOM_BUILDER.get().parse(xmlContent);
114
115         doc.getDocumentElement().normalize();
116         return doc;
117     }
118
119     public static Document newDocument() {
120         return DEFAULT_DOM_BUILDER.get().newDocument();
121     }
122
123     public static Element createElement(final Document document, final String qmame,
124             final Optional<String> namespaceURI) {
125         if (namespaceURI.isPresent()) {
126             final Element element = document.createElementNS(namespaceURI.get(), qmame);
127             String name = XMLNS_ATTRIBUTE_KEY;
128             if (element.getPrefix() != null) {
129                 name += ":" + element.getPrefix();
130             }
131             element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
132             return element;
133         }
134         return document.createElement(qmame);
135     }
136
137     public static Element createTextElement(final Document document, final String qname, final String content,
138             final Optional<String> namespaceURI) {
139         Element typeElement = createElement(document, qname, namespaceURI);
140         typeElement.appendChild(document.createTextNode(content));
141         return typeElement;
142     }
143
144     public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
145             final String prefix, final String namespace, final String contentWithoutPrefix) {
146
147         return createTextElementWithNamespacedContent(document, qname, prefix, namespace, contentWithoutPrefix,
148                 Optional.<String>absent());
149     }
150
151     public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
152             final String prefix, final String namespace, final String contentWithoutPrefix,
153             final Optional<String> namespaceURI) {
154
155         String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
156         Element element = createTextElement(document, qname, content, namespaceURI);
157         String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE_KEY, prefix);
158         element.setAttributeNS(XMLNS_URI, prefixedNamespaceAttr, namespace);
159         return element;
160     }
161
162     public static String createPrefixedValue(final String prefix, final String value) {
163         return prefix + ":" + value;
164     }
165
166     public static String toString(final Document document) {
167         return toString(document.getDocumentElement());
168     }
169
170     public static String toString(final Element xml) {
171         return toString(xml, false);
172     }
173
174     public static String toString(final XmlElement xmlElement) {
175         return toString(xmlElement.getDomElement(), false);
176     }
177
178     public static String toString(final Element xml, final boolean addXmlDeclaration) {
179         try {
180             Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
181             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
182             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
183
184             StreamResult result = new StreamResult(new StringWriter());
185             DOMSource source = new DOMSource(xml);
186             transformer.transform(source, result);
187
188             return result.getWriter().toString();
189         } catch (TransformerFactoryConfigurationError | TransformerException e) {
190             throw new IllegalStateException("Unable to serialize xml element " + xml, e);
191         }
192     }
193
194     public static String toString(final Document doc, final boolean addXmlDeclaration) {
195         return toString(doc.getDocumentElement(), addXmlDeclaration);
196     }
197
198     public static Schema loadSchema(final InputStream... fromStreams) {
199         Source[] sources = new Source[fromStreams.length];
200         int index = 0;
201         for (InputStream stream : fromStreams) {
202             sources[index++] = new StreamSource(stream);
203         }
204
205         try {
206             return SCHEMA_FACTORY.newSchema(sources);
207         } catch (final SAXException e) {
208             throw new IllegalStateException("Failed to instantiate XML schema", e);
209         }
210     }
211
212     public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
213         try {
214             return expr.evaluate(rootNode, returnType);
215         } catch (final XPathExpressionException e) {
216             throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
217         }
218     }
219
220     public static Document createDocumentCopy(final Document original) {
221         final Document copiedDocument = newDocument();
222         final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
223         copiedDocument.appendChild(copiedRoot);
224         return copiedDocument;
225     }
226 }