Merge "builder class for path creating"
[netconf.git] / netconf / mdsal-netconf-connector / src / main / java / org / opendaylight / netconf / mdsal / connector / ops / get / FilterContentValidator.java
1 /*
2  * Copyright (c) 2016 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 package org.opendaylight.netconf.mdsal.connector.ops.get;
9
10 import java.net.URI;
11 import java.net.URISyntaxException;
12 import java.util.ArrayDeque;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Deque;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19 import org.opendaylight.controller.config.util.xml.DocumentedException;
20 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
21 import org.opendaylight.controller.config.util.xml.XmlElement;
22 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
25 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
26 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
28 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.Module;
31
32 /**
33  * Class validates filter content against schema context.
34  */
35 public class FilterContentValidator {
36
37     private final CurrentSchemaContext schemaContext;
38
39     /**
40      * @param schemaContext current schema context
41      */
42     public FilterContentValidator(CurrentSchemaContext schemaContext) {
43         this.schemaContext = schemaContext;
44     }
45
46     /**
47      * Validates filter content against this validator schema context. If the filter is valid, method returns {@link YangInstanceIdentifier}
48      * of node which can be used as root for data selection.
49      * @param filterContent filter content
50      * @return YangInstanceIdentifier
51      * @throws DocumentedException if filter content is not valid
52      */
53     public YangInstanceIdentifier validate(XmlElement filterContent) throws DocumentedException {
54         try {
55             final URI namespace = new URI(filterContent.getNamespace());
56             final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespace, null);
57             final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
58             final FilterTree filterTree = validateNode(filterContent, schema, new FilterTree(schema.getQName(), Type.OTHER));
59             return getFilterDataRoot(filterTree, YangInstanceIdentifier.builder());
60         } catch (DocumentedException e) {
61             throw e;
62         } catch (Exception e) {
63             throw new DocumentedException("Validation failed. Cause: " + e.getMessage(),
64                     DocumentedException.ErrorType.application,
65                     DocumentedException.ErrorTag.unknown_namespace,
66                     DocumentedException.ErrorSeverity.error);
67         }
68     }
69
70     /**
71      * Returns module's child data node of given name space and name
72      * @param module module
73      * @param nameSpace name space
74      * @param name name
75      * @return child data node schema
76      * @throws DocumentedException if child with given name is not present
77      */
78     private DataSchemaNode getRootDataSchemaNode(Module module, URI nameSpace, String name) throws DocumentedException {
79         final Collection<DataSchemaNode> childNodes = module.getChildNodes();
80         for (DataSchemaNode childNode : childNodes) {
81             final QName qName = childNode.getQName();
82             if (qName.getNamespace().equals(nameSpace) && qName.getLocalName().equals(name)) {
83                 return childNode;
84             }
85         }
86         throw new DocumentedException("Unable to find node with namespace: " + nameSpace + "in schema context: " + schemaContext.getCurrentContext().toString(),
87                 DocumentedException.ErrorType.application,
88                 DocumentedException.ErrorTag.unknown_namespace,
89                 DocumentedException.ErrorSeverity.error);
90     }
91
92     /**
93      * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
94      * @param element element to check
95      * @param parentNodeSchema parent node schema
96      * @param tree parent node tree
97      * @return tree
98      * @throws ValidationException if filter content is not valid
99      */
100     private FilterTree validateNode(XmlElement element, DataSchemaNode parentNodeSchema, FilterTree tree) throws ValidationException {
101         final List<XmlElement> childElements = element.getChildElements();
102         for (XmlElement childElement : childElements) {
103             try {
104                 final Deque<DataSchemaNode> path = findSchemaNodeByNameAndNamespace(parentNodeSchema, childElement.getName(), new URI(childElement.getNamespace()));
105                 if (path.isEmpty()) {
106                     throw new ValidationException(element, childElement);
107                 }
108                 FilterTree subtree = tree;
109                 for (DataSchemaNode dataSchemaNode : path) {
110                         subtree = subtree.addChild(dataSchemaNode);
111                 }
112                 final DataSchemaNode childSchema = path.getLast();
113                 validateNode(childElement, childSchema, subtree);
114             } catch (URISyntaxException | MissingNameSpaceException e) {
115                 throw new RuntimeException("Wrong namespace in element + " + childElement.toString());
116             }
117         }
118         return tree;
119     }
120
121     /**
122      * Searches for YangInstanceIdentifier of node, which can be used as root for data selection.
123      * It goes as deep in tree as possible. Method stops traversing, when there are multiple child elements
124      * or when it encounters list node.
125      * @param tree QName tree
126      * @param builder builder
127      * @return YangInstanceIdentifier
128      */
129     private YangInstanceIdentifier getFilterDataRoot(FilterTree tree, YangInstanceIdentifier.InstanceIdentifierBuilder builder) {
130         builder.node(tree.getName());
131         while (tree.getChildren().size() == 1) {
132             final FilterTree child = tree.getChildren().iterator().next();
133             if (child.getType() == Type.CHOICE_CASE) {
134                 tree = child;
135                 continue;
136             }
137             builder.node(child.getName());
138             if (child.getType() == Type.LIST) {
139                 return builder.build();
140             }
141             tree = child;
142         }
143         return builder.build();
144     }
145
146     //FIXME this method will also be in yangtools ParserUtils, use that when https://git.opendaylight.org/gerrit/#/c/37031/ will be merged
147     /**
148      * Returns stack of schema nodes via which it was necessary to pass to get schema node with specified
149      * {@code childName} and {@code namespace}
150      *
151      * @param dataSchemaNode
152      * @param childName
153      * @param namespace
154      * @return stack of schema nodes via which it was passed through. If found schema node is direct child then stack
155      *         contains only one node. If it is found under choice and case then stack should contains 2*n+1 element
156      *         (where n is number of choices through it was passed)
157      */
158     private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
159                                                                    final String childName, final URI namespace) {
160         final Deque<DataSchemaNode> result = new ArrayDeque<>();
161         final List<ChoiceSchemaNode> childChoices = new ArrayList<>();
162         DataSchemaNode potentialChildNode = null;
163         if (dataSchemaNode instanceof DataNodeContainer) {
164             for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
165                 if (childNode instanceof ChoiceSchemaNode) {
166                     childChoices.add((ChoiceSchemaNode) childNode);
167                 } else {
168                     final QName childQName = childNode.getQName();
169
170                     if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
171                         if (potentialChildNode == null ||
172                                 childQName.getRevision().after(potentialChildNode.getQName().getRevision())) {
173                             potentialChildNode = childNode;
174                         }
175                     }
176                 }
177             }
178         }
179         if (potentialChildNode != null) {
180             result.push(potentialChildNode);
181             return result;
182         }
183
184         // try to find data schema node in choice (looking for first match)
185         for (final ChoiceSchemaNode choiceNode : childChoices) {
186             for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
187                 final Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
188                         namespace);
189                 if (!resultFromRecursion.isEmpty()) {
190                     resultFromRecursion.push(concreteCase);
191                     resultFromRecursion.push(choiceNode);
192                     return resultFromRecursion;
193                 }
194             }
195         }
196         return result;
197     }
198
199     /**
200      * Class represents tree of QNames as they are present in the filter.
201      */
202     private static class FilterTree {
203
204         private final QName name;
205         private final Type type;
206         private final Map<QName, FilterTree> children;
207
208         FilterTree(QName name, Type type) {
209             this.name = name;
210             this.type = type;
211             this.children = new HashMap<>();
212         }
213
214         FilterTree addChild(DataSchemaNode data) {
215             Type type;
216             if (data instanceof ChoiceCaseNode) {
217                 type = Type.CHOICE_CASE;
218             } else if (data instanceof ListSchemaNode) {
219                 type = Type.LIST;
220             } else {
221                 type = Type.OTHER;
222             }
223             final QName name = data.getQName();
224             FilterTree childTree = children.get(name);
225             if (childTree == null) {
226                 childTree = new FilterTree(name, type);
227             }
228             children.put(name, childTree);
229             return childTree;
230         }
231
232         Collection<FilterTree> getChildren() {
233             return children.values();
234         }
235
236         QName getName() {
237             return name;
238         }
239
240         Type getType() {
241             return type;
242         }
243     }
244
245     private enum Type {
246         LIST, CHOICE_CASE, OTHER
247     }
248
249     private static class ValidationException extends Exception {
250         public ValidationException(XmlElement parent, XmlElement child) {
251             super("Element " + child + " can't be child of " + parent);
252         }
253     }
254
255 }