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.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;
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;
38 public final class XmlElement {
40 public static final String DEFAULT_NAMESPACE_PREFIX = "";
42 private final Element element;
43 private static final Logger LOG = LoggerFactory.getLogger(XmlElement.class);
45 private XmlElement(Element element) {
46 this.element = element;
49 public static XmlElement fromDomElement(Element e) {
50 return new XmlElement(e);
53 public static XmlElement fromDomDocument(Document xml) {
54 return new XmlElement(xml.getDocumentElement());
57 public static XmlElement fromString(String s) throws NetconfDocumentedException {
59 return new XmlElement(XmlUtil.readXmlToElement(s));
60 } catch (IOException | SAXException e) {
61 throw NetconfDocumentedException.wrap(e);
65 public static XmlElement fromDomElementWithExpected(Element element, String expectedName) throws NetconfDocumentedException {
66 XmlElement xmlElement = XmlElement.fromDomElement(element);
67 xmlElement.checkName(expectedName);
71 public static XmlElement fromDomElementWithExpected(Element element, String expectedName, String expectedNamespace) throws NetconfDocumentedException {
72 XmlElement xmlElement = XmlElement.fromDomElementWithExpected(element, expectedName);
73 xmlElement.checkNamespace(expectedNamespace);
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)) {
85 if (attribKey.equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
86 prefix = DEFAULT_NAMESPACE_PREFIX;
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);
94 prefix = attribKey.substring(XmlUtil.XMLNS_ATTRIBUTE_KEY.length() + 1);
96 namespaces.put(prefix, attribute.getNodeValue());
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());
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,
115 NetconfDocumentedException.ErrorType.application,
116 NetconfDocumentedException.ErrorTag.operation_failed,
117 NetconfDocumentedException.ErrorSeverity.error);
121 public void checkNamespaceAttribute(String expectedNamespace) throws UnexpectedNamespaceException, MissingNameSpaceException {
122 if (!getNamespaceAttribute().equals(expectedNamespace))
124 throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s should be %s",
125 getNamespaceAttribute(),
127 NetconfDocumentedException.ErrorType.application,
128 NetconfDocumentedException.ErrorTag.operation_failed,
129 NetconfDocumentedException.ErrorSeverity.error);
133 public void checkNamespace(String expectedNamespace) throws UnexpectedNamespaceException, MissingNameSpaceException {
134 if (!getNamespace().equals(expectedNamespace))
136 throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s should be %s",
139 NetconfDocumentedException.ErrorType.application,
140 NetconfDocumentedException.ErrorTag.operation_failed,
141 NetconfDocumentedException.ErrorSeverity.error);
145 public String getName() {
146 final String localName = element.getLocalName();
147 if (!Strings.isNullOrEmpty(localName)){
150 return element.getTagName();
153 public String getAttribute(String attributeName) {
154 return element.getAttribute(attributeName);
157 public String getAttribute(String attributeName, String namespace) {
158 return element.getAttributeNS(namespace, attributeName);
161 public NodeList getElementsByTagName(String name) {
162 return element.getElementsByTagName(name);
165 public void appendChild(Element element) {
166 this.element.appendChild(element);
169 public Element getDomElement() {
173 public Map<String, Attr> getAttributes() {
175 Map<String, Attr> mappedAttributes = Maps.newHashMap();
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);
183 return mappedAttributes;
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)) {
197 if (strat.accept((Element) item)) {
198 result.add(new XmlElement((Element) item));
205 public List<XmlElement> getChildElements() {
206 return getChildElementsInternal(new ElementFilteringStrategy() {
208 public boolean accept(Element e) {
214 public List<XmlElement> getChildElementsWithinNamespace(final String childName, String namespace) {
215 return Lists.newArrayList(Collections2.filter(getChildElementsWithinNamespace(namespace),
216 new Predicate<XmlElement>() {
218 public boolean apply(XmlElement xmlElement) {
219 return xmlElement.getName().equals(childName);
224 public List<XmlElement> getChildElementsWithinNamespace(final String namespace) {
225 return getChildElementsInternal(new ElementFilteringStrategy() {
227 public boolean accept(Element e) {
229 return XmlElement.fromDomElement(e).getNamespace().equals(namespace);
230 } catch (MissingNameSpaceException e1) {
240 * @param tagName tag name without prefix
241 * @return List of child elements
243 public List<XmlElement> getChildElements(final String tagName) {
244 return getChildElementsInternal(new ElementFilteringStrategy() {
246 public boolean accept(Element e) {
247 // localName returns pure localName without prefix
248 return e.getLocalName().equals(tagName);
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);
261 return nameElements.get(0);
264 public Optional<XmlElement> getOnlyChildElementOptionally(String childName) {
265 List<XmlElement> nameElements = getChildElements(childName);
266 if (nameElements.size() != 1) {
267 return Optional.absent();
269 return Optional.of(nameElements.get(0));
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>() {
276 public boolean apply(XmlElement xmlElement) {
277 return xmlElement.getName().equals(childName);
280 if (children.size() != 1){
281 return Optional.absent();
283 return Optional.of(children.get(0));
286 public XmlElement getOnlyChildElementWithSameNamespace(String childName) throws NetconfDocumentedException {
287 return getOnlyChildElement(childName, getNamespace());
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>() {
296 public boolean apply(XmlElement xmlElement) {
297 return xmlElement.getName().equals(childName);
300 if (children.size() != 1){
301 return Optional.absent();
303 return Optional.of(children.get(0));
305 return Optional.absent();
308 public XmlElement getOnlyChildElementWithSameNamespace() throws NetconfDocumentedException {
309 XmlElement childElement = getOnlyChildElement();
310 childElement.checkNamespace(getNamespace());
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())) {
322 return Optional.absent();
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>() {
329 public boolean apply(XmlElement xmlElement) {
330 return xmlElement.getName().equals(childName);
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);
341 return children.get(0);
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(),
349 NetconfDocumentedException.ErrorType.application,
350 NetconfDocumentedException.ErrorTag.invalid_value,
351 NetconfDocumentedException.ErrorSeverity.error);
353 return children.get(0);
356 public Optional<XmlElement> getOnlyChildElementOptionally() {
357 List<XmlElement> children = getChildElements();
358 if (children.size() != 1) {
359 return Optional.absent();
361 return Optional.of(children.get(0));
364 public String getTextContent() throws NetconfDocumentedException {
365 NodeList childNodes = element.getChildNodes();
366 if (childNodes.getLength() == 0) {
367 return DEFAULT_NAMESPACE_PREFIX;
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();
376 throw new NetconfDocumentedException(getName() + " should contain text.",
377 NetconfDocumentedException.ErrorType.application,
378 NetconfDocumentedException.ErrorTag.invalid_value,
379 NetconfDocumentedException.ErrorSeverity.error
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());
391 return Optional.absent();
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",
399 NetconfDocumentedException.ErrorType.application,
400 NetconfDocumentedException.ErrorTag.operation_failed,
401 NetconfDocumentedException.ErrorSeverity.error);
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();
411 return Optional.of(attribute);
414 public Optional<String> getNamespaceOptionally() {
415 String namespaceURI = element.getNamespaceURI();
416 if (Strings.isNullOrEmpty(namespaceURI)) {
417 return Optional.absent();
419 return Optional.of(namespaceURI);
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);
431 return namespaceURI.get();
435 public String toString() {
436 final StringBuilder sb = new StringBuilder("XmlElement{");
437 sb.append("name='").append(getName()).append('\'');
438 if (element.getNamespaceURI() != null) {
440 sb.append(", namespace='").append(getNamespace()).append('\'');
441 } catch (MissingNameSpaceException e) {
442 LOG.trace("Missing namespace for element.");
446 return sb.toString();
450 * Search for element's attributes defining namespaces. Look for the one
451 * namespace that matches prefix of element's text content. E.g.
455 * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">th-java:threadfactory-naming</type>
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.
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(':');
467 if (indexOfColon > -1) {
468 prefix = textContent.substring(0, indexOfColon);
470 prefix = DEFAULT_NAMESPACE_PREFIX;
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);
476 return Maps.immutableEntry(prefix, namespaces.get(prefix));
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>() {
483 public boolean apply(XmlElement xmlElement) {
484 return xmlElement.getName().equals(childName);
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);
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);
504 public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) throws NetconfDocumentedException {
505 checkUnrecognisedElements(Collections.<XmlElement>emptyList(), additionalRecognisedElements);
509 public boolean equals(Object o) {
513 if (o == null || getClass() != o.getClass()) {
517 XmlElement that = (XmlElement) o;
519 return element.isEqualNode(that.element);
524 public int hashCode() {
525 return element.hashCode();
528 public boolean hasNamespace() {
529 if (!getNamespaceAttributeOptionally().isPresent()) {
530 if (!getNamespaceOptionally().isPresent()) {
537 private interface ElementFilteringStrategy {
538 boolean accept(Element e);