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 if (element.getLocalName()!=null && !element.getLocalName().equals("")){
107 return element.getLocalName();
109 return element.getTagName();
112 public String getAttribute(String attributeName) {
113 return element.getAttribute(attributeName);
116 public String getAttribute(String attributeName, String namespace) {
117 return element.getAttributeNS(namespace, attributeName);
120 public NodeList getElementsByTagName(String name) {
121 return element.getElementsByTagName(name);
124 public void appendChild(Element element) {
125 this.element.appendChild(element);
126 // Element newElement = (Element) element.cloneNode(true);
127 // newElement.appendChild(configElement);
128 // return XmlElement.fromDomElement(newElement);
131 public Element getDomElement() {
135 public Map<String, Attr> getAttributes() {
137 Map<String, Attr> mappedAttributes = Maps.newHashMap();
139 NamedNodeMap attributes = element.getAttributes();
140 for (int i = 0; i < attributes.getLength(); i++) {
141 Attr attr = (Attr) attributes.item(i);
142 mappedAttributes.put(attr.getNodeName(), attr);
145 return mappedAttributes;
151 private List<XmlElement> getChildElementsInternal(ElementFilteringStrategy strat) {
152 NodeList childNodes = element.getChildNodes();
153 final List<XmlElement> result = new ArrayList<>();
154 for (int i = 0; i < childNodes.getLength(); i++) {
155 Node item = childNodes.item(i);
156 if (item instanceof Element == false)
158 if (strat.accept((Element) item))
159 result.add(new XmlElement((Element) item));
165 public List<XmlElement> getChildElements() {
166 return getChildElementsInternal(new ElementFilteringStrategy() {
168 public boolean accept(Element e) {
174 public List<XmlElement> getChildElementsWithinNamespace(final String childName, String namespace) {
175 return Lists.newArrayList(Collections2.filter(getChildElementsWithinNamespace(namespace),
176 new Predicate<XmlElement>() {
178 public boolean apply(@Nullable XmlElement xmlElement) {
179 return xmlElement.getName().equals(childName);
184 public List<XmlElement> getChildElementsWithinNamespace(final String namespace) {
185 return getChildElementsInternal(new ElementFilteringStrategy() {
187 public boolean accept(Element e) {
188 return XmlElement.fromDomElement(e).getNamespace().equals(namespace);
194 public List<XmlElement> getChildElements(final String tagName) {
195 return getChildElementsInternal(new ElementFilteringStrategy() {
197 public boolean accept(Element e) {
198 return e.getTagName().equals(tagName);
203 public XmlElement getOnlyChildElement(String childName) {
204 List<XmlElement> nameElements = getChildElements(childName);
205 Preconditions.checkState(nameElements.size() == 1, "One element " + childName + " expected in " + toString());
206 return nameElements.get(0);
209 public Optional<XmlElement> getOnlyChildElementOptionally(String childName) {
211 return Optional.of(getOnlyChildElement(childName));
212 } catch (Exception e) {
213 return Optional.absent();
217 public Optional<XmlElement> getOnlyChildElementOptionally(String childName, String namespace) {
219 return Optional.of(getOnlyChildElement(childName, namespace));
220 } catch (Exception e) {
221 return Optional.absent();
225 public XmlElement getOnlyChildElementWithSameNamespace(String childName) {
226 return getOnlyChildElement(childName, getNamespace());
229 public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally(String childName) {
231 return Optional.of(getOnlyChildElement(childName, getNamespace()));
232 } catch (Exception e) {
233 return Optional.absent();
237 public XmlElement getOnlyChildElementWithSameNamespace() {
238 XmlElement childElement = getOnlyChildElement();
239 childElement.checkNamespace(getNamespace());
243 public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally() {
245 XmlElement childElement = getOnlyChildElement();
246 childElement.checkNamespace(getNamespace());
247 return Optional.of(childElement);
248 } catch (Exception e) {
249 return Optional.absent();
253 public XmlElement getOnlyChildElement(final String childName, String namespace) {
254 List<XmlElement> children = getChildElementsWithinNamespace(namespace);
255 children = Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
257 public boolean apply(@Nullable XmlElement xmlElement) {
258 return xmlElement.getName().equals(childName);
261 Preconditions.checkState(children.size() == 1, "One element %s:%s expected in %s but was %s", namespace,
262 childName, toString(), children.size());
263 return children.get(0);
266 public XmlElement getOnlyChildElement() {
267 List<XmlElement> children = getChildElements();
268 Preconditions.checkState(children.size() == 1, "One element expected in %s but was %s", toString(),
270 return children.get(0);
273 public String getTextContent() {
274 Node textChild = element.getFirstChild();
275 Preconditions.checkState(textChild instanceof Text, getName() + " should contain text");
276 String content = textChild.getTextContent();
278 return content.trim();
281 public String getNamespaceAttribute() {
282 String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY);
283 Preconditions.checkState(attribute != null && !attribute.equals(""), "Element %s must specify namespace",
288 public String getNamespace() {
289 String namespaceURI = element.getNamespaceURI();
290 Preconditions.checkState(namespaceURI != null, "No namespace defined for %s", this);
291 return namespaceURI.toString();
295 public String toString() {
296 final StringBuffer sb = new StringBuffer("XmlElement{");
297 sb.append("name='").append(getName()).append('\'');
298 if (element.getNamespaceURI() != null) {
299 sb.append(", namespace='").append(getNamespace()).append('\'');
302 return sb.toString();
306 * Search for element's attributes defining namespaces. Look for the one
307 * namespace that matches prefix of element's text content. E.g.
311 * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">th-java:threadfactory-naming</type>
314 * returns {"th-java","urn:.."}. If no prefix is matched, then default
315 * namespace is returned with empty string as key. If no default namespace
316 * is found value will be null.
318 public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() {
319 Map<String, String> namespaces = extractNamespaces(element);
320 String textContent = getTextContent();
321 int indexOfColon = textContent.indexOf(":");
323 if (indexOfColon > -1) {
324 prefix = textContent.substring(0, indexOfColon);
328 if (namespaces.containsKey(prefix) == false) {
329 throw new IllegalArgumentException("Cannot find namespace for " + element + ". Prefix from content is "
330 + prefix + ". Found namespaces " + namespaces);
332 return Maps.immutableEntry(prefix, namespaces.get(prefix));
335 public List<XmlElement> getChildElementsWithSameNamespace(final String childName) {
336 List<XmlElement> children = getChildElementsWithinNamespace(getNamespace());
337 return Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
339 public boolean apply(@Nullable XmlElement xmlElement) {
340 return xmlElement.getName().equals(childName);
345 public void checkUnrecognisedElements(List<XmlElement> recognisedElements,
346 XmlElement... additionalRecognisedElements) {
347 List<XmlElement> childElements = getChildElements();
348 childElements.removeAll(recognisedElements);
349 for (XmlElement additionalRecognisedElement : additionalRecognisedElements) {
350 childElements.remove(additionalRecognisedElement);
352 Preconditions.checkState(childElements.isEmpty(), "Unrecognised elements %s in %s", childElements, this);
355 public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) {
356 checkUnrecognisedElements(Collections.<XmlElement> emptyList(), additionalRecognisedElements);
360 public boolean equals(Object o) {
363 if (o == null || getClass() != o.getClass())
366 XmlElement that = (XmlElement) o;
368 if (!element.isEqualNode(that.element))
375 public int hashCode() {
376 return element.hashCode();
379 public boolean hasNamespace() {
381 getNamespaceAttribute();
382 } catch (IllegalStateException e) {
385 } catch (IllegalStateException e1) {
393 private static interface ElementFilteringStrategy {
394 boolean accept(Element e);