459ae7c8a443e8d9daa4547658bbe646df291305
[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 static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
11 import static org.opendaylight.yangtools.yang.data.util.ParserStreamUtils.findSchemaNodeByNameAndNamespace;
12
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import java.net.URI;
16 import java.net.URISyntaxException;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.Deque;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24 import org.opendaylight.controller.config.util.xml.DocumentedException;
25 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
26 import org.opendaylight.controller.config.util.xml.XmlElement;
27 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
31 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.Module;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * Class validates filter content against schema context.
39  */
40 public class FilterContentValidator {
41
42     private static final Logger LOG = LoggerFactory.getLogger(FilterContentValidator.class);
43     private final CurrentSchemaContext schemaContext;
44
45     /**
46      * @param schemaContext current schema context
47      */
48     public FilterContentValidator(final CurrentSchemaContext schemaContext) {
49         this.schemaContext = schemaContext;
50     }
51
52     /**
53      * Validates filter content against this validator schema context. If the filter is valid,
54      * method returns {@link YangInstanceIdentifier} of node which can be used as root for data selection.
55      * @param filterContent filter content
56      * @return YangInstanceIdentifier
57      * @throws DocumentedException if filter content is not valid
58      */
59     public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
60         try {
61             final URI namespace = new URI(filterContent.getNamespace());
62             final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespace, null);
63             final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
64             final FilterTree filterTree = validateNode(filterContent, schema, new FilterTree(schema.getQName(),
65                     Type.OTHER, schema));
66             return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
67         } catch (final DocumentedException e) {
68             throw e;
69         } catch (final Exception e) {
70             LOG.debug("Filter content isn't valid", e);
71             throw new DocumentedException("Validation failed. Cause: " + e.getMessage(),
72                     DocumentedException.ErrorType.APPLICATION,
73                     DocumentedException.ErrorTag.UNKNOWN_NAMESPACE,
74                     DocumentedException.ErrorSeverity.ERROR);
75         }
76     }
77
78     /**
79      * Returns module's child data node of given name space and name
80      * @param module module
81      * @param nameSpace name space
82      * @param name name
83      * @return child data node schema
84      * @throws DocumentedException if child with given name is not present
85      */
86     private DataSchemaNode getRootDataSchemaNode(final Module module, final URI nameSpace, final String name)
87             throws DocumentedException {
88         final Collection<DataSchemaNode> childNodes = module.getChildNodes();
89         for (final DataSchemaNode childNode : childNodes) {
90             final QName qName = childNode.getQName();
91             if (qName.getNamespace().equals(nameSpace) && qName.getLocalName().equals(name)) {
92                 return childNode;
93             }
94         }
95         throw new DocumentedException("Unable to find node with namespace: " + nameSpace + "in schema context: " +
96                 schemaContext.getCurrentContext().toString(),
97                 DocumentedException.ErrorType.APPLICATION,
98                 DocumentedException.ErrorTag.UNKNOWN_NAMESPACE,
99                 DocumentedException.ErrorSeverity.ERROR);
100     }
101
102     /**
103      * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
104      * @param element element to check
105      * @param parentNodeSchema parent node schema
106      * @param tree parent node tree
107      * @return tree
108      * @throws ValidationException if filter content is not valid
109      */
110     private FilterTree validateNode(final XmlElement element, final DataSchemaNode parentNodeSchema,
111                                     final FilterTree tree) throws ValidationException {
112         final List<XmlElement> childElements = element.getChildElements();
113         for (final XmlElement childElement : childElements) {
114             try {
115                 final Deque<DataSchemaNode> path = findSchemaNodeByNameAndNamespace(parentNodeSchema,
116                         childElement.getName(), new URI(childElement.getNamespace()));
117                 if (path.isEmpty()) {
118                     throw new ValidationException(element, childElement);
119                 }
120                 FilterTree subtree = tree;
121                 for (final DataSchemaNode dataSchemaNode : path) {
122                     subtree = subtree.addChild(dataSchemaNode);
123                 }
124                 final DataSchemaNode childSchema = path.getLast();
125                 validateNode(childElement, childSchema, subtree);
126             } catch (URISyntaxException | MissingNameSpaceException e) {
127                 throw new RuntimeException("Wrong namespace in element + " + childElement.toString());
128             }
129         }
130         return tree;
131     }
132
133     /**
134      * Searches for YangInstanceIdentifier of node, which can be used as root for data selection.
135      * It goes as deep in tree as possible. Method stops traversing, when there are multiple child elements. If element
136      * represents list and child elements are key values, then it builds YangInstanceIdentifier of list entry.
137      * @param tree QName tree
138      * @param filterContent filter element
139      * @param builder builder  @return YangInstanceIdentifier
140      */
141     private YangInstanceIdentifier getFilterDataRoot(FilterTree tree, final XmlElement filterContent,
142                                                      final InstanceIdentifierBuilder builder) {
143         builder.node(tree.getName());
144         final List<String> path = new ArrayList<>();
145         while (tree.getChildren().size() == 1) {
146             final FilterTree child = tree.getChildren().iterator().next();
147             if (child.getType() == Type.CHOICE_CASE) {
148                 tree = child;
149                 continue;
150             }
151             builder.node(child.getName());
152             path.add(child.getName().getLocalName());
153             if (child.getType() == Type.LIST) {
154                 appendKeyIfPresent(child, filterContent, path, builder);
155                 return builder.build();
156             }
157             tree = child;
158         }
159         return builder.build();
160     }
161
162     private void appendKeyIfPresent(final FilterTree tree, final XmlElement filterContent,
163                                     final List<String> pathToList,
164                                     final InstanceIdentifierBuilder builder) {
165         Preconditions.checkArgument(tree.getSchemaNode() instanceof ListSchemaNode);
166         final ListSchemaNode listSchemaNode = (ListSchemaNode) tree.getSchemaNode();
167         final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
168         final Map<QName, Object> map = getKeyValues(pathToList, filterContent, keyDefinition);
169         if (!map.isEmpty()) {
170             builder.nodeWithKey(tree.getName(), map);
171         }
172     }
173
174     private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
175                                             final List<QName> keyDefinition) {
176         XmlElement current = filterContent;
177         //find list element
178         for (final String pathElement : path) {
179             final List<XmlElement> childElements = current.getChildElements(pathElement);
180             // if there are multiple list entries present in the filter, we can't use any keys and must read whole list
181             if (childElements.size() != 1) {
182                 return Collections.emptyMap();
183             }
184             current = childElements.get(0);
185         }
186         final Map<QName, Object> keys = new HashMap<>();
187         for (final QName qName : keyDefinition) {
188             final Optional<XmlElement> childElements = current.getOnlyChildElementOptionally(qName.getLocalName());
189             if (!childElements.isPresent()) {
190                 return Collections.emptyMap();
191             }
192             final Optional<String> keyValue = childElements.get().getOnlyTextContentOptionally();
193             if (keyValue.isPresent()) {
194                 keys.put(qName, keyValue.get());
195             }
196         }
197         return keys;
198     }
199
200     /**
201      * Class represents tree of QNames as they are present in the filter.
202      */
203     private static class FilterTree {
204
205         private final QName name;
206         private final Type type;
207         private final DataSchemaNode schemaNode;
208         private final Map<QName, FilterTree> children;
209
210         FilterTree(final QName name, final Type type, final DataSchemaNode schemaNode) {
211             this.name = name;
212             this.type = type;
213             this.schemaNode = schemaNode;
214             this.children = new HashMap<>();
215         }
216
217         FilterTree addChild(final DataSchemaNode data) {
218             final Type type;
219             if (data instanceof ChoiceCaseNode) {
220                 type = Type.CHOICE_CASE;
221             } else if (data instanceof ListSchemaNode) {
222                 type = Type.LIST;
223             } else {
224                 type = Type.OTHER;
225             }
226             final QName name = data.getQName();
227             FilterTree childTree = children.get(name);
228             if (childTree == null) {
229                 childTree = new FilterTree(name, type, data);
230             }
231             children.put(name, childTree);
232             return childTree;
233         }
234
235         Collection<FilterTree> getChildren() {
236             return children.values();
237         }
238
239         QName getName() {
240             return name;
241         }
242
243         Type getType() {
244             return type;
245         }
246
247         DataSchemaNode getSchemaNode() {
248             return schemaNode;
249         }
250     }
251
252     private enum Type {
253         LIST, CHOICE_CASE, OTHER
254     }
255
256     private static class ValidationException extends Exception {
257         public ValidationException(final XmlElement parent, final XmlElement child) {
258             super("Element " + child + " can't be child of " + parent);
259         }
260     }
261
262 }