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