2 * Copyright (c) 2014 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.netconf.util.messages;
11 import com.google.common.base.Optional;
13 import org.opendaylight.controller.config.util.xml.DocumentedException;
14 import org.opendaylight.controller.config.util.xml.XmlElement;
15 import org.opendaylight.controller.config.util.xml.XmlUtil;
16 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
17 import org.opendaylight.netconf.util.mapping.AbstractNetconfOperation.OperationNameAndNamespace;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20 import org.w3c.dom.Attr;
21 import org.w3c.dom.Document;
22 import org.w3c.dom.Element;
23 import org.w3c.dom.Node;
26 * See <a href="http://tools.ietf.org/html/rfc6241#section-6">rfc6241</a> for details.
28 public final class SubtreeFilter {
29 private static final Logger LOG = LoggerFactory.getLogger(SubtreeFilter.class);
31 private SubtreeFilter() {
35 public static Document applyRpcSubtreeFilter(Document requestDocument,
36 Document rpcReply) throws DocumentedException {
37 OperationNameAndNamespace operationNameAndNamespace = new OperationNameAndNamespace(requestDocument);
38 if (XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0.equals(operationNameAndNamespace.getNamespace())
39 && XmlNetconfConstants.GET.equals(operationNameAndNamespace.getOperationName())
40 || XmlNetconfConstants.GET_CONFIG.equals(operationNameAndNamespace.getOperationName())) {
41 // process subtree filtering here, in case registered netconf operations do
42 // not implement filtering.
43 Optional<XmlElement> maybeFilter = operationNameAndNamespace.getOperationElement()
44 .getOnlyChildElementOptionally(XmlNetconfConstants.FILTER,
45 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
46 if (!maybeFilter.isPresent()) {
49 XmlElement filter = maybeFilter.get();
50 if (isSupported(filter)) {
53 return filtered(maybeFilter.get(), rpcReply);
57 return rpcReply; // return identical document
61 * Filters notification content. If filter type isn't of type "subtree", returns unchanged notification content.
62 * If no match is found, absent is returned.
63 * @param filter filter
64 * @param notification notification
65 * @return document containing filtered notification content
66 * @throws DocumentedException if operation fails
68 public static Optional<Document> applySubtreeNotificationFilter(XmlElement filter,
69 Document notification) throws DocumentedException {
70 removeEventTimeNode(notification);
71 if (isSupported(filter)) {
72 return Optional.fromNullable(filteredNotification(filter, notification));
74 return Optional.of(extractNotificationContent(notification));
77 private static void removeEventTimeNode(Document document) {
78 final Node eventTimeNode = document.getDocumentElement().getElementsByTagNameNS(XmlNetconfConstants
79 .URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0, XmlNetconfConstants.EVENT_TIME).item(0);
80 document.getDocumentElement().removeChild(eventTimeNode);
83 private static boolean isSupported(XmlElement filter) {
84 return "subtree".equals(filter.getAttribute("type"))
85 || "subtree".equals(filter.getAttribute("type",
86 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
89 private static Document extractNotificationContent(Document notification) throws DocumentedException {
90 XmlElement root = XmlElement.fromDomElement(notification.getDocumentElement());
91 XmlElement content = root.getOnlyChildElement();
92 notification.removeChild(root.getDomElement());
93 notification.appendChild(content.getDomElement());
97 private static Document filteredNotification(XmlElement filter,
98 Document originalNotification) throws DocumentedException {
99 Document result = XmlUtil.newDocument();
100 XmlElement dataSrc = XmlElement.fromDomDocument(originalNotification);
101 Element dataDst = (Element) result.importNode(dataSrc.getDomElement(), false);
102 for (XmlElement filterChild : filter.getChildElements()) {
103 addSubtree2(filterChild, dataSrc.getOnlyChildElement(), XmlElement.fromDomElement(dataDst));
105 if (dataDst.getFirstChild() != null) {
106 result.appendChild(dataDst.getFirstChild());
113 private static Document filtered(XmlElement filter, Document originalReplyDocument) throws DocumentedException {
114 Document result = XmlUtil.newDocument();
115 // even if filter is empty, copy /rpc/data
116 Element rpcReply = originalReplyDocument.getDocumentElement();
117 Node rpcReplyDst = result.importNode(rpcReply, false);
118 result.appendChild(rpcReplyDst);
119 XmlElement dataSrc = XmlElement.fromDomElement(rpcReply).getOnlyChildElement("data",
120 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
121 Element dataDst = (Element) result.importNode(dataSrc.getDomElement(), false);
122 rpcReplyDst.appendChild(dataDst);
123 addSubtree(filter, dataSrc, XmlElement.fromDomElement(dataDst));
128 private static void addSubtree(XmlElement filter, XmlElement src, XmlElement dst) throws DocumentedException {
129 for (XmlElement srcChild : src.getChildElements()) {
130 for (XmlElement filterChild : filter.getChildElements()) {
131 addSubtree2(filterChild, srcChild, dst);
136 private static MatchingResult addSubtree2(XmlElement filter, XmlElement src,
137 XmlElement dstParent) throws DocumentedException {
138 Document document = dstParent.getDomElement().getOwnerDocument();
139 MatchingResult matches = matches(src, filter);
140 if (matches != MatchingResult.NO_MATCH && matches != MatchingResult.CONTENT_MISMATCH) {
141 // copy srcChild to dst
142 boolean filterHasChildren = !filter.getChildElements().isEmpty();
143 // copy to depth if this is leaf of filter tree
144 Element copied = (Element) document.importNode(src.getDomElement(), !filterHasChildren);
145 boolean shouldAppend = !filterHasChildren;
146 if (filterHasChildren) { // this implies TAG_MATCH
147 // do the same recursively
148 int numberOfTextMatchingChildren = 0;
149 for (XmlElement srcChild : src.getChildElements()) {
150 for (XmlElement filterChild : filter.getChildElements()) {
151 MatchingResult childMatch =
152 addSubtree2(filterChild, srcChild, XmlElement.fromDomElement(copied));
153 if (childMatch == MatchingResult.CONTENT_MISMATCH) {
154 return MatchingResult.NO_MATCH;
156 if (childMatch == MatchingResult.CONTENT_MATCH) {
157 numberOfTextMatchingChildren++;
159 shouldAppend |= childMatch != MatchingResult.NO_MATCH;
162 // if only text matching child filters are specified..
163 if (numberOfTextMatchingChildren == filter.getChildElements().size()) {
164 // force all children to be added (to depth). This is done by copying parent node to depth.
165 // implies shouldAppend == true
166 copied = (Element) document.importNode(src.getDomElement(), true);
170 dstParent.getDomElement().appendChild(copied);
177 * Shallow compare src node to filter: tag name and namespace must match.
178 * If filter node has no children and has text content, it also must match.
180 private static MatchingResult matches(XmlElement src, XmlElement filter) throws DocumentedException {
181 boolean tagMatch = src.getName().equals(filter.getName())
182 && src.getNamespaceOptionally().equals(filter.getNamespaceOptionally());
183 MatchingResult result = null;
185 // match text content
186 Optional<String> maybeText = filter.getOnlyTextContentOptionally();
187 if (maybeText.isPresent()) {
188 if (maybeText.equals(src.getOnlyTextContentOptionally()) || prefixedContentMatches(filter, src)) {
189 result = MatchingResult.CONTENT_MATCH;
191 result = MatchingResult.CONTENT_MISMATCH;
194 // match attributes, combination of content and tag is not supported
195 if (result == null) {
196 for (Attr attr : filter.getAttributes().values()) {
197 // ignore namespace declarations
198 if (!XmlUtil.XMLNS_URI.equals(attr.getNamespaceURI())) {
199 // find attr with matching localName(), namespaceURI(), == value() in src
200 String found = src.getAttribute(attr.getLocalName(), attr.getNamespaceURI());
201 if (attr.getValue().equals(found) && result != MatchingResult.NO_MATCH) {
202 result = MatchingResult.TAG_MATCH;
204 result = MatchingResult.NO_MATCH;
209 if (result == null) {
210 result = MatchingResult.TAG_MATCH;
213 if (result == null) {
214 result = MatchingResult.NO_MATCH;
216 LOG.debug("Matching {} to {} resulted in {}", src, filter, result);
220 private static boolean prefixedContentMatches(final XmlElement filter,
221 final XmlElement src) throws DocumentedException {
222 final Map.Entry<String, String> prefixToNamespaceOfFilter;
223 final Map.Entry<String, String> prefixToNamespaceOfSrc;
225 prefixToNamespaceOfFilter = filter.findNamespaceOfTextContent();
226 prefixToNamespaceOfSrc = src.findNamespaceOfTextContent();
227 } catch (IllegalArgumentException e) {
228 //if we can't find namespace of prefix - it's not a prefix, so it doesn't match
232 final String prefix = prefixToNamespaceOfFilter.getKey();
233 // If this is not a prefixed content, we do not need to continue since content do not match
234 if (prefix.equals(XmlElement.DEFAULT_NAMESPACE_PREFIX)) {
237 // Namespace mismatch
238 if (!prefixToNamespaceOfFilter.getValue().equals(prefixToNamespaceOfSrc.getValue())) {
242 final String unprefixedFilterContent =
243 filter.getTextContent().substring(prefixToNamespaceOfFilter.getKey().length() + 1);
244 final String unprefixedSrcContnet =
245 src.getTextContent().substring(prefixToNamespaceOfSrc.getKey().length() + 1);
246 // Finally compare unprefixed content
247 return unprefixedFilterContent.equals(unprefixedSrcContnet);
250 enum MatchingResult {
251 NO_MATCH, TAG_MATCH, CONTENT_MATCH, CONTENT_MISMATCH