fac5afa009bf3a516e10919eb710699f0a089b69
[netconf.git] / protocol / 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 package org.opendaylight.netconf.api.xml;
9
10 import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE;
11 import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
12
13 import com.google.common.io.Resources;
14 import java.io.ByteArrayInputStream;
15 import java.io.File;
16 import java.io.FileInputStream;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.StringWriter;
20 import java.nio.charset.StandardCharsets;
21 import java.util.Optional;
22 import javax.xml.namespace.QName;
23 import javax.xml.parsers.DocumentBuilder;
24 import javax.xml.parsers.DocumentBuilderFactory;
25 import javax.xml.parsers.ParserConfigurationException;
26 import javax.xml.transform.OutputKeys;
27 import javax.xml.transform.Templates;
28 import javax.xml.transform.Transformer;
29 import javax.xml.transform.TransformerConfigurationException;
30 import javax.xml.transform.TransformerException;
31 import javax.xml.transform.TransformerFactory;
32 import javax.xml.transform.dom.DOMSource;
33 import javax.xml.transform.stream.StreamResult;
34 import javax.xml.transform.stream.StreamSource;
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      * A pre-compiled XSL template to deal with Java XML transform creating empty lines when indenting is enabled, as
45      * detailed in <a href="https://bugs.openjdk.org/browse/JDK-8262285">JDK-8262285</a>.
46      */
47     private static final Templates PRETTY_PRINT_TEMPLATE;
48
49     static {
50         try {
51             PRETTY_PRINT_TEMPLATE = TransformerFactory.newInstance()
52                 .newTemplates(new StreamSource(Resources.getResource(XmlUtil.class, "/pretty-print.xsl").openStream()));
53         } catch (IOException | TransformerConfigurationException e) {
54             throw new ExceptionInInitializerError(e);
55         }
56     }
57
58     private static final DocumentBuilderFactory BUILDER_FACTORY;
59
60     static {
61         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
62         try {
63             factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
64             factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
65             factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
66             factory.setXIncludeAware(false);
67             factory.setExpandEntityReferences(false);
68             // Performance improvement for messages with size <10k according to
69             // https://xerces.apache.org/xerces2-j/faq-performance.html
70             factory.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
71         } catch (final ParserConfigurationException e) {
72             throw new ExceptionInInitializerError(e);
73         }
74         factory.setNamespaceAware(true);
75         factory.setCoalescing(true);
76         factory.setIgnoringElementContentWhitespace(true);
77         factory.setIgnoringComments(true);
78         BUILDER_FACTORY = factory;
79     }
80
81     private static final ThreadLocal<DocumentBuilder> DEFAULT_DOM_BUILDER = new ThreadLocal<>() {
82         @Override
83         protected DocumentBuilder initialValue() {
84             try {
85                 return BUILDER_FACTORY.newDocumentBuilder();
86             } catch (final ParserConfigurationException e) {
87                 throw new IllegalStateException("Failed to create threadLocal dom builder", e);
88             }
89         }
90
91         @Override
92         public void set(final DocumentBuilder value) {
93             throw new UnsupportedOperationException();
94         }
95     };
96
97     private XmlUtil() {
98         // Hidden on purpose
99     }
100
101     public static Element readXmlToElement(final File xmlFile) throws SAXException, IOException {
102         return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
103     }
104
105     public static Element readXmlToElement(final String xmlContent) throws SAXException, IOException {
106         Document doc = readXmlToDocument(xmlContent);
107         return doc.getDocumentElement();
108     }
109
110     public static Element readXmlToElement(final InputStream xmlContent) throws SAXException, IOException {
111         Document doc = readXmlToDocument(xmlContent);
112         return doc.getDocumentElement();
113     }
114
115     public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
116         return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)));
117     }
118
119     // TODO improve exceptions throwing
120     // along with XmlElement
121
122     public static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
123         Document doc = DEFAULT_DOM_BUILDER.get().parse(xmlContent);
124
125         doc.getDocumentElement().normalize();
126         return doc;
127     }
128
129     public static Document newDocument() {
130         return DEFAULT_DOM_BUILDER.get().newDocument();
131     }
132
133     public static Element createElement(final Document document, final String qname,
134             final Optional<String> namespaceURI) {
135         if (namespaceURI.isEmpty()) {
136             return document.createElement(qname);
137         }
138
139         final String uri = namespaceURI.orElseThrow();
140         final Element element = document.createElementNS(uri, qname);
141         String name = XMLNS_ATTRIBUTE;
142         if (element.getPrefix() != null) {
143             name += ":" + element.getPrefix();
144         }
145         element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, name, uri);
146         return element;
147     }
148
149     public static Element createTextElement(final Document document, final String qname, final String content,
150             final Optional<String> namespaceURI) {
151         Element typeElement = createElement(document, qname, namespaceURI);
152         typeElement.appendChild(document.createTextNode(content));
153         return typeElement;
154     }
155
156     public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
157             final String prefix, final String namespace, final String contentWithoutPrefix) {
158
159         return createTextElementWithNamespacedContent(document, qname, prefix, namespace, contentWithoutPrefix,
160                 Optional.empty());
161     }
162
163     public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
164             final String prefix, final String namespace, final String contentWithoutPrefix,
165             final Optional<String> namespaceURI) {
166
167         String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
168         Element element = createTextElement(document, qname, content, namespaceURI);
169         String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE, prefix);
170         element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, prefixedNamespaceAttr, namespace);
171         return element;
172     }
173
174     public static String createPrefixedValue(final String prefix, final String value) {
175         return prefix + ":" + value;
176     }
177
178     /**
179      * Return a new {@link Transformer} which performs indentation.
180      *
181      * @return A new Transformer
182      * @throws TransformerConfigurationException if a Transformer can not be created
183      */
184     public static Transformer newIndentingTransformer() throws TransformerConfigurationException {
185         final Transformer ret = PRETTY_PRINT_TEMPLATE.newTransformer();
186         ret.setOutputProperty(OutputKeys.INDENT, "yes");
187         return ret;
188     }
189
190     public static String toString(final Document document) {
191         return toString(document.getDocumentElement());
192     }
193
194     public static String toString(final Element xml) {
195         return toString(xml, false);
196     }
197
198     public static String toString(final XmlElement xmlElement) {
199         return toString(xmlElement.getDomElement(), false);
200     }
201
202     public static String toString(final Element xml, final boolean addXmlDeclaration) {
203         final StringWriter writer = new StringWriter();
204
205         try {
206             Transformer transformer = newIndentingTransformer();
207             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
208             transformer.transform(new DOMSource(xml), new StreamResult(writer));
209         } catch (TransformerException e) {
210             throw new IllegalStateException("Unable to serialize xml element " + xml, e);
211         }
212
213         return writer.toString();
214     }
215
216     public static String toString(final Document doc, final boolean addXmlDeclaration) {
217         return toString(doc.getDocumentElement(), addXmlDeclaration);
218     }
219
220     public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
221         try {
222             return expr.evaluate(rootNode, returnType);
223         } catch (final XPathExpressionException e) {
224             throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
225         }
226     }
227
228     public static Document createDocumentCopy(final Document original) {
229         final Document copiedDocument = newDocument();
230         final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
231         copiedDocument.appendChild(copiedRoot);
232         return copiedDocument;
233     }
234 }