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 / XmlElement.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.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicate;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Maps;
17 import org.w3c.dom.Attr;
18 import org.w3c.dom.Document;
19 import org.w3c.dom.Element;
20 import org.w3c.dom.NamedNodeMap;
21 import org.w3c.dom.Node;
22 import org.w3c.dom.NodeList;
23 import org.w3c.dom.Text;
24 import org.xml.sax.SAXException;
25
26 import javax.annotation.Nullable;
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33
34 public class XmlElement {
35
36     public final Element element;
37
38     private XmlElement(Element element) {
39         this.element = element;
40     }
41
42     public static XmlElement fromDomElement(Element e) {
43         return new XmlElement(e);
44     }
45
46     public static XmlElement fromDomDocument(Document xml) {
47         return new XmlElement(xml.getDocumentElement());
48     }
49
50     public static XmlElement fromString(String s) {
51         try {
52             return new XmlElement(XmlUtil.readXmlToElement(s));
53         } catch (IOException | SAXException e) {
54             throw new IllegalArgumentException("Unable to create from " + s, e);
55         }
56     }
57
58     public static XmlElement fromDomElementWithExpected(Element element, String expectedName) {
59         XmlElement xmlElement = XmlElement.fromDomElement(element);
60         xmlElement.checkName(expectedName);
61         return xmlElement;
62     }
63
64     public static XmlElement fromDomElementWithExpected(Element element, String expectedName, String expectedNamespace) {
65         XmlElement xmlElement = XmlElement.fromDomElementWithExpected(element, expectedName);
66         xmlElement.checkNamespace(expectedNamespace);
67         return xmlElement;
68     }
69
70     private static Map<String, String> extractNamespaces(Element typeElement) {
71         Map<String, String> namespaces = new HashMap<>();
72         NamedNodeMap attributes = typeElement.getAttributes();
73         for (int i = 0; i < attributes.getLength(); i++) {
74             Node attribute = attributes.item(i);
75             String attribKey = attribute.getNodeName();
76             if (attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
77                 String prefix;
78                 if (attribKey.equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
79                     prefix = "";
80                 } else {
81                     Preconditions.checkState(attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY + ":"));
82                     prefix = attribKey.substring(XmlUtil.XMLNS_ATTRIBUTE_KEY.length() + 1);
83                 }
84                 namespaces.put(prefix, attribute.getNodeValue());
85             }
86         }
87         return namespaces;
88     }
89
90     public void checkName(String expectedName) {
91         Preconditions.checkArgument(getName().equals(expectedName), "Expected %s xml element but was %s", expectedName,
92                 getName());
93     }
94
95     public void checkNamespaceAttribute(String expectedNamespace) {
96         Preconditions.checkArgument(getNamespaceAttribute().equals(expectedNamespace),
97                 "Unexpected namespace %s for element %s, should be %s", getNamespaceAttribute(), expectedNamespace);
98     }
99
100     public void checkNamespace(String expectedNamespace) {
101         Preconditions.checkArgument(getNamespace().equals(expectedNamespace),
102                 "Unexpected namespace %s for element %s, should be %s", getNamespace(), expectedNamespace);
103     }
104
105     public String getName() {
106         return element.getTagName();
107     }
108
109     public String getAttribute(String attributeName) {
110         return element.getAttribute(attributeName);
111     }
112
113     public String getAttribute(String attributeName, String namespace) {
114         return element.getAttributeNS(namespace, attributeName);
115     }
116
117     public void appendChild(Element element) {
118         this.element.appendChild(element);
119         // Element newElement = (Element) element.cloneNode(true);
120         // newElement.appendChild(configElement);
121         // return XmlElement.fromDomElement(newElement);
122     }
123
124     public Element getDomElement() {
125         return element;
126     }
127
128     public Map<String, Attr> getAttributes() {
129
130         Map<String, Attr> mappedAttributes = Maps.newHashMap();
131
132         NamedNodeMap attributes = element.getAttributes();
133         for (int i = 0; i < attributes.getLength(); i++) {
134             Attr attr = (Attr) attributes.item(i);
135             mappedAttributes.put(attr.getNodeName(), attr);
136         }
137
138         return mappedAttributes;
139     }
140
141     /**
142      * Non recursive
143      */
144     private List<XmlElement> getChildElementsInternal(ElementFilteringStrategy strat) {
145         NodeList childNodes = element.getChildNodes();
146         final List<XmlElement> result = new ArrayList<>();
147         for (int i = 0; i < childNodes.getLength(); i++) {
148             Node item = childNodes.item(i);
149             if (item instanceof Element == false)
150                 continue;
151             if (strat.accept((Element) item))
152                 result.add(new XmlElement((Element) item));
153         }
154
155         return result;
156     }
157
158     public List<XmlElement> getChildElements() {
159         return getChildElementsInternal(new ElementFilteringStrategy() {
160             @Override
161             public boolean accept(Element e) {
162                 return true;
163             }
164         });
165     }
166
167     public List<XmlElement> getChildElementsWithinNamespace(final String childName, String namespace) {
168         return Lists.newArrayList(Collections2.filter(getChildElementsWithinNamespace(namespace),
169                 new Predicate<XmlElement>() {
170                     @Override
171                     public boolean apply(@Nullable XmlElement xmlElement) {
172                         return xmlElement.getName().equals(childName);
173                     }
174                 }));
175     }
176
177     public List<XmlElement> getChildElementsWithinNamespace(final String namespace) {
178         return getChildElementsInternal(new ElementFilteringStrategy() {
179             @Override
180             public boolean accept(Element e) {
181                 return XmlElement.fromDomElement(e).getNamespace().equals(namespace);
182             }
183
184         });
185     }
186
187     public List<XmlElement> getChildElements(final String tagName) {
188         return getChildElementsInternal(new ElementFilteringStrategy() {
189             @Override
190             public boolean accept(Element e) {
191                 return e.getTagName().equals(tagName);
192             }
193         });
194     }
195
196     public XmlElement getOnlyChildElement(String childName) {
197         List<XmlElement> nameElements = getChildElements(childName);
198         Preconditions.checkState(nameElements.size() == 1, "One element " + childName + " expected in " + toString());
199         return nameElements.get(0);
200     }
201
202     public Optional<XmlElement> getOnlyChildElementOptionally(String childName) {
203         try {
204             return Optional.of(getOnlyChildElement(childName));
205         } catch (Exception e) {
206             return Optional.absent();
207         }
208     }
209
210     public Optional<XmlElement> getOnlyChildElementOptionally(String childName, String namespace) {
211         try {
212             return Optional.of(getOnlyChildElement(childName, namespace));
213         } catch (Exception e) {
214             return Optional.absent();
215         }
216     }
217
218     public XmlElement getOnlyChildElementWithSameNamespace(String childName) {
219         return getOnlyChildElement(childName, getNamespace());
220     }
221
222     public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally(String childName) {
223         try {
224             return Optional.of(getOnlyChildElement(childName, getNamespace()));
225         } catch (Exception e) {
226             return Optional.absent();
227         }
228     }
229
230     public XmlElement getOnlyChildElementWithSameNamespace() {
231         XmlElement childElement = getOnlyChildElement();
232         childElement.checkNamespace(getNamespace());
233         return childElement;
234     }
235
236     public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally() {
237         try {
238             XmlElement childElement = getOnlyChildElement();
239             childElement.checkNamespace(getNamespace());
240             return Optional.of(childElement);
241         } catch (Exception e) {
242             return Optional.absent();
243         }
244     }
245
246     public XmlElement getOnlyChildElement(final String childName, String namespace) {
247         List<XmlElement> children = getChildElementsWithinNamespace(namespace);
248         children = Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
249             @Override
250             public boolean apply(@Nullable XmlElement xmlElement) {
251                 return xmlElement.getName().equals(childName);
252             }
253         }));
254         Preconditions.checkState(children.size() == 1, "One element %s:%s expected in %s but was %s", namespace,
255                 childName, toString(), children.size());
256         return children.get(0);
257     }
258
259     public XmlElement getOnlyChildElement() {
260         List<XmlElement> children = getChildElements();
261         Preconditions.checkState(children.size() == 1, "One element expected in %s but was %s", toString(),
262                 children.size());
263         return children.get(0);
264     }
265
266     public String getTextContent() {
267         Node textChild = element.getFirstChild();
268         Preconditions.checkState(textChild instanceof Text, getName() + " should contain text");
269         String content = textChild.getTextContent();
270         // Trim needed
271         return content.trim();
272     }
273
274     public String getNamespaceAttribute() {
275         String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY);
276         Preconditions.checkState(attribute != null && !attribute.equals(""), "Element %s must specify a %s attribute",
277                 toString(), XmlUtil.XMLNS_ATTRIBUTE_KEY);
278         return attribute;
279     }
280
281     public String getNamespace() {
282         String namespaceURI = element.getNamespaceURI();
283         Preconditions.checkState(namespaceURI != null, "No namespace defined for %s", this);
284         return namespaceURI.toString();
285     }
286
287     @Override
288     public String toString() {
289         final StringBuffer sb = new StringBuffer("XmlElement{");
290         sb.append("name='").append(getName()).append('\'');
291         if (element.getNamespaceURI() != null) {
292             sb.append(", namespace='").append(getNamespace()).append('\'');
293         }
294         sb.append('}');
295         return sb.toString();
296     }
297
298     /**
299      * Search for element's attributes defining namespaces. Look for the one
300      * namespace that matches prefix of element's text content. E.g.
301      *
302      * <pre>
303      * &lt;type
304      * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl"&gt;th-java:threadfactory-naming&lt;/type&gt;
305      * </pre>
306      *
307      * returns {"th-java","urn:.."}. If no prefix is matched, then default
308      * namespace is returned with empty string as key. If no default namespace
309      * is found value will be null.
310      */
311     public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() {
312         Map<String, String> namespaces = extractNamespaces(element);
313         String textContent = getTextContent();
314         int indexOfColon = textContent.indexOf(":");
315         String prefix;
316         if (indexOfColon > -1) {
317             prefix = textContent.substring(0, indexOfColon);
318         } else {
319             prefix = "";
320         }
321         if (namespaces.containsKey(prefix) == false) {
322             throw new IllegalArgumentException("Cannot find namespace for " + element + ". Prefix from content is "
323                     + prefix + ". Found namespaces " + namespaces);
324         }
325         return Maps.immutableEntry(prefix, namespaces.get(prefix));
326     }
327
328     public List<XmlElement> getChildElementsWithSameNamespace(final String childName) {
329         List<XmlElement> children = getChildElementsWithinNamespace(getNamespace());
330         return Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
331             @Override
332             public boolean apply(@Nullable XmlElement xmlElement) {
333                 return xmlElement.getName().equals(childName);
334             }
335         }));
336     }
337
338     public void checkUnrecognisedElements(List<XmlElement> recognisedElements,
339             XmlElement... additionalRecognisedElements) {
340         List<XmlElement> childElements = getChildElements();
341         childElements.removeAll(recognisedElements);
342         for (XmlElement additionalRecognisedElement : additionalRecognisedElements) {
343             childElements.remove(additionalRecognisedElement);
344         }
345         Preconditions.checkState(childElements.isEmpty(), "Unrecognised elements %s in %s", childElements, this);
346     }
347
348     public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) {
349         checkUnrecognisedElements(Collections.<XmlElement> emptyList(), additionalRecognisedElements);
350     }
351
352     @Override
353     public boolean equals(Object o) {
354         if (this == o)
355             return true;
356         if (o == null || getClass() != o.getClass())
357             return false;
358
359         XmlElement that = (XmlElement) o;
360
361         if (!element.isEqualNode(that.element))
362             return false;
363
364         return true;
365     }
366
367     @Override
368     public int hashCode() {
369         return element.hashCode();
370     }
371
372     private static interface ElementFilteringStrategy {
373         boolean accept(Element e);
374     }
375 }