2 * Copyright (c) 2013 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.controller.netconf.util.xml;
11 import com.google.common.base.Charsets;
12 import com.google.common.base.Optional;
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 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;
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 (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 (ParserConfigurationException e) {
77 throw new IllegalStateException("Failed to create threadLocal dom builder", e);
82 public void set(DocumentBuilder value) {
83 throw new UnsupportedOperationException();
88 throw new UnsupportedOperationException("Utility class");
91 public static Element readXmlToElement(final String xmlContent) throws SAXException, IOException {
92 Document doc = readXmlToDocument(xmlContent);
93 return doc.getDocumentElement();
96 public static Element readXmlToElement(final InputStream xmlContent) throws SAXException, IOException {
97 Document doc = readXmlToDocument(xmlContent);
98 return doc.getDocumentElement();
101 public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
102 return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
105 // TODO improve exceptions throwing
106 // along with XmlElement
108 public static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
109 Document doc = DEFAULT_DOM_BUILDER.get().parse(xmlContent);
111 doc.getDocumentElement().normalize();
115 public static Element readXmlToElement(final File xmlFile) throws SAXException, IOException {
116 return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
119 public static Document newDocument() {
120 return DEFAULT_DOM_BUILDER.get().newDocument();
123 public static Element createElement(final Document document, final String qName, final Optional<String> namespaceURI) {
124 if(namespaceURI.isPresent()) {
125 final Element element = document.createElementNS(namespaceURI.get(), qName);
126 String name = XMLNS_ATTRIBUTE_KEY;
127 if(element.getPrefix() != null) {
128 name += ":" + element.getPrefix();
130 element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
133 return document.createElement(qName);
136 public static Element createTextElement(final Document document, final String qName, final String content, final Optional<String> namespaceURI) {
137 Element typeElement = createElement(document, qName, namespaceURI);
138 typeElement.appendChild(document.createTextNode(content));
142 public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
143 final String namespace, final String contentWithoutPrefix) {
145 return createTextElementWithNamespacedContent(document, qName, prefix, namespace, contentWithoutPrefix, Optional.<String>absent());
148 public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
149 final String namespace, final String contentWithoutPrefix, final Optional<String> namespaceURI) {
151 String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
152 Element element = createTextElement(document, qName, content, namespaceURI);
153 String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE_KEY, prefix);
154 element.setAttributeNS(XMLNS_URI, prefixedNamespaceAttr, namespace);
158 public static String createPrefixedValue(final String prefix, final String value) {
159 return prefix + ":" + value;
162 public static String toString(final Document document) {
163 return toString(document.getDocumentElement());
166 public static String toString(final Element xml) {
167 return toString(xml, false);
170 public static String toString(final XmlElement xmlElement) {
171 return toString(xmlElement.getDomElement(), false);
174 public static String toString(final Element xml, final boolean addXmlDeclaration) {
176 Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
177 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
178 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
180 StreamResult result = new StreamResult(new StringWriter());
181 DOMSource source = new DOMSource(xml);
182 transformer.transform(source, result);
184 return result.getWriter().toString();
185 } catch (Exception | TransformerFactoryConfigurationError e) {
186 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
190 public static String toString(final Document doc, final boolean addXmlDeclaration) {
191 return toString(doc.getDocumentElement(), addXmlDeclaration);
194 public static Schema loadSchema(final InputStream... fromStreams) {
195 Source[] sources = new Source[fromStreams.length];
197 for (InputStream stream : fromStreams) {
198 sources[i++] = new StreamSource(stream);
202 return SCHEMA_FACTORY.newSchema(sources);
203 } catch (SAXException e) {
204 throw new IllegalStateException("Failed to instantiate XML schema", e);
208 public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
210 return expr.evaluate(rootNode, returnType);
211 } catch (XPathExpressionException e) {
212 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
216 public static Document createDocumentCopy(final Document original) {
217 final Document copiedDocument = newDocument();
218 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
219 copiedDocument.appendChild(copiedRoot);
220 return copiedDocument;