Migrate netconf-console to Karaf 4 way
[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 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 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 java.nio.charset.StandardCharsets;
20 import java.util.Optional;
21 import javax.xml.XMLConstants;
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.Source;
28 import javax.xml.transform.Transformer;
29 import javax.xml.transform.TransformerException;
30 import javax.xml.transform.TransformerFactory;
31 import javax.xml.transform.TransformerFactoryConfigurationError;
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.validation.Schema;
36 import javax.xml.validation.SchemaFactory;
37 import javax.xml.xpath.XPathExpression;
38 import javax.xml.xpath.XPathExpressionException;
39 import org.w3c.dom.Document;
40 import org.w3c.dom.Element;
41 import org.w3c.dom.Node;
42 import org.xml.sax.SAXException;
43
44 public final class XmlUtil {
45
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 qname) {
124         return createElement(document, qname, Optional.empty());
125     }
126
127     public static Element createElement(final Document document, final String qname,
128             final Optional<String> namespaceURI) {
129         if (namespaceURI.isPresent()) {
130             final Element element = document.createElementNS(namespaceURI.get(), qname);
131             String name = XMLNS_ATTRIBUTE;
132             if (element.getPrefix() != null) {
133                 name += ":" + element.getPrefix();
134             }
135             element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, name, namespaceURI.get());
136             return element;
137         }
138         return document.createElement(qname);
139     }
140
141     public static Element createTextElement(final Document document, final String qname, final String content,
142             final Optional<String> namespaceURI) {
143         Element typeElement = createElement(document, qname, namespaceURI);
144         typeElement.appendChild(document.createTextNode(content));
145         return typeElement;
146     }
147
148     public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
149             final String prefix, final String namespace, final String contentWithoutPrefix) {
150
151         return createTextElementWithNamespacedContent(document, qname, prefix, namespace, contentWithoutPrefix,
152                 Optional.empty());
153     }
154
155     public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
156             final String prefix, final String namespace, final String contentWithoutPrefix,
157             final Optional<String> namespaceURI) {
158
159         String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
160         Element element = createTextElement(document, qname, content, namespaceURI);
161         String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE, prefix);
162         element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, prefixedNamespaceAttr, namespace);
163         return element;
164     }
165
166     public static String createPrefixedValue(final String prefix, final String value) {
167         return prefix + ":" + value;
168     }
169
170     public static String toString(final Document document) {
171         return toString(document.getDocumentElement());
172     }
173
174     public static String toString(final Element xml) {
175         return toString(xml, false);
176     }
177
178     public static String toString(final XmlElement xmlElement) {
179         return toString(xmlElement.getDomElement(), false);
180     }
181
182     public static String toString(final Element xml, final boolean addXmlDeclaration) {
183         try {
184             Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
185             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
186             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
187
188             StreamResult result = new StreamResult(new StringWriter());
189             DOMSource source = new DOMSource(xml);
190             transformer.transform(source, result);
191
192             return result.getWriter().toString();
193         } catch (TransformerFactoryConfigurationError | TransformerException e) {
194             throw new IllegalStateException("Unable to serialize xml element " + xml, e);
195         }
196     }
197
198     public static String toString(final Document doc, final boolean addXmlDeclaration) {
199         return toString(doc.getDocumentElement(), addXmlDeclaration);
200     }
201
202     public static Schema loadSchema(final InputStream... fromStreams) {
203         Source[] sources = new Source[fromStreams.length];
204         int index = 0;
205         for (InputStream stream : fromStreams) {
206             sources[index++] = new StreamSource(stream);
207         }
208
209         try {
210             return SCHEMA_FACTORY.newSchema(sources);
211         } catch (final SAXException e) {
212             throw new IllegalStateException("Failed to instantiate XML schema", e);
213         }
214     }
215
216     public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
217         try {
218             return expr.evaluate(rootNode, returnType);
219         } catch (final XPathExpressionException e) {
220             throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
221         }
222     }
223
224     public static Document createDocumentCopy(final Document original) {
225         final Document copiedDocument = newDocument();
226         final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
227         copiedDocument.appendChild(copiedRoot);
228         return copiedDocument;
229     }
230 }