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