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 if (element.getLocalName()!=null && !element.getLocalName().equals(DEFAULT_NAMESPACE_PREFIX)){
147 return element.getLocalName();
149 return element.getTagName();
152 public String getAttribute(String attributeName) {
153 return element.getAttribute(attributeName);
156 public String getAttribute(String attributeName, String namespace) {
157 return element.getAttributeNS(namespace, attributeName);
160 public NodeList getElementsByTagName(String name) {
161 return element.getElementsByTagName(name);
164 public void appendChild(Element element) {
165 this.element.appendChild(element);
168 public Element getDomElement() {
172 public Map<String, Attr> getAttributes() {
174 Map<String, Attr> mappedAttributes = Maps.newHashMap();
176 NamedNodeMap attributes = element.getAttributes();
177 for (int i = 0; i < attributes.getLength(); i++) {
178 Attr attr = (Attr) attributes.item(i);
179 mappedAttributes.put(attr.getNodeName(), attr);
182 return mappedAttributes;
188 private List<XmlElement> getChildElementsInternal(ElementFilteringStrategy strat) {
189 NodeList childNodes = element.getChildNodes();
190 final List<XmlElement> result = new ArrayList<>();
191 for (int i = 0; i < childNodes.getLength(); i++) {
192 Node item = childNodes.item(i);
193 if (!(item instanceof Element)) {
196 if (strat.accept((Element) item)) {
197 result.add(new XmlElement((Element) item));
204 public List<XmlElement> getChildElements() {
205 return getChildElementsInternal(new ElementFilteringStrategy() {
207 public boolean accept(Element e) {
213 public List<XmlElement> getChildElementsWithinNamespace(final String childName, String namespace) {
214 return Lists.newArrayList(Collections2.filter(getChildElementsWithinNamespace(namespace),
215 new Predicate<XmlElement>() {
217 public boolean apply(XmlElement xmlElement) {
218 return xmlElement.getName().equals(childName);
223 public List<XmlElement> getChildElementsWithinNamespace(final String namespace) {
224 return getChildElementsInternal(new ElementFilteringStrategy() {
226 public boolean accept(Element e) {
228 return XmlElement.fromDomElement(e).getNamespace().equals(namespace);
229 } catch (MissingNameSpaceException e1) {
239 * @param tagName tag name without prefix
242 public List<XmlElement> getChildElements(final String tagName) {
243 return getChildElementsInternal(new ElementFilteringStrategy() {
245 public boolean accept(Element e) {
246 // localName returns pure localName without prefix
247 return e.getLocalName().equals(tagName);
252 public XmlElement getOnlyChildElement(String childName) throws NetconfDocumentedException {
253 List<XmlElement> nameElements = getChildElements(childName);
254 if (nameElements.size() != 1){
255 throw new NetconfDocumentedException("One element " + childName + " expected in " + toString(),
256 NetconfDocumentedException.ErrorType.application,
257 NetconfDocumentedException.ErrorTag.invalid_value,
258 NetconfDocumentedException.ErrorSeverity.error);
260 return nameElements.get(0);
263 public Optional<XmlElement> getOnlyChildElementOptionally(String childName) {
265 return Optional.of(getOnlyChildElement(childName));
266 } catch (Exception e) {
267 return Optional.absent();
271 public Optional<XmlElement> getOnlyChildElementOptionally(String childName, String namespace) {
273 return Optional.of(getOnlyChildElement(childName, namespace));
274 } catch (Exception e) {
275 return Optional.absent();
279 public XmlElement getOnlyChildElementWithSameNamespace(String childName) throws NetconfDocumentedException {
280 return getOnlyChildElement(childName, getNamespace());
283 public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally(String childName) {
285 return Optional.of(getOnlyChildElement(childName, getNamespace()));
286 } catch (Exception e) {
287 return Optional.absent();
291 public XmlElement getOnlyChildElementWithSameNamespace() throws NetconfDocumentedException {
292 XmlElement childElement = getOnlyChildElement();
293 childElement.checkNamespace(getNamespace());
297 public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally() {
299 XmlElement childElement = getOnlyChildElement();
300 childElement.checkNamespace(getNamespace());
301 return Optional.of(childElement);
302 } catch (Exception e) {
303 return Optional.absent();
307 public XmlElement getOnlyChildElement(final String childName, String namespace) throws NetconfDocumentedException {
308 List<XmlElement> children = getChildElementsWithinNamespace(namespace);
309 children = Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
311 public boolean apply(XmlElement xmlElement) {
312 return xmlElement.getName().equals(childName);
315 if (children.size() != 1){
316 throw new NetconfDocumentedException(String.format("One element %s:%s expected in %s but was %s", namespace,
317 childName, toString(), children.size()),
318 NetconfDocumentedException.ErrorType.application,
319 NetconfDocumentedException.ErrorTag.invalid_value,
320 NetconfDocumentedException.ErrorSeverity.error);
323 return children.get(0);
326 public XmlElement getOnlyChildElement() throws NetconfDocumentedException {
327 List<XmlElement> children = getChildElements();
328 if (children.size() != 1){
329 throw new NetconfDocumentedException(String.format( "One element expected in %s but was %s", toString(),
331 NetconfDocumentedException.ErrorType.application,
332 NetconfDocumentedException.ErrorTag.invalid_value,
333 NetconfDocumentedException.ErrorSeverity.error);
335 return children.get(0);
338 public String getTextContent() throws NetconfDocumentedException {
339 NodeList childNodes = element.getChildNodes();
340 if (childNodes.getLength() == 0) {
341 return DEFAULT_NAMESPACE_PREFIX;
343 for(int i = 0; i < childNodes.getLength(); i++) {
344 Node textChild = childNodes.item(i);
345 if (textChild instanceof Text) {
346 String content = textChild.getTextContent();
347 return content.trim();
350 throw new NetconfDocumentedException(getName() + " should contain text.",
351 NetconfDocumentedException.ErrorType.application,
352 NetconfDocumentedException.ErrorTag.invalid_value,
353 NetconfDocumentedException.ErrorSeverity.error
357 public Optional<String> getOnlyTextContentOptionally() {
358 // only return text content if this node has exactly one Text child node
359 if (element.getChildNodes().getLength() == 1) {
360 Node item = element.getChildNodes().item(0);
361 if (item instanceof Text) {
362 return Optional.of(((Text) item).getWholeText());
365 return Optional.absent();
368 public String getNamespaceAttribute() throws MissingNameSpaceException {
369 String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY);
370 if (attribute == null || attribute.equals(DEFAULT_NAMESPACE_PREFIX)){
371 throw new MissingNameSpaceException(String.format("Element %s must specify namespace",
373 NetconfDocumentedException.ErrorType.application,
374 NetconfDocumentedException.ErrorTag.operation_failed,
375 NetconfDocumentedException.ErrorSeverity.error);
380 public Optional<String> getNamespaceOptionally() {
381 String namespaceURI = element.getNamespaceURI();
382 if (Strings.isNullOrEmpty(namespaceURI)) {
383 return Optional.absent();
385 return Optional.of(namespaceURI);
389 public String getNamespace() throws MissingNameSpaceException {
390 Optional<String> namespaceURI = getNamespaceOptionally();
391 if (namespaceURI.isPresent() == false){
392 throw new MissingNameSpaceException(String.format("No namespace defined for %s", this),
393 NetconfDocumentedException.ErrorType.application,
394 NetconfDocumentedException.ErrorTag.operation_failed,
395 NetconfDocumentedException.ErrorSeverity.error);
397 return namespaceURI.get();
401 public String toString() {
402 final StringBuilder sb = new StringBuilder("XmlElement{");
403 sb.append("name='").append(getName()).append('\'');
404 if (element.getNamespaceURI() != null) {
406 sb.append(", namespace='").append(getNamespace()).append('\'');
407 } catch (MissingNameSpaceException e) {
408 LOG.trace("Missing namespace for element.");
412 return sb.toString();
416 * Search for element's attributes defining namespaces. Look for the one
417 * namespace that matches prefix of element's text content. E.g.
421 * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">th-java:threadfactory-naming</type>
424 * returns {"th-java","urn:.."}. If no prefix is matched, then default
425 * namespace is returned with empty string as key. If no default namespace
426 * is found value will be null.
428 public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() throws NetconfDocumentedException {
429 Map<String, String> namespaces = extractNamespaces();
430 String textContent = getTextContent();
431 int indexOfColon = textContent.indexOf(':');
433 if (indexOfColon > -1) {
434 prefix = textContent.substring(0, indexOfColon);
436 prefix = DEFAULT_NAMESPACE_PREFIX;
438 if (!namespaces.containsKey(prefix)) {
439 throw new IllegalArgumentException("Cannot find namespace for " + XmlUtil.toString(element) + ". Prefix from content is "
440 + prefix + ". Found namespaces " + namespaces);
442 return Maps.immutableEntry(prefix, namespaces.get(prefix));
445 public List<XmlElement> getChildElementsWithSameNamespace(final String childName) throws MissingNameSpaceException {
446 List<XmlElement> children = getChildElementsWithinNamespace(getNamespace());
447 return Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
449 public boolean apply(XmlElement xmlElement) {
450 return xmlElement.getName().equals(childName);
455 public void checkUnrecognisedElements(List<XmlElement> recognisedElements,
456 XmlElement... additionalRecognisedElements) throws NetconfDocumentedException {
457 List<XmlElement> childElements = getChildElements();
458 childElements.removeAll(recognisedElements);
459 for (XmlElement additionalRecognisedElement : additionalRecognisedElements) {
460 childElements.remove(additionalRecognisedElement);
462 if (!childElements.isEmpty()){
463 throw new NetconfDocumentedException(String.format("Unrecognised elements %s in %s", childElements, this),
464 NetconfDocumentedException.ErrorType.application,
465 NetconfDocumentedException.ErrorTag.invalid_value,
466 NetconfDocumentedException.ErrorSeverity.error);
470 public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) throws NetconfDocumentedException {
471 checkUnrecognisedElements(Collections.<XmlElement>emptyList(), additionalRecognisedElements);
475 public boolean equals(Object o) {
479 if (o == null || getClass() != o.getClass()) {
483 XmlElement that = (XmlElement) o;
485 if (!element.isEqualNode(that.element)) {
493 public int hashCode() {
494 return element.hashCode();
497 public boolean hasNamespace() {
499 getNamespaceAttribute();
500 } catch (MissingNameSpaceException e) {
503 } catch (MissingNameSpaceException e1) {
511 private interface ElementFilteringStrategy {
512 boolean accept(Element e);