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 } catch (ParserConfigurationException e) {
59 throw new ExceptionInInitializerError(e);
61 factory.setNamespaceAware(true);
62 factory.setCoalescing(true);
63 factory.setIgnoringElementContentWhitespace(true);
64 factory.setIgnoringComments(true);
65 BUILDER_FACTORY = factory;
69 throw new UnsupportedOperationException("Utility class");
72 public static Element readXmlToElement(final String xmlContent) throws SAXException, IOException {
73 Document doc = readXmlToDocument(xmlContent);
74 return doc.getDocumentElement();
77 public static Element readXmlToElement(final InputStream xmlContent) throws SAXException, IOException {
78 Document doc = readXmlToDocument(xmlContent);
79 return doc.getDocumentElement();
82 public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
83 return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
86 // TODO improve exceptions throwing
87 // along with XmlElement
89 public static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
90 DocumentBuilder dBuilder;
92 dBuilder = BUILDER_FACTORY.newDocumentBuilder();
93 } catch (ParserConfigurationException e) {
94 throw new IllegalStateException("Failed to parse XML document", e);
96 Document doc = dBuilder.parse(xmlContent);
98 doc.getDocumentElement().normalize();
102 public static Element readXmlToElement(final File xmlFile) throws SAXException, IOException {
103 return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
106 public static Document newDocument() {
108 DocumentBuilder builder = BUILDER_FACTORY.newDocumentBuilder();
109 return builder.newDocument();
110 } catch (ParserConfigurationException e) {
111 throw new IllegalStateException("Failed to create document", e);
115 public static Element createElement(final Document document, final String qName, final Optional<String> namespaceURI) {
116 if(namespaceURI.isPresent()) {
117 final Element element = document.createElementNS(namespaceURI.get(), qName);
118 String name = XMLNS_ATTRIBUTE_KEY;
119 if(element.getPrefix() != null) {
120 name += ":" + element.getPrefix();
122 element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
125 return document.createElement(qName);
128 public static Element createTextElement(final Document document, final String qName, final String content, final Optional<String> namespaceURI) {
129 Element typeElement = createElement(document, qName, namespaceURI);
130 typeElement.appendChild(document.createTextNode(content));
134 public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
135 final String namespace, final String contentWithoutPrefix) {
137 return createTextElementWithNamespacedContent(document, qName, prefix, namespace, contentWithoutPrefix, Optional.<String>absent());
140 public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
141 final String namespace, final String contentWithoutPrefix, final Optional<String> namespaceURI) {
143 String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
144 Element element = createTextElement(document, qName, content, namespaceURI);
145 String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE_KEY, prefix);
146 element.setAttributeNS(XMLNS_URI, prefixedNamespaceAttr, namespace);
150 public static String createPrefixedValue(final String prefix, final String value) {
151 return prefix + ":" + value;
154 public static String toString(final Document document) {
155 return toString(document.getDocumentElement());
158 public static String toString(final Element xml) {
159 return toString(xml, false);
162 public static String toString(final XmlElement xmlElement) {
163 return toString(xmlElement.getDomElement(), false);
166 public static String toString(final Element xml, final boolean addXmlDeclaration) {
168 Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
169 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
170 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
172 StreamResult result = new StreamResult(new StringWriter());
173 DOMSource source = new DOMSource(xml);
174 transformer.transform(source, result);
176 return result.getWriter().toString();
177 } catch (Exception | TransformerFactoryConfigurationError e) {
178 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
182 public static String toString(final Document doc, final boolean addXmlDeclaration) {
183 return toString(doc.getDocumentElement(), addXmlDeclaration);
186 public static Schema loadSchema(final InputStream... fromStreams) {
187 Source[] sources = new Source[fromStreams.length];
189 for (InputStream stream : fromStreams) {
190 sources[i++] = new StreamSource(stream);
194 return SCHEMA_FACTORY.newSchema(sources);
195 } catch (SAXException e) {
196 throw new IllegalStateException("Failed to instantiate XML schema", e);
200 public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
202 return expr.evaluate(rootNode, returnType);
203 } catch (XPathExpressionException e) {
204 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
208 public static Document createDocumentCopy(final Document original) {
209 final Document copiedDocument = newDocument();
210 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
211 copiedDocument.appendChild(copiedRoot);
212 return copiedDocument;