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
9 package org.opendaylight.netconf.api.xml;
11 import com.google.common.base.Optional;
12 import java.io.ByteArrayInputStream;
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;
42 public final class XmlUtil {
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);
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 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();
131 element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
134 return document.createElement(qmame);
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));
144 public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
145 final String prefix, final String namespace, final String contentWithoutPrefix) {
147 return createTextElementWithNamespacedContent(document, qname, prefix, namespace, contentWithoutPrefix,
148 Optional.<String>absent());
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) {
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);
162 public static String createPrefixedValue(final String prefix, final String value) {
163 return prefix + ":" + value;
166 public static String toString(final Document document) {
167 return toString(document.getDocumentElement());
170 public static String toString(final Element xml) {
171 return toString(xml, false);
174 public static String toString(final XmlElement xmlElement) {
175 return toString(xmlElement.getDomElement(), false);
178 public static String toString(final Element xml, final boolean addXmlDeclaration) {
180 Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
181 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
182 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
184 StreamResult result = new StreamResult(new StringWriter());
185 DOMSource source = new DOMSource(xml);
186 transformer.transform(source, result);
188 return result.getWriter().toString();
189 } catch (TransformerFactoryConfigurationError | TransformerException e) {
190 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
194 public static String toString(final Document doc, final boolean addXmlDeclaration) {
195 return toString(doc.getDocumentElement(), addXmlDeclaration);
198 public static Schema loadSchema(final InputStream... fromStreams) {
199 Source[] sources = new Source[fromStreams.length];
201 for (InputStream stream : fromStreams) {
202 sources[index++] = new StreamSource(stream);
206 return SCHEMA_FACTORY.newSchema(sources);
207 } catch (final SAXException e) {
208 throw new IllegalStateException("Failed to instantiate XML schema", e);
212 public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
214 return expr.evaluate(rootNode, returnType);
215 } catch (final XPathExpressionException e) {
216 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
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;