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 javax.annotation.Nullable;
24 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
25 import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
26 import org.opendaylight.controller.netconf.util.exception.UnexpectedElementException;
27 import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.w3c.dom.Attr;
31 import org.w3c.dom.Document;
32 import org.w3c.dom.Element;
33 import org.w3c.dom.NamedNodeMap;
34 import org.w3c.dom.Node;
35 import org.w3c.dom.NodeList;
36 import org.w3c.dom.Text;
37 import org.xml.sax.SAXException;
39 public final class XmlElement {
41 private final Element element;
42 private static final Logger logger = LoggerFactory.getLogger(XmlElement.class);
44 private XmlElement(Element element) {
45 this.element = element;
48 public static XmlElement fromDomElement(Element e) {
49 return new XmlElement(e);
52 public static XmlElement fromDomDocument(Document xml) {
53 return new XmlElement(xml.getDocumentElement());
56 public static XmlElement fromString(String s) throws NetconfDocumentedException {
58 return new XmlElement(XmlUtil.readXmlToElement(s));
59 } catch (IOException | SAXException e) {
60 throw NetconfDocumentedException.wrap(e);
64 public static XmlElement fromDomElementWithExpected(Element element, String expectedName) throws NetconfDocumentedException {
65 XmlElement xmlElement = XmlElement.fromDomElement(element);
66 xmlElement.checkName(expectedName);
70 public static XmlElement fromDomElementWithExpected(Element element, String expectedName, String expectedNamespace) throws NetconfDocumentedException {
71 XmlElement xmlElement = XmlElement.fromDomElementWithExpected(element, expectedName);
72 xmlElement.checkNamespace(expectedNamespace);
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)) {
84 if (attribKey.equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
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);
93 prefix = attribKey.substring(XmlUtil.XMLNS_ATTRIBUTE_KEY.length() + 1);
95 namespaces.put(prefix, attribute.getNodeValue());
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,
105 NetconfDocumentedException.ErrorType.application,
106 NetconfDocumentedException.ErrorTag.operation_failed,
107 NetconfDocumentedException.ErrorSeverity.error);
111 public void checkNamespaceAttribute(String expectedNamespace) throws UnexpectedNamespaceException, MissingNameSpaceException {
112 if (!getNamespaceAttribute().equals(expectedNamespace))
114 throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s should be %s",
115 getNamespaceAttribute(),
117 NetconfDocumentedException.ErrorType.application,
118 NetconfDocumentedException.ErrorTag.operation_failed,
119 NetconfDocumentedException.ErrorSeverity.error);
123 public void checkNamespace(String expectedNamespace) throws UnexpectedNamespaceException, MissingNameSpaceException {
124 if (!getNamespace().equals(expectedNamespace))
126 throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s should be %s",
129 NetconfDocumentedException.ErrorType.application,
130 NetconfDocumentedException.ErrorTag.operation_failed,
131 NetconfDocumentedException.ErrorSeverity.error);
135 public String getName() {
136 if (element.getLocalName()!=null && !element.getLocalName().equals("")){
137 return element.getLocalName();
139 return element.getTagName();
142 public String getAttribute(String attributeName) {
143 return element.getAttribute(attributeName);
146 public String getAttribute(String attributeName, String namespace) {
147 return element.getAttributeNS(namespace, attributeName);
150 public NodeList getElementsByTagName(String name) {
151 return element.getElementsByTagName(name);
154 public void appendChild(Element element) {
155 this.element.appendChild(element);
158 public Element getDomElement() {
162 public Map<String, Attr> getAttributes() {
164 Map<String, Attr> mappedAttributes = Maps.newHashMap();
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);
172 return mappedAttributes;
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)) {
186 if (strat.accept((Element) item)) {
187 result.add(new XmlElement((Element) item));
194 public List<XmlElement> getChildElements() {
195 return getChildElementsInternal(new ElementFilteringStrategy() {
197 public boolean accept(Element e) {
203 public List<XmlElement> getChildElementsWithinNamespace(final String childName, String namespace) {
204 return Lists.newArrayList(Collections2.filter(getChildElementsWithinNamespace(namespace),
205 new Predicate<XmlElement>() {
207 public boolean apply(@Nullable XmlElement xmlElement) {
208 return xmlElement.getName().equals(childName);
213 public List<XmlElement> getChildElementsWithinNamespace(final String namespace) {
214 return getChildElementsInternal(new ElementFilteringStrategy() {
216 public boolean accept(Element e) {
218 return XmlElement.fromDomElement(e).getNamespace().equals(namespace);
219 } catch (MissingNameSpaceException e1) {
227 public List<XmlElement> getChildElements(final String tagName) {
228 return getChildElementsInternal(new ElementFilteringStrategy() {
230 public boolean accept(Element e) {
231 return e.getTagName().equals(tagName);
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);
244 return nameElements.get(0);
247 public Optional<XmlElement> getOnlyChildElementOptionally(String childName) {
249 return Optional.of(getOnlyChildElement(childName));
250 } catch (Exception e) {
251 return Optional.absent();
255 public Optional<XmlElement> getOnlyChildElementOptionally(String childName, String namespace) {
257 return Optional.of(getOnlyChildElement(childName, namespace));
258 } catch (Exception e) {
259 return Optional.absent();
263 public XmlElement getOnlyChildElementWithSameNamespace(String childName) throws NetconfDocumentedException {
264 return getOnlyChildElement(childName, getNamespace());
267 public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally(String childName) {
269 return Optional.of(getOnlyChildElement(childName, getNamespace()));
270 } catch (Exception e) {
271 return Optional.absent();
275 public XmlElement getOnlyChildElementWithSameNamespace() throws NetconfDocumentedException {
276 XmlElement childElement = getOnlyChildElement();
277 childElement.checkNamespace(getNamespace());
281 public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally() {
283 XmlElement childElement = getOnlyChildElement();
284 childElement.checkNamespace(getNamespace());
285 return Optional.of(childElement);
286 } catch (Exception e) {
287 return Optional.absent();
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>() {
295 public boolean apply(@Nullable XmlElement xmlElement) {
296 return xmlElement.getName().equals(childName);
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);
307 return children.get(0);
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(),
315 NetconfDocumentedException.ErrorType.application,
316 NetconfDocumentedException.ErrorTag.invalid_value,
317 NetconfDocumentedException.ErrorSeverity.error);
319 return children.get(0);
322 public String getTextContent() throws NetconfDocumentedException {
323 NodeList childNodes = element.getChildNodes();
324 if (childNodes.getLength() == 0) {
327 for(int i = 0; i < childNodes.getLength(); i++) {
328 Node textChild = childNodes.item(i);
329 if (textChild instanceof Text) {
330 String content = textChild.getTextContent();
331 return content.trim();
334 throw new NetconfDocumentedException(getName() + " should contain text.",
335 NetconfDocumentedException.ErrorType.application,
336 NetconfDocumentedException.ErrorTag.invalid_value,
337 NetconfDocumentedException.ErrorSeverity.error
341 public Optional<String> getOnlyTextContentOptionally() {
342 // only return text content if this node has exactly one Text child node
343 if (element.getChildNodes().getLength() == 1) {
344 Node item = element.getChildNodes().item(0);
345 if (item instanceof Text) {
346 return Optional.of(((Text) item).getWholeText());
349 return Optional.absent();
352 public String getNamespaceAttribute() throws MissingNameSpaceException {
353 String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY);
354 if (attribute == null || attribute.equals("")){
355 throw new MissingNameSpaceException(String.format("Element %s must specify namespace",
357 NetconfDocumentedException.ErrorType.application,
358 NetconfDocumentedException.ErrorTag.operation_failed,
359 NetconfDocumentedException.ErrorSeverity.error);
364 public Optional<String> getNamespaceOptionally() {
365 String namespaceURI = element.getNamespaceURI();
366 if (Strings.isNullOrEmpty(namespaceURI)) {
367 return Optional.absent();
369 return Optional.of(namespaceURI);
373 public String getNamespace() throws MissingNameSpaceException {
374 Optional<String> namespaceURI = getNamespaceOptionally();
375 if (namespaceURI.isPresent() == false){
376 throw new MissingNameSpaceException(String.format("No namespace defined for %s", this),
377 NetconfDocumentedException.ErrorType.application,
378 NetconfDocumentedException.ErrorTag.operation_failed,
379 NetconfDocumentedException.ErrorSeverity.error);
381 return namespaceURI.get();
385 public String toString() {
386 final StringBuilder sb = new StringBuilder("XmlElement{");
387 sb.append("name='").append(getName()).append('\'');
388 if (element.getNamespaceURI() != null) {
390 sb.append(", namespace='").append(getNamespace()).append('\'');
391 } catch (MissingNameSpaceException e) {
392 logger.trace("Missing namespace for element.");
396 return sb.toString();
400 * Search for element's attributes defining namespaces. Look for the one
401 * namespace that matches prefix of element's text content. E.g.
405 * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">th-java:threadfactory-naming</type>
408 * returns {"th-java","urn:.."}. If no prefix is matched, then default
409 * namespace is returned with empty string as key. If no default namespace
410 * is found value will be null.
412 public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() throws NetconfDocumentedException {
413 Map<String, String> namespaces = extractNamespaces(element);
414 String textContent = getTextContent();
415 int indexOfColon = textContent.indexOf(':');
417 if (indexOfColon > -1) {
418 prefix = textContent.substring(0, indexOfColon);
422 if (!namespaces.containsKey(prefix)) {
423 throw new IllegalArgumentException("Cannot find namespace for " + XmlUtil.toString(element) + ". Prefix from content is "
424 + prefix + ". Found namespaces " + namespaces);
426 return Maps.immutableEntry(prefix, namespaces.get(prefix));
429 public List<XmlElement> getChildElementsWithSameNamespace(final String childName) throws MissingNameSpaceException {
430 List<XmlElement> children = getChildElementsWithinNamespace(getNamespace());
431 return Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
433 public boolean apply(@Nullable XmlElement xmlElement) {
434 return xmlElement.getName().equals(childName);
439 public void checkUnrecognisedElements(List<XmlElement> recognisedElements,
440 XmlElement... additionalRecognisedElements) throws NetconfDocumentedException {
441 List<XmlElement> childElements = getChildElements();
442 childElements.removeAll(recognisedElements);
443 for (XmlElement additionalRecognisedElement : additionalRecognisedElements) {
444 childElements.remove(additionalRecognisedElement);
446 if (!childElements.isEmpty()){
447 throw new NetconfDocumentedException(String.format("Unrecognised elements %s in %s", childElements, this),
448 NetconfDocumentedException.ErrorType.application,
449 NetconfDocumentedException.ErrorTag.invalid_value,
450 NetconfDocumentedException.ErrorSeverity.error);
454 public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) throws NetconfDocumentedException {
455 checkUnrecognisedElements(Collections.<XmlElement>emptyList(), additionalRecognisedElements);
459 public boolean equals(Object o) {
463 if (o == null || getClass() != o.getClass()) {
467 XmlElement that = (XmlElement) o;
469 if (!element.isEqualNode(that.element)) {
477 public int hashCode() {
478 return element.hashCode();
481 public boolean hasNamespace() {
483 getNamespaceAttribute();
484 } catch (MissingNameSpaceException e) {
487 } catch (MissingNameSpaceException e1) {
495 private interface ElementFilteringStrategy {
496 boolean accept(Element e);