a7ea7150bb8b8f35d6a2a08c1a72b6d09778d37a
[netconf.git] / plugins / netconf-server-mdsal / src / main / java / org / opendaylight / netconf / server / mdsal / operations / 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.server.mdsal.operations;
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.io.Serial;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Deque;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
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.server.mdsal.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.InstanceIdentifierTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.w3c.dom.Document;
52
53 /**
54  * Class validates filter content against schema context.
55  */
56 public class FilterContentValidator {
57
58     private static final Logger LOG = LoggerFactory.getLogger(FilterContentValidator.class);
59     private final CurrentSchemaContext schemaContext;
60
61     public FilterContentValidator(final CurrentSchemaContext schemaContext) {
62         this.schemaContext = schemaContext;
63     }
64
65     /**
66      * Validates filter content against this validator schema context. If the filter is valid,
67      * method returns {@link YangInstanceIdentifier} of node which can be used as root for data selection.
68      *
69      * @param filterContent filter content
70      * @return YangInstanceIdentifier
71      * @throws DocumentedException if filter content validation failed
72      */
73     public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
74         final XMLNamespace namespace;
75         try {
76             namespace = XMLNamespace.of(filterContent.getNamespace());
77         } catch (final IllegalArgumentException e) {
78             // FIXME: throw DocumentedException
79             throw new IllegalArgumentException("Wrong namespace in element + " + filterContent.toString(), e);
80         }
81
82         try {
83             final Module module = schemaContext.getCurrentContext().findModules(namespace).iterator().next();
84             final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
85             final FilterTree filterTree = validateNode(
86                     filterContent, schema, new FilterTree(schema.getQName(), Type.OTHER, schema));
87             return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
88         } catch (final ValidationException e) {
89             LOG.debug("Filter content isn't valid", e);
90             throw new DocumentedException("Validation failed. Cause: " + e.getMessage(), e,
91                     ErrorType.APPLICATION, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
92         }
93     }
94
95     /**
96      * Returns module's child data node of given name space and name.
97      *
98      * @param module    module
99      * @param nameSpace name space
100      * @param name      name
101      * @return child data node schema
102      * @throws DocumentedException if child with given name is not present
103      */
104     private DataSchemaNode getRootDataSchemaNode(final Module module, final XMLNamespace nameSpace, final String name)
105             throws DocumentedException {
106         for (final DataSchemaNode childNode : module.getChildNodes()) {
107             final QName qName = childNode.getQName();
108             if (qName.getNamespace().equals(nameSpace) && qName.getLocalName().equals(name)) {
109                 return childNode;
110             }
111         }
112         throw new DocumentedException("Unable to find node with namespace: " + nameSpace + " in schema context: "
113                 + schemaContext.getCurrentContext(),
114                 ErrorType.APPLICATION, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
115     }
116
117     /**
118      * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
119      *
120      * @param element          element to check
121      * @param parentNodeSchema parent node schema
122      * @param tree             parent node tree
123      * @return tree
124      * @throws ValidationException if filter content is not valid
125      */
126     private FilterTree validateNode(final XmlElement element, final DataSchemaNode parentNodeSchema,
127                                     final FilterTree tree) throws ValidationException {
128         for (final XmlElement childElement : element.getChildElements()) {
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 IllegalArgumentException("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(current, 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 parent, final FilterTree list, final XmlElement filterContent,
181             final List<String> pathToList, final InstanceIdentifierBuilder builder) {
182         Preconditions.checkArgument(list.getSchemaNode() instanceof ListSchemaNode);
183         final ListSchemaNode listSchemaNode = (ListSchemaNode) list.getSchemaNode();
184         final DataSchemaNode parentSchemaNode = parent.getSchemaNode();
185
186         final Map<QName, Object> map = getKeyValues(pathToList, filterContent, parentSchemaNode, listSchemaNode);
187         if (!map.isEmpty()) {
188             builder.nodeWithKey(list.getName(), map);
189         }
190     }
191
192     private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
193             final DataSchemaNode parentSchemaNode, 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 Map.of();
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 var optChildElements = current.getOnlyChildElementOptionally(qualifiedName.getLocalName());
208             if (optChildElements.isEmpty()) {
209                 return Map.of();
210             }
211             optChildElements.orElseThrow().getOnlyTextContentOptionally().ifPresent(keyValue -> {
212                 final LeafSchemaNode listKey = (LeafSchemaNode) listSchemaNode.getDataChildByName(qualifiedName);
213                 if (listKey instanceof IdentityrefTypeDefinition) {
214                     keys.put(qualifiedName, keyValue);
215                 } else {
216                     final TypeDefinition<? extends TypeDefinition<?>> keyType = listKey.getType();
217                     if (keyType instanceof IdentityrefTypeDefinition || keyType instanceof LeafrefTypeDefinition
218                             || keyType instanceof InstanceIdentifierTypeDefinition) {
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);
228                         keys.put(qualifiedName, deserializedKeyValue);
229                     } else {
230                         final Object deserializedKey = TypeDefinitionAwareCodec.from(keyType).deserialize(keyValue);
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         @Serial
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 }