2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.api.xml;
10 import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE;
11 import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
13 import java.io.ByteArrayInputStream;
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;
44 public final class XmlUtil {
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);
51 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
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);
64 factory.setNamespaceAware(true);
65 factory.setCoalescing(true);
66 factory.setIgnoringElementContentWhitespace(true);
67 factory.setIgnoringComments(true);
68 BUILDER_FACTORY = factory;
71 private static final ThreadLocal<DocumentBuilder> DEFAULT_DOM_BUILDER = new ThreadLocal<DocumentBuilder>() {
73 protected DocumentBuilder initialValue() {
75 return BUILDER_FACTORY.newDocumentBuilder();
76 } catch (final ParserConfigurationException e) {
77 throw new IllegalStateException("Failed to create threadLocal dom builder", e);
82 public void set(final DocumentBuilder value) {
83 throw new UnsupportedOperationException();
88 throw new UnsupportedOperationException("Utility class");
91 public static Element readXmlToElement(final File xmlFile) throws SAXException, IOException {
92 return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
95 public static Element readXmlToElement(final String xmlContent) throws SAXException, IOException {
96 Document doc = readXmlToDocument(xmlContent);
97 return doc.getDocumentElement();
100 public static Element readXmlToElement(final InputStream xmlContent) throws SAXException, IOException {
101 Document doc = readXmlToDocument(xmlContent);
102 return doc.getDocumentElement();
105 public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
106 return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)));
109 // TODO improve exceptions throwing
110 // along with XmlElement
112 public static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
113 Document doc = DEFAULT_DOM_BUILDER.get().parse(xmlContent);
115 doc.getDocumentElement().normalize();
119 public static Document newDocument() {
120 return DEFAULT_DOM_BUILDER.get().newDocument();
123 public static Element createElement(final Document document, final String qname,
124 final Optional<String> namespaceURI) {
125 if (namespaceURI.isEmpty()) {
126 return document.createElement(qname);
129 final String uri = namespaceURI.get();
130 final Element element = document.createElementNS(uri, qname);
131 String name = XMLNS_ATTRIBUTE;
132 if (element.getPrefix() != null) {
133 name += ":" + element.getPrefix();
135 element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, name, uri);
139 public static Element createTextElement(final Document document, final String qname, final String content,
140 final Optional<String> namespaceURI) {
141 Element typeElement = createElement(document, qname, namespaceURI);
142 typeElement.appendChild(document.createTextNode(content));
146 public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
147 final String prefix, final String namespace, final String contentWithoutPrefix) {
149 return createTextElementWithNamespacedContent(document, qname, prefix, namespace, contentWithoutPrefix,
153 public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
154 final String prefix, final String namespace, final String contentWithoutPrefix,
155 final Optional<String> namespaceURI) {
157 String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
158 Element element = createTextElement(document, qname, content, namespaceURI);
159 String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE, prefix);
160 element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, prefixedNamespaceAttr, namespace);
164 public static String createPrefixedValue(final String prefix, final String value) {
165 return prefix + ":" + value;
168 public static String toString(final Document document) {
169 return toString(document.getDocumentElement());
172 public static String toString(final Element xml) {
173 return toString(xml, false);
176 public static String toString(final XmlElement xmlElement) {
177 return toString(xmlElement.getDomElement(), false);
180 public static String toString(final Element xml, final boolean addXmlDeclaration) {
182 Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
183 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
184 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
186 StreamResult result = new StreamResult(new StringWriter());
187 DOMSource source = new DOMSource(xml);
188 transformer.transform(source, result);
190 return result.getWriter().toString();
191 } catch (TransformerFactoryConfigurationError | TransformerException e) {
192 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
196 public static String toString(final Document doc, final boolean addXmlDeclaration) {
197 return toString(doc.getDocumentElement(), addXmlDeclaration);
200 public static Schema loadSchema(final InputStream... fromStreams) {
201 Source[] sources = new Source[fromStreams.length];
203 for (InputStream stream : fromStreams) {
204 sources[index++] = new StreamSource(stream);
208 return SCHEMA_FACTORY.newSchema(sources);
209 } catch (final SAXException e) {
210 throw new IllegalStateException("Failed to instantiate XML schema", e);
214 public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
216 return expr.evaluate(rootNode, returnType);
217 } catch (final XPathExpressionException e) {
218 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
222 public static Document createDocumentCopy(final Document original) {
223 final Document copiedDocument = newDocument();
224 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
225 copiedDocument.appendChild(copiedRoot);
226 return copiedDocument;