Fix star import and enable checkstyle rule to prevent it.
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / xml / XmlUtil.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.netconf.util.xml;
10
11 import com.google.common.base.Charsets;
12 import org.w3c.dom.Document;
13 import org.w3c.dom.Element;
14 import org.w3c.dom.Node;
15 import org.xml.sax.SAXException;
16
17 import javax.xml.XMLConstants;
18 import javax.xml.namespace.QName;
19 import javax.xml.parsers.DocumentBuilder;
20 import javax.xml.parsers.DocumentBuilderFactory;
21 import javax.xml.parsers.ParserConfigurationException;
22 import javax.xml.transform.OutputKeys;
23 import javax.xml.transform.Source;
24 import javax.xml.transform.Transformer;
25 import javax.xml.transform.TransformerException;
26 import javax.xml.transform.TransformerFactory;
27 import javax.xml.transform.TransformerFactoryConfigurationError;
28 import javax.xml.transform.dom.DOMSource;
29 import javax.xml.transform.stream.StreamResult;
30 import javax.xml.transform.stream.StreamSource;
31 import javax.xml.validation.Schema;
32 import javax.xml.validation.SchemaFactory;
33 import javax.xml.xpath.XPathExpression;
34 import javax.xml.xpath.XPathExpressionException;
35 import java.io.ByteArrayInputStream;
36 import java.io.File;
37 import java.io.FileInputStream;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.StringWriter;
41
42 public class XmlUtil {
43
44     public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
45
46     public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
47         Document doc = readXmlToDocument(xmlContent);
48         return doc.getDocumentElement();
49     }
50
51     public static Element readXmlToElement(InputStream xmlContent) throws SAXException, IOException {
52         Document doc = readXmlToDocument(xmlContent);
53         return doc.getDocumentElement();
54     }
55
56     public static Document readXmlToDocument(String xmlContent) throws SAXException, IOException {
57         return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
58     }
59
60     public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
61         DocumentBuilderFactory factory = getDocumentBuilderFactory();
62         DocumentBuilder dBuilder;
63         try {
64             dBuilder = factory.newDocumentBuilder();
65         } catch (ParserConfigurationException e) {
66             throw new RuntimeException(e);
67         }
68         Document doc = dBuilder.parse(xmlContent);
69
70         doc.getDocumentElement().normalize();
71         return doc;
72     }
73
74     public static Element readXmlToElement(File xmlFile) throws SAXException, IOException {
75         return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
76     }
77
78     private static final DocumentBuilderFactory getDocumentBuilderFactory() {
79         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
80         factory.setNamespaceAware(true);
81         factory.setCoalescing(true);
82         // factory.setValidating(true);
83         factory.setIgnoringElementContentWhitespace(true);
84         factory.setIgnoringComments(true);
85         return factory;
86     }
87
88     public static Document newDocument() {
89         DocumentBuilderFactory factory = getDocumentBuilderFactory();
90         try {
91             DocumentBuilder builder = factory.newDocumentBuilder();
92             Document document = builder.newDocument();
93             return document;
94         } catch (ParserConfigurationException e) {
95             throw new RuntimeException(e);
96         }
97     }
98
99     public static Element createTextElement(Document document, String name, String content) {
100         Element typeElement = document.createElement(name);
101         typeElement.appendChild(document.createTextNode(content));
102         return typeElement;
103     }
104
105     public static void addNamespaceAttr(Element root, String namespace) {
106         root.setAttribute(XMLNS_ATTRIBUTE_KEY, namespace);
107     }
108
109     public static void addPrefixedNamespaceAttr(Element root, String prefix, String namespace) {
110         root.setAttribute(concat(XMLNS_ATTRIBUTE_KEY, prefix), namespace);
111     }
112
113     public static Element createPrefixedTextElement(Document document, String key, String prefix, String moduleName) {
114         return createTextElement(document, key, concat(prefix, moduleName));
115     }
116
117     private static String concat(String prefix, String value) {
118         return prefix + ":" + value;
119     }
120
121     public static String toString(Document document) {
122         return toString(document.getDocumentElement());
123     }
124
125     public static String toString(Element xml) {
126         return toString(xml, false);
127     }
128
129     public static String toString(XmlElement xmlElement) {
130         return toString(xmlElement.getDomElement(), false);
131     }
132
133     public static String toString(Element xml, boolean addXmlDeclaration) {
134         try {
135             Transformer transformer = TransformerFactory.newInstance().newTransformer();
136             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
137             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration == true ? "no" : "yes");
138
139             StreamResult result = new StreamResult(new StringWriter());
140             DOMSource source = new DOMSource(xml);
141             transformer.transform(source, result);
142
143             String xmlString = result.getWriter().toString();
144             return xmlString;
145         } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
146             throw new RuntimeException("Unable to serialize xml element " + xml, e);
147         }
148     }
149
150     public static String toString(Document doc, boolean addXmlDeclaration) {
151         return toString(doc.getDocumentElement(), addXmlDeclaration);
152     }
153
154     public static Schema loadSchema(InputStream... fromStreams) {
155         Source[] sources = new Source[fromStreams.length];
156         int i = 0;
157         for (InputStream stream : fromStreams) {
158             sources[i++] = new StreamSource(stream);
159         }
160
161         final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
162         try {
163             return schemaFactory.newSchema(sources);
164         } catch (SAXException e) {
165             throw new IllegalStateException("Failed to instantiate XML schema", e);
166         }
167     }
168
169     public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
170         try {
171             return expr.evaluate(rootNode, returnType);
172         } catch (XPathExpressionException e) {
173             throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
174         }
175     }
176
177     public static Document createDocumentCopy(Document original) {
178         final Document copiedDocument = newDocument();
179         final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
180         copiedDocument.appendChild(copiedRoot);
181         return copiedDocument;
182     }
183 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.