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.Preconditions;
13 import com.google.common.base.Predicate;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Maps;
17 import org.w3c.dom.Attr;
18 import org.w3c.dom.Document;
19 import org.w3c.dom.Element;
20 import org.w3c.dom.NamedNodeMap;
21 import org.w3c.dom.Node;
22 import org.w3c.dom.NodeList;
23 import org.w3c.dom.Text;
24 import org.xml.sax.SAXException;
26 import javax.annotation.Nullable;
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.List;
34 public class XmlElement {
36 public final Element element;
38 private XmlElement(Element element) {
39 this.element = element;
42 public static XmlElement fromDomElement(Element e) {
43 return new XmlElement(e);
46 public static XmlElement fromDomDocument(Document xml) {
47 return new XmlElement(xml.getDocumentElement());
50 public static XmlElement fromString(String s) {
52 return new XmlElement(XmlUtil.readXmlToElement(s));
53 } catch (IOException | SAXException e) {
54 throw new IllegalArgumentException("Unable to create from " + s, e);
58 public static XmlElement fromDomElementWithExpected(Element element, String expectedName) {
59 XmlElement xmlElement = XmlElement.fromDomElement(element);
60 xmlElement.checkName(expectedName);
64 public static XmlElement fromDomElementWithExpected(Element element, String expectedName, String expectedNamespace) {
65 XmlElement xmlElement = XmlElement.fromDomElementWithExpected(element, expectedName);
66 xmlElement.checkNamespace(expectedNamespace);
70 private static Map<String, String> extractNamespaces(Element typeElement) {
71 Map<String, String> namespaces = new HashMap<>();
72 NamedNodeMap attributes = typeElement.getAttributes();
73 for (int i = 0; i < attributes.getLength(); i++) {
74 Node attribute = attributes.item(i);
75 String attribKey = attribute.getNodeName();
76 if (attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
78 if (attribKey.equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
81 Preconditions.checkState(attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY + ":"));
82 prefix = attribKey.substring(XmlUtil.XMLNS_ATTRIBUTE_KEY.length() + 1);
84 namespaces.put(prefix, attribute.getNodeValue());
90 public void checkName(String expectedName) {
91 Preconditions.checkArgument(getName().equals(expectedName), "Expected %s xml element but was %s", expectedName,
95 public void checkNamespaceAttribute(String expectedNamespace) {
96 Preconditions.checkArgument(getNamespaceAttribute().equals(expectedNamespace),
97 "Unexpected namespace %s for element %s, should be %s", getNamespaceAttribute(), expectedNamespace);
100 public void checkNamespace(String expectedNamespace) {
101 Preconditions.checkArgument(getNamespace().equals(expectedNamespace),
102 "Unexpected namespace %s for element %s, should be %s", getNamespace(), expectedNamespace);
105 public String getName() {
106 return element.getTagName();
109 public String getAttribute(String attributeName) {
110 return element.getAttribute(attributeName);
113 public String getAttribute(String attributeName, String namespace) {
114 return element.getAttributeNS(namespace, attributeName);
117 public void appendChild(Element element) {
118 this.element.appendChild(element);
119 // Element newElement = (Element) element.cloneNode(true);
120 // newElement.appendChild(configElement);
121 // return XmlElement.fromDomElement(newElement);
124 public Element getDomElement() {
128 public Map<String, Attr> getAttributes() {
130 Map<String, Attr> mappedAttributes = Maps.newHashMap();
132 NamedNodeMap attributes = element.getAttributes();
133 for (int i = 0; i < attributes.getLength(); i++) {
134 Attr attr = (Attr) attributes.item(i);
135 mappedAttributes.put(attr.getNodeName(), attr);
138 return mappedAttributes;
144 private List<XmlElement> getChildElementsInternal(ElementFilteringStrategy strat) {
145 NodeList childNodes = element.getChildNodes();
146 final List<XmlElement> result = new ArrayList<>();
147 for (int i = 0; i < childNodes.getLength(); i++) {
148 Node item = childNodes.item(i);
149 if (item instanceof Element == false)
151 if (strat.accept((Element) item))
152 result.add(new XmlElement((Element) item));
158 public List<XmlElement> getChildElements() {
159 return getChildElementsInternal(new ElementFilteringStrategy() {
161 public boolean accept(Element e) {
167 public List<XmlElement> getChildElementsWithinNamespace(final String childName, String namespace) {
168 return Lists.newArrayList(Collections2.filter(getChildElementsWithinNamespace(namespace),
169 new Predicate<XmlElement>() {
171 public boolean apply(@Nullable XmlElement xmlElement) {
172 return xmlElement.getName().equals(childName);
177 public List<XmlElement> getChildElementsWithinNamespace(final String namespace) {
178 return getChildElementsInternal(new ElementFilteringStrategy() {
180 public boolean accept(Element e) {
181 return XmlElement.fromDomElement(e).getNamespace().equals(namespace);
187 public List<XmlElement> getChildElements(final String tagName) {
188 return getChildElementsInternal(new ElementFilteringStrategy() {
190 public boolean accept(Element e) {
191 return e.getTagName().equals(tagName);
196 public XmlElement getOnlyChildElement(String childName) {
197 List<XmlElement> nameElements = getChildElements(childName);
198 Preconditions.checkState(nameElements.size() == 1, "One element " + childName + " expected in " + toString());
199 return nameElements.get(0);
202 public Optional<XmlElement> getOnlyChildElementOptionally(String childName) {
204 return Optional.of(getOnlyChildElement(childName));
205 } catch (Exception e) {
206 return Optional.absent();
210 public Optional<XmlElement> getOnlyChildElementOptionally(String childName, String namespace) {
212 return Optional.of(getOnlyChildElement(childName, namespace));
213 } catch (Exception e) {
214 return Optional.absent();
218 public XmlElement getOnlyChildElementWithSameNamespace(String childName) {
219 return getOnlyChildElement(childName, getNamespace());
222 public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally(String childName) {
224 return Optional.of(getOnlyChildElement(childName, getNamespace()));
225 } catch (Exception e) {
226 return Optional.absent();
230 public XmlElement getOnlyChildElementWithSameNamespace() {
231 XmlElement childElement = getOnlyChildElement();
232 childElement.checkNamespace(getNamespace());
236 public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally() {
238 XmlElement childElement = getOnlyChildElement();
239 childElement.checkNamespace(getNamespace());
240 return Optional.of(childElement);
241 } catch (Exception e) {
242 return Optional.absent();
246 public XmlElement getOnlyChildElement(final String childName, String namespace) {
247 List<XmlElement> children = getChildElementsWithinNamespace(namespace);
248 children = Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
250 public boolean apply(@Nullable XmlElement xmlElement) {
251 return xmlElement.getName().equals(childName);
254 Preconditions.checkState(children.size() == 1, "One element %s:%s expected in %s but was %s", namespace,
255 childName, toString(), children.size());
256 return children.get(0);
259 public XmlElement getOnlyChildElement() {
260 List<XmlElement> children = getChildElements();
261 Preconditions.checkState(children.size() == 1, "One element expected in %s but was %s", toString(),
263 return children.get(0);
266 public String getTextContent() {
267 Node textChild = element.getFirstChild();
268 Preconditions.checkState(textChild instanceof Text, getName() + " should contain text");
269 String content = textChild.getTextContent();
271 return content.trim();
274 public String getNamespaceAttribute() {
275 String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY);
276 Preconditions.checkState(attribute != null && !attribute.equals(""), "Element %s must specify a %s attribute",
277 toString(), XmlUtil.XMLNS_ATTRIBUTE_KEY);
281 public String getNamespace() {
282 String namespaceURI = element.getNamespaceURI();
283 Preconditions.checkState(namespaceURI != null, "No namespace defined for %s", this);
284 return namespaceURI.toString();
288 public String toString() {
289 final StringBuffer sb = new StringBuffer("XmlElement{");
290 sb.append("name='").append(getName()).append('\'');
291 if (element.getNamespaceURI() != null) {
292 sb.append(", namespace='").append(getNamespace()).append('\'');
295 return sb.toString();
299 * Search for element's attributes defining namespaces. Look for the one
300 * namespace that matches prefix of element's text content. E.g.
304 * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">th-java:threadfactory-naming</type>
307 * returns {"th-java","urn:.."}. If no prefix is matched, then default
308 * namespace is returned with empty string as key. If no default namespace
309 * is found value will be null.
311 public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() {
312 Map<String, String> namespaces = extractNamespaces(element);
313 String textContent = getTextContent();
314 int indexOfColon = textContent.indexOf(":");
316 if (indexOfColon > -1) {
317 prefix = textContent.substring(0, indexOfColon);
321 if (namespaces.containsKey(prefix) == false) {
322 throw new IllegalArgumentException("Cannot find namespace for " + element + ". Prefix from content is "
323 + prefix + ". Found namespaces " + namespaces);
325 return Maps.immutableEntry(prefix, namespaces.get(prefix));
328 public List<XmlElement> getChildElementsWithSameNamespace(final String childName) {
329 List<XmlElement> children = getChildElementsWithinNamespace(getNamespace());
330 return Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
332 public boolean apply(@Nullable XmlElement xmlElement) {
333 return xmlElement.getName().equals(childName);
338 public void checkUnrecognisedElements(List<XmlElement> recognisedElements,
339 XmlElement... additionalRecognisedElements) {
340 List<XmlElement> childElements = getChildElements();
341 childElements.removeAll(recognisedElements);
342 for (XmlElement additionalRecognisedElement : additionalRecognisedElements) {
343 childElements.remove(additionalRecognisedElement);
345 Preconditions.checkState(childElements.isEmpty(), "Unrecognised elements %s in %s", childElements, this);
348 public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) {
349 checkUnrecognisedElements(Collections.<XmlElement> emptyList(), additionalRecognisedElements);
353 public boolean equals(Object o) {
356 if (o == null || getClass() != o.getClass())
359 XmlElement that = (XmlElement) o;
361 if (!element.isEqualNode(that.element))
368 public int hashCode() {
369 return element.hashCode();
372 private static interface ElementFilteringStrategy {
373 boolean accept(Element e);