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