Remove dependency on controller config-util
[netconf.git] / netconf / netconf-util / src / main / java / org / opendaylight / netconf / util / messages / SubtreeFilter.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.netconf.util.messages;
10
11 import com.google.common.base.Optional;
12 import java.util.Map;
13 import org.opendaylight.netconf.api.DocumentedException;
14 import org.opendaylight.netconf.api.xml.XmlElement;
15 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
16 import org.opendaylight.netconf.api.xml.XmlUtil;
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;
24
25 /**
26  * See <a href="http://tools.ietf.org/html/rfc6241#section-6">rfc6241</a> for details.
27  */
28 public final class SubtreeFilter {
29     private static final Logger LOG = LoggerFactory.getLogger(SubtreeFilter.class);
30
31     private SubtreeFilter() {
32
33     }
34
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()) {
47                 return rpcReply;
48             }
49             XmlElement filter = maybeFilter.get();
50             if (isSupported(filter)) {
51
52                 // do
53                 return filtered(maybeFilter.get(), rpcReply);
54             }
55         }
56
57         return rpcReply; // return identical document
58     }
59
60     /**
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
67      */
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));
73         }
74         return Optional.of(extractNotificationContent(notification));
75     }
76
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);
81     }
82
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));
87     }
88
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());
94         return notification;
95     }
96
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));
104         }
105         if (dataDst.getFirstChild() != null) {
106             result.appendChild(dataDst.getFirstChild());
107             return result;
108         } else {
109             return null;
110         }
111     }
112
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));
124
125         return result;
126     }
127
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);
132             }
133         }
134     }
135
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;
155                         }
156                         if (childMatch == MatchingResult.CONTENT_MATCH) {
157                             numberOfTextMatchingChildren++;
158                         }
159                         shouldAppend |= childMatch != MatchingResult.NO_MATCH;
160                     }
161                 }
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);
167                 }
168             }
169             if (shouldAppend) {
170                 dstParent.getDomElement().appendChild(copied);
171             }
172         }
173         return matches;
174     }
175
176     /**
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.
179      */
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;
184         if (tagMatch) {
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;
190                 } else {
191                     result = MatchingResult.CONTENT_MISMATCH;
192                 }
193             }
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;
203                         } else {
204                             result = MatchingResult.NO_MATCH;
205                         }
206                     }
207                 }
208             }
209             if (result == null) {
210                 result = MatchingResult.TAG_MATCH;
211             }
212         }
213         if (result == null) {
214             result = MatchingResult.NO_MATCH;
215         }
216         LOG.debug("Matching {} to {} resulted in {}", src, filter, result);
217         return result;
218     }
219
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;
224         try {
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
229             return false;
230         }
231
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)) {
235             return false;
236         }
237         // Namespace mismatch
238         if (!prefixToNamespaceOfFilter.getValue().equals(prefixToNamespaceOfSrc.getValue())) {
239             return false;
240         }
241
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);
248     }
249
250     enum MatchingResult {
251         NO_MATCH, TAG_MATCH, CONTENT_MATCH, CONTENT_MISMATCH
252     }
253 }