6408fce5d39b199c1105807619bf9e4e0198c4f6
[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 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.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
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 (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 XmlUtil() {
72         throw new UnsupportedOperationException("Utility class");
73     }
74
75     public static Element readXmlToElement(final String xmlContent) throws SAXException, IOException {
76         Document doc = readXmlToDocument(xmlContent);
77         return doc.getDocumentElement();
78     }
79
80     public static Element readXmlToElement(final InputStream xmlContent) throws SAXException, IOException {
81         Document doc = readXmlToDocument(xmlContent);
82         return doc.getDocumentElement();
83     }
84
85     public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
86         return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
87     }
88
89     // TODO improve exceptions throwing
90     // along with XmlElement
91
92     public static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
93         DocumentBuilder dBuilder;
94         try {
95             dBuilder = BUILDER_FACTORY.newDocumentBuilder();
96         } catch (ParserConfigurationException e) {
97             throw new IllegalStateException("Failed to parse XML document", e);
98         }
99         Document doc = dBuilder.parse(xmlContent);
100
101         doc.getDocumentElement().normalize();
102         return doc;
103     }
104
105     public static Element readXmlToElement(final File xmlFile) throws SAXException, IOException {
106         return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
107     }
108
109     public static Document newDocument() {
110         try {
111             DocumentBuilder builder = BUILDER_FACTORY.newDocumentBuilder();
112             return builder.newDocument();
113         } catch (ParserConfigurationException e) {
114             throw new IllegalStateException("Failed to create document", e);
115         }
116     }
117
118     public static Element createElement(final Document document, final String qName, final Optional<String> namespaceURI) {
119         if(namespaceURI.isPresent()) {
120             final Element element = document.createElementNS(namespaceURI.get(), qName);
121             String name = XMLNS_ATTRIBUTE_KEY;
122             if(element.getPrefix() != null) {
123                 name += ":" + element.getPrefix();
124             }
125             element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
126             return element;
127         }
128         return document.createElement(qName);
129     }
130
131     public static Element createTextElement(final Document document, final String qName, final String content, final Optional<String> namespaceURI) {
132         Element typeElement = createElement(document, qName, namespaceURI);
133         typeElement.appendChild(document.createTextNode(content));
134         return typeElement;
135     }
136
137     public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
138                                                                  final String namespace, final String contentWithoutPrefix) {
139
140         return createTextElementWithNamespacedContent(document, qName, prefix, namespace, contentWithoutPrefix, Optional.<String>absent());
141     }
142
143     public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
144                                                                  final String namespace, final String contentWithoutPrefix, final Optional<String> namespaceURI) {
145
146         String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
147         Element element = createTextElement(document, qName, content, namespaceURI);
148         String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE_KEY, prefix);
149         element.setAttributeNS(XMLNS_URI, prefixedNamespaceAttr, namespace);
150         return element;
151     }
152
153     public static String createPrefixedValue(final String prefix, final String value) {
154         return prefix + ":" + value;
155     }
156
157     public static String toString(final Document document) {
158         return toString(document.getDocumentElement());
159     }
160
161     public static String toString(final Element xml) {
162         return toString(xml, false);
163     }
164
165     public static String toString(final XmlElement xmlElement) {
166         return toString(xmlElement.getDomElement(), false);
167     }
168
169     public static String toString(final Element xml, final boolean addXmlDeclaration) {
170         try {
171             Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
172             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
173             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
174
175             StreamResult result = new StreamResult(new StringWriter());
176             DOMSource source = new DOMSource(xml);
177             transformer.transform(source, result);
178
179             return result.getWriter().toString();
180         } catch (Exception |  TransformerFactoryConfigurationError e) {
181             throw new IllegalStateException("Unable to serialize xml element " + xml, e);
182         }
183     }
184
185     public static String toString(final Document doc, final boolean addXmlDeclaration) {
186         return toString(doc.getDocumentElement(), addXmlDeclaration);
187     }
188
189     public static Schema loadSchema(final InputStream... fromStreams) {
190         Source[] sources = new Source[fromStreams.length];
191         int i = 0;
192         for (InputStream stream : fromStreams) {
193             sources[i++] = new StreamSource(stream);
194         }
195
196         try {
197             return SCHEMA_FACTORY.newSchema(sources);
198         } catch (SAXException e) {
199             throw new IllegalStateException("Failed to instantiate XML schema", e);
200         }
201     }
202
203     public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
204         try {
205             return expr.evaluate(rootNode, returnType);
206         } catch (XPathExpressionException e) {
207             throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
208         }
209     }
210
211     public static Document createDocumentCopy(final Document original) {
212         final Document copiedDocument = newDocument();
213         final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
214         copiedDocument.appendChild(copiedRoot);
215         return copiedDocument;
216     }
217 }