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