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