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.controller.config.util.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.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.w3c.dom.Document;
37 import org.w3c.dom.Element;
38 import org.w3c.dom.Node;
39 import org.xml.sax.SAXException;
41 public final class XmlUtil {
43 public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
44 public static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
45 private static final DocumentBuilderFactory BUILDER_FACTORY;
46 private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
47 private static final SchemaFactory SCHEMA_FACTORY = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
50 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
52 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
53 factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
54 factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
55 factory.setXIncludeAware(false);
56 factory.setExpandEntityReferences(false);
57 // Performance improvement for messages with size <10k according to
58 // https://xerces.apache.org/xerces2-j/faq-performance.html
59 factory.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
60 } catch (ParserConfigurationException e) {
61 throw new ExceptionInInitializerError(e);
63 factory.setNamespaceAware(true);
64 factory.setCoalescing(true);
65 factory.setIgnoringElementContentWhitespace(true);
66 factory.setIgnoringComments(true);
67 BUILDER_FACTORY = factory;
70 private static final ThreadLocal<DocumentBuilder> DEFAULT_DOM_BUILDER = new ThreadLocal<DocumentBuilder>(){
72 protected DocumentBuilder initialValue() {
74 return BUILDER_FACTORY.newDocumentBuilder();
75 } catch (ParserConfigurationException e) {
76 throw new IllegalStateException("Failed to create threadLocal dom builder", e);
81 public void set(DocumentBuilder value) {
82 throw new UnsupportedOperationException();
87 throw new UnsupportedOperationException("Utility class");
90 public static Element readXmlToElement(final String xmlContent) throws SAXException, IOException {
91 Document doc = readXmlToDocument(xmlContent);
92 return doc.getDocumentElement();
95 public static Element readXmlToElement(final InputStream xmlContent) throws SAXException, IOException {
96 Document doc = readXmlToDocument(xmlContent);
97 return doc.getDocumentElement();
100 public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
101 return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)));
104 // TODO improve exceptions throwing
105 // along with XmlElement
107 public static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
108 Document doc = DEFAULT_DOM_BUILDER.get().parse(xmlContent);
110 doc.getDocumentElement().normalize();
114 public static Element readXmlToElement(final File xmlFile) throws SAXException, IOException {
115 return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
118 public static Document newDocument() {
119 return DEFAULT_DOM_BUILDER.get().newDocument();
122 public static Element createElement(final Document document, final String qName, final Optional<String> namespaceURI) {
123 if(namespaceURI.isPresent()) {
124 final Element element = document.createElementNS(namespaceURI.get(), qName);
125 String name = XMLNS_ATTRIBUTE_KEY;
126 if(element.getPrefix() != null) {
127 name += ":" + element.getPrefix();
129 element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
132 return document.createElement(qName);
135 public static Element createTextElement(final Document document, final String qName, final String content, final Optional<String> namespaceURI) {
136 Element typeElement = createElement(document, qName, namespaceURI);
137 typeElement.appendChild(document.createTextNode(content));
141 public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
142 final String namespace, final String contentWithoutPrefix) {
144 return createTextElementWithNamespacedContent(document, qName, prefix, namespace, contentWithoutPrefix, Optional.<String>absent());
147 public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
148 final String namespace, final String contentWithoutPrefix, final Optional<String> namespaceURI) {
150 String content = createPrefixedValue(XmlMappingConstants.PREFIX, contentWithoutPrefix);
151 Element element = createTextElement(document, qName, content, namespaceURI);
152 String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE_KEY, prefix);
153 element.setAttributeNS(XMLNS_URI, prefixedNamespaceAttr, namespace);
157 public static String createPrefixedValue(final String prefix, final String value) {
158 return prefix + ":" + value;
161 public static String toString(final Document document) {
162 return toString(document.getDocumentElement());
165 public static String toString(final Element xml) {
166 return toString(xml, false);
169 public static String toString(final XmlElement xmlElement) {
170 return toString(xmlElement.getDomElement(), false);
173 public static String toString(final Element xml, final boolean addXmlDeclaration) {
175 Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
176 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
177 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
179 StreamResult result = new StreamResult(new StringWriter());
180 DOMSource source = new DOMSource(xml);
181 transformer.transform(source, result);
183 return result.getWriter().toString();
184 } catch (Exception | TransformerFactoryConfigurationError e) {
185 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
189 public static String toString(final Document doc, final boolean addXmlDeclaration) {
190 return toString(doc.getDocumentElement(), addXmlDeclaration);
193 public static Schema loadSchema(final InputStream... fromStreams) {
194 Source[] sources = new Source[fromStreams.length];
196 for (InputStream stream : fromStreams) {
197 sources[i++] = new StreamSource(stream);
201 return SCHEMA_FACTORY.newSchema(sources);
202 } catch (SAXException e) {
203 throw new IllegalStateException("Failed to instantiate XML schema", e);
207 public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
209 return expr.evaluate(rootNode, returnType);
210 } catch (XPathExpressionException e) {
211 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
215 public static Document createDocumentCopy(final Document original) {
216 final Document copiedDocument = newDocument();
217 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
218 copiedDocument.appendChild(copiedRoot);
219 return copiedDocument;