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