Bug 716: Errors on controller shutdown
[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.Predicate;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.Lists;
15 import com.google.common.collect.Maps;
16 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
17 import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
18 import org.opendaylight.controller.netconf.util.exception.UnexpectedElementException;
19 import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22 import org.w3c.dom.Attr;
23 import org.w3c.dom.Document;
24 import org.w3c.dom.Element;
25 import org.w3c.dom.NamedNodeMap;
26 import org.w3c.dom.Node;
27 import org.w3c.dom.NodeList;
28 import org.w3c.dom.Text;
29 import org.xml.sax.SAXException;
30
31 import javax.annotation.Nullable;
32 import java.io.IOException;
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38
39 public final class XmlElement {
40
41     private final Element element;
42     private static final Logger logger = LoggerFactory.getLogger(XmlElement.class);
43
44     private XmlElement(Element element) {
45         this.element = element;
46     }
47
48     public static XmlElement fromDomElement(Element e) {
49         return new XmlElement(e);
50     }
51
52     public static XmlElement fromDomDocument(Document xml) {
53         return new XmlElement(xml.getDocumentElement());
54     }
55
56     public static XmlElement fromString(String s) throws NetconfDocumentedException {
57         try {
58             return new XmlElement(XmlUtil.readXmlToElement(s));
59         } catch (IOException | SAXException e) {
60             throw NetconfDocumentedException.wrap(e);
61         }
62     }
63
64     public static XmlElement fromDomElementWithExpected(Element element, String expectedName) throws NetconfDocumentedException {
65         XmlElement xmlElement = XmlElement.fromDomElement(element);
66         xmlElement.checkName(expectedName);
67         return xmlElement;
68     }
69
70     public static XmlElement fromDomElementWithExpected(Element element, String expectedName, String expectedNamespace) throws NetconfDocumentedException {
71         XmlElement xmlElement = XmlElement.fromDomElementWithExpected(element, expectedName);
72         xmlElement.checkNamespace(expectedNamespace);
73         return xmlElement;
74     }
75
76     private static Map<String, String> extractNamespaces(Element typeElement) throws NetconfDocumentedException {
77         Map<String, String> namespaces = new HashMap<>();
78         NamedNodeMap attributes = typeElement.getAttributes();
79         for (int i = 0; i < attributes.getLength(); i++) {
80             Node attribute = attributes.item(i);
81             String attribKey = attribute.getNodeName();
82             if (attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
83                 String prefix;
84                 if (attribKey.equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
85                     prefix = "";
86                 } else {
87                     if (!attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY + ":")){
88                         throw new NetconfDocumentedException("Attribute doesn't start with :",
89                                 NetconfDocumentedException.ErrorType.application,
90                                 NetconfDocumentedException.ErrorTag.invalid_value,
91                                 NetconfDocumentedException.ErrorSeverity.error);
92                     }
93                     prefix = attribKey.substring(XmlUtil.XMLNS_ATTRIBUTE_KEY.length() + 1);
94                 }
95                 namespaces.put(prefix, attribute.getNodeValue());
96             }
97         }
98         return namespaces;
99     }
100
101     public void checkName(String expectedName) throws UnexpectedElementException {
102         if (!getName().equals(expectedName)){
103             throw new UnexpectedElementException(String.format("Expected %s xml element but was %s", expectedName,
104                     getName()),
105                     NetconfDocumentedException.ErrorType.application,
106                     NetconfDocumentedException.ErrorTag.operation_failed,
107                     NetconfDocumentedException.ErrorSeverity.error);
108         }
109     }
110
111     public void checkNamespaceAttribute(String expectedNamespace) throws UnexpectedNamespaceException, MissingNameSpaceException {
112         if (!getNamespaceAttribute().equals(expectedNamespace))
113         {
114             throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s for element %s, should be %s",
115                     getNamespaceAttribute(),
116                     expectedNamespace),
117                     NetconfDocumentedException.ErrorType.application,
118                     NetconfDocumentedException.ErrorTag.operation_failed,
119                     NetconfDocumentedException.ErrorSeverity.error);
120         }
121     }
122
123     public void checkNamespace(String expectedNamespace) throws UnexpectedNamespaceException, MissingNameSpaceException {
124         if (!getNamespace().equals(expectedNamespace))
125        {
126             throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s for element %s, should be %s",
127                     getNamespace(),
128                     expectedNamespace),
129                     NetconfDocumentedException.ErrorType.application,
130                     NetconfDocumentedException.ErrorTag.operation_failed,
131                     NetconfDocumentedException.ErrorSeverity.error);
132         }
133     }
134
135     public String getName() {
136         if (element.getLocalName()!=null && !element.getLocalName().equals("")){
137             return element.getLocalName();
138         }
139         return element.getTagName();
140     }
141
142     public String getAttribute(String attributeName) {
143         return element.getAttribute(attributeName);
144     }
145
146     public String getAttribute(String attributeName, String namespace) {
147         return element.getAttributeNS(namespace, attributeName);
148     }
149
150     public NodeList getElementsByTagName(String name) {
151         return element.getElementsByTagName(name);
152     }
153
154     public void appendChild(Element element) {
155         this.element.appendChild(element);
156     }
157
158     public Element getDomElement() {
159         return element;
160     }
161
162     public Map<String, Attr> getAttributes() {
163
164         Map<String, Attr> mappedAttributes = Maps.newHashMap();
165
166         NamedNodeMap attributes = element.getAttributes();
167         for (int i = 0; i < attributes.getLength(); i++) {
168             Attr attr = (Attr) attributes.item(i);
169             mappedAttributes.put(attr.getNodeName(), attr);
170         }
171
172         return mappedAttributes;
173     }
174
175     /**
176      * Non recursive
177      */
178     private List<XmlElement> getChildElementsInternal(ElementFilteringStrategy strat) {
179         NodeList childNodes = element.getChildNodes();
180         final List<XmlElement> result = new ArrayList<>();
181         for (int i = 0; i < childNodes.getLength(); i++) {
182             Node item = childNodes.item(i);
183             if (!(item instanceof Element)) {
184                 continue;
185             }
186             if (strat.accept((Element) item)) {
187                 result.add(new XmlElement((Element) item));
188             }
189         }
190
191         return result;
192     }
193
194     public List<XmlElement> getChildElements() {
195         return getChildElementsInternal(new ElementFilteringStrategy() {
196             @Override
197             public boolean accept(Element e) {
198                 return true;
199             }
200         });
201     }
202
203     public List<XmlElement> getChildElementsWithinNamespace(final String childName, String namespace) {
204         return Lists.newArrayList(Collections2.filter(getChildElementsWithinNamespace(namespace),
205                 new Predicate<XmlElement>() {
206                     @Override
207                     public boolean apply(@Nullable XmlElement xmlElement) {
208                         return xmlElement.getName().equals(childName);
209                     }
210                 }));
211     }
212
213     public List<XmlElement> getChildElementsWithinNamespace(final String namespace) {
214         return getChildElementsInternal(new ElementFilteringStrategy() {
215             @Override
216             public boolean accept(Element e) {
217                 try {
218                     return XmlElement.fromDomElement(e).getNamespace().equals(namespace);
219                 } catch (MissingNameSpaceException e1) {
220                     return false;
221                 }
222             }
223
224         });
225     }
226
227     public List<XmlElement> getChildElements(final String tagName) {
228         return getChildElementsInternal(new ElementFilteringStrategy() {
229             @Override
230             public boolean accept(Element e) {
231                 return e.getTagName().equals(tagName);
232             }
233         });
234     }
235
236     public XmlElement getOnlyChildElement(String childName) throws NetconfDocumentedException {
237         List<XmlElement> nameElements = getChildElements(childName);
238         if (nameElements.size() != 1){
239             throw new NetconfDocumentedException("One element " + childName + " expected in " + toString(),
240                     NetconfDocumentedException.ErrorType.application,
241                     NetconfDocumentedException.ErrorTag.invalid_value,
242                     NetconfDocumentedException.ErrorSeverity.error);
243         }
244         return nameElements.get(0);
245     }
246
247     public Optional<XmlElement> getOnlyChildElementOptionally(String childName) {
248         try {
249             return Optional.of(getOnlyChildElement(childName));
250         } catch (Exception e) {
251             return Optional.absent();
252         }
253     }
254
255     public Optional<XmlElement> getOnlyChildElementOptionally(String childName, String namespace) {
256         try {
257             return Optional.of(getOnlyChildElement(childName, namespace));
258         } catch (Exception e) {
259             return Optional.absent();
260         }
261     }
262
263     public XmlElement getOnlyChildElementWithSameNamespace(String childName) throws  NetconfDocumentedException {
264         return getOnlyChildElement(childName, getNamespace());
265     }
266
267     public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally(String childName) {
268         try {
269             return Optional.of(getOnlyChildElement(childName, getNamespace()));
270         } catch (Exception e) {
271             return Optional.absent();
272         }
273     }
274
275     public XmlElement getOnlyChildElementWithSameNamespace() throws NetconfDocumentedException {
276         XmlElement childElement = getOnlyChildElement();
277         childElement.checkNamespace(getNamespace());
278         return childElement;
279     }
280
281     public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally() {
282         try {
283             XmlElement childElement = getOnlyChildElement();
284             childElement.checkNamespace(getNamespace());
285             return Optional.of(childElement);
286         } catch (Exception e) {
287             return Optional.absent();
288         }
289     }
290
291     public XmlElement getOnlyChildElement(final String childName, String namespace) throws NetconfDocumentedException {
292         List<XmlElement> children = getChildElementsWithinNamespace(namespace);
293         children = Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
294             @Override
295             public boolean apply(@Nullable XmlElement xmlElement) {
296                 return xmlElement.getName().equals(childName);
297             }
298         }));
299         if (children.size() != 1){
300             throw new NetconfDocumentedException(String.format("One element %s:%s expected in %s but was %s", namespace,
301                     childName, toString(), children.size()),
302                     NetconfDocumentedException.ErrorType.application,
303                     NetconfDocumentedException.ErrorTag.invalid_value,
304                     NetconfDocumentedException.ErrorSeverity.error);
305         }
306
307         return children.get(0);
308     }
309
310     public XmlElement getOnlyChildElement() throws NetconfDocumentedException {
311         List<XmlElement> children = getChildElements();
312         if (children.size() != 1){
313             throw new NetconfDocumentedException(String.format( "One element expected in %s but was %s", toString(),
314                     children.size()),
315                     NetconfDocumentedException.ErrorType.application,
316                     NetconfDocumentedException.ErrorTag.invalid_value,
317                     NetconfDocumentedException.ErrorSeverity.error);
318         }
319         return children.get(0);
320     }
321
322     public String getTextContent() throws NetconfDocumentedException {
323         Node textChild = element.getFirstChild();
324         if (null == textChild){
325             throw new NetconfDocumentedException(String.format( "Child node expected, got null for " + getName() + " : " + element),
326                     NetconfDocumentedException.ErrorType.application,
327                     NetconfDocumentedException.ErrorTag.invalid_value,
328                     NetconfDocumentedException.ErrorSeverity.error);
329         }
330         if (!(textChild instanceof Text)){
331             throw new NetconfDocumentedException(String.format(getName() + " should contain text." +
332                     Text.class.getName() + " expected, got " + textChild),
333                     NetconfDocumentedException.ErrorType.application,
334                     NetconfDocumentedException.ErrorTag.invalid_value,
335                     NetconfDocumentedException.ErrorSeverity.error);
336         }
337         String content = textChild.getTextContent();
338         // Trim needed
339         return content.trim();
340     }
341
342     public String getNamespaceAttribute() throws MissingNameSpaceException {
343         String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY);
344         if (attribute == null || attribute.equals("")){
345             throw new MissingNameSpaceException(String.format("Element %s must specify namespace",
346                     toString()),
347                     NetconfDocumentedException.ErrorType.application,
348                     NetconfDocumentedException.ErrorTag.operation_failed,
349                     NetconfDocumentedException.ErrorSeverity.error);
350         }
351         return attribute;
352     }
353
354     public String getNamespace() throws MissingNameSpaceException {
355         String namespaceURI = element.getNamespaceURI();
356         if (namespaceURI  == null || namespaceURI.equals("")){
357             throw new MissingNameSpaceException(String.format("No namespace defined for %s", this),
358                     NetconfDocumentedException.ErrorType.application,
359                     NetconfDocumentedException.ErrorTag.operation_failed,
360                     NetconfDocumentedException.ErrorSeverity.error);
361         }
362         return namespaceURI;
363     }
364
365     @Override
366     public String toString() {
367         final StringBuilder sb = new StringBuilder("XmlElement{");
368         sb.append("name='").append(getName()).append('\'');
369         if (element.getNamespaceURI() != null) {
370             try {
371                 sb.append(", namespace='").append(getNamespace()).append('\'');
372             } catch (MissingNameSpaceException e) {
373                 logger.trace("Missing namespace for element.");
374             }
375         }
376         sb.append('}');
377         return sb.toString();
378     }
379
380     /**
381      * Search for element's attributes defining namespaces. Look for the one
382      * namespace that matches prefix of element's text content. E.g.
383      *
384      * <pre>
385      * &lt;type
386      * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl"&gt;th-java:threadfactory-naming&lt;/type&gt;
387      * </pre>
388      *
389      * returns {"th-java","urn:.."}. If no prefix is matched, then default
390      * namespace is returned with empty string as key. If no default namespace
391      * is found value will be null.
392      */
393     public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() throws NetconfDocumentedException {
394         Map<String, String> namespaces = extractNamespaces(element);
395         String textContent = getTextContent();
396         int indexOfColon = textContent.indexOf(':');
397         String prefix;
398         if (indexOfColon > -1) {
399             prefix = textContent.substring(0, indexOfColon);
400         } else {
401             prefix = "";
402         }
403         if (!namespaces.containsKey(prefix)) {
404             throw new IllegalArgumentException("Cannot find namespace for " + XmlUtil.toString(element) + ". Prefix from content is "
405                     + prefix + ". Found namespaces " + namespaces);
406         }
407         return Maps.immutableEntry(prefix, namespaces.get(prefix));
408     }
409
410     public List<XmlElement> getChildElementsWithSameNamespace(final String childName) throws MissingNameSpaceException {
411         List<XmlElement> children = getChildElementsWithinNamespace(getNamespace());
412         return Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
413             @Override
414             public boolean apply(@Nullable XmlElement xmlElement) {
415                 return xmlElement.getName().equals(childName);
416             }
417         }));
418     }
419
420     public void checkUnrecognisedElements(List<XmlElement> recognisedElements,
421             XmlElement... additionalRecognisedElements) throws NetconfDocumentedException {
422         List<XmlElement> childElements = getChildElements();
423         childElements.removeAll(recognisedElements);
424         for (XmlElement additionalRecognisedElement : additionalRecognisedElements) {
425             childElements.remove(additionalRecognisedElement);
426         }
427         if (!childElements.isEmpty()){
428             throw new NetconfDocumentedException(String.format("Unrecognised elements %s in %s", childElements, this),
429                     NetconfDocumentedException.ErrorType.application,
430                     NetconfDocumentedException.ErrorTag.invalid_value,
431                     NetconfDocumentedException.ErrorSeverity.error);
432         }
433     }
434
435     public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) throws NetconfDocumentedException {
436         checkUnrecognisedElements(Collections.<XmlElement>emptyList(), additionalRecognisedElements);
437     }
438
439     @Override
440     public boolean equals(Object o) {
441         if (this == o) {
442             return true;
443         }
444         if (o == null || getClass() != o.getClass()) {
445             return false;
446         }
447
448         XmlElement that = (XmlElement) o;
449
450         if (!element.isEqualNode(that.element)) {
451             return false;
452         }
453
454         return true;
455     }
456
457     @Override
458     public int hashCode() {
459         return element.hashCode();
460     }
461
462     public boolean hasNamespace() {
463         try {
464             getNamespaceAttribute();
465         } catch (MissingNameSpaceException e) {
466             try {
467                 getNamespace();
468             } catch (MissingNameSpaceException e1) {
469                 return false;
470             }
471             return true;
472         }
473         return true;
474     }
475
476     private interface ElementFilteringStrategy {
477         boolean accept(Element e);
478     }
479 }