Remove DocumentedException.ErrorType
[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.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.type.IdentityrefTypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.w3c.dom.Document;
49
50 /**
51  * Class validates filter content against schema context.
52  */
53 public class FilterContentValidator {
54
55     private static final Logger LOG = LoggerFactory.getLogger(FilterContentValidator.class);
56     private final CurrentSchemaContext schemaContext;
57
58     public FilterContentValidator(final CurrentSchemaContext schemaContext) {
59         this.schemaContext = schemaContext;
60     }
61
62     /**
63      * Validates filter content against this validator schema context. If the filter is valid,
64      * method returns {@link YangInstanceIdentifier} of node which can be used as root for data selection.
65      *
66      * @param filterContent filter content
67      * @return YangInstanceIdentifier
68      * @throws DocumentedException if filter content validation failed
69      */
70     public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
71         final XMLNamespace namespace;
72         try {
73             namespace = XMLNamespace.of(filterContent.getNamespace());
74         } catch (final IllegalArgumentException e) {
75             throw new RuntimeException("Wrong namespace in element + " + filterContent.toString(), e);
76         }
77
78         try {
79             final Module module = schemaContext.getCurrentContext().findModules(namespace).iterator().next();
80             final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
81             final FilterTree filterTree = validateNode(
82                     filterContent, schema, new FilterTree(schema.getQName(), Type.OTHER, schema));
83             return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
84         } catch (final ValidationException e) {
85             LOG.debug("Filter content isn't valid", e);
86             throw new DocumentedException("Validation failed. Cause: " + e.getMessage(), e,
87                     ErrorType.APPLICATION, DocumentedException.ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
88         }
89     }
90
91     /**
92      * Returns module's child data node of given name space and name.
93      *
94      * @param module    module
95      * @param nameSpace name space
96      * @param name      name
97      * @return child data node schema
98      * @throws DocumentedException if child with given name is not present
99      */
100     private DataSchemaNode getRootDataSchemaNode(final Module module, final XMLNamespace nameSpace, final String name)
101             throws DocumentedException {
102         for (final DataSchemaNode childNode : module.getChildNodes()) {
103             final QName qName = childNode.getQName();
104             if (qName.getNamespace().equals(nameSpace) && qName.getLocalName().equals(name)) {
105                 return childNode;
106             }
107         }
108         throw new DocumentedException("Unable to find node with namespace: " + nameSpace + " in schema context: "
109                 + schemaContext.getCurrentContext(),
110                 ErrorType.APPLICATION, DocumentedException.ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
111     }
112
113     /**
114      * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
115      *
116      * @param element          element to check
117      * @param parentNodeSchema parent node schema
118      * @param tree             parent node tree
119      * @return tree
120      * @throws ValidationException if filter content is not valid
121      */
122     private FilterTree validateNode(final XmlElement element, final DataSchemaNode parentNodeSchema,
123                                     final FilterTree tree) throws ValidationException {
124         final List<XmlElement> childElements = element.getChildElements();
125         for (final XmlElement childElement : childElements) {
126             try {
127                 final Deque<DataSchemaNode> path = findSchemaNodeByNameAndNamespace(parentNodeSchema,
128                         childElement.getName(), XMLNamespace.of(childElement.getNamespace()));
129                 if (path.isEmpty()) {
130                     throw new ValidationException(element, childElement);
131                 }
132                 FilterTree subtree = tree;
133                 for (final DataSchemaNode dataSchemaNode : path) {
134                     subtree = subtree.addChild(dataSchemaNode);
135                 }
136                 final DataSchemaNode childSchema = path.getLast();
137                 validateNode(childElement, childSchema, subtree);
138             } catch (IllegalArgumentException | MissingNameSpaceException e) {
139                 throw new RuntimeException("Wrong namespace in element + " + childElement.toString(), e);
140             }
141         }
142         return tree;
143     }
144
145     /**
146      * Searches for YangInstanceIdentifier of node, which can be used as root for data selection.
147      * It goes as deep in tree as possible. Method stops traversing, when there are multiple child elements. If element
148      * represents list and child elements are key values, then it builds YangInstanceIdentifier of list entry.
149      *
150      * @param tree          QName tree
151      * @param filterContent filter element
152      * @param builder       builder  @return YangInstanceIdentifier
153      */
154     private YangInstanceIdentifier getFilterDataRoot(final FilterTree tree, final XmlElement filterContent,
155                                                      final InstanceIdentifierBuilder builder) {
156         builder.node(tree.getName());
157         final List<String> path = new ArrayList<>();
158
159         FilterTree current = tree;
160         while (current.size() == 1) {
161             final FilterTree child = current.getChildren().iterator().next();
162             if (child.getType() == Type.CHOICE_CASE) {
163                 current = child;
164                 continue;
165             }
166             builder.node(child.getName());
167             path.add(child.getName().getLocalName());
168             if (child.getType() == Type.LIST) {
169                 appendKeyIfPresent(child, filterContent, path, builder);
170                 return builder.build();
171             }
172             current = child;
173         }
174         return builder.build();
175     }
176
177     private void appendKeyIfPresent(final FilterTree tree, final XmlElement filterContent,
178                                     final List<String> pathToList,
179                                     final InstanceIdentifierBuilder builder) {
180         Preconditions.checkArgument(tree.getSchemaNode() instanceof ListSchemaNode);
181         final ListSchemaNode listSchemaNode = (ListSchemaNode) tree.getSchemaNode();
182
183         final Map<QName, Object> map = getKeyValues(pathToList, filterContent, listSchemaNode);
184         if (!map.isEmpty()) {
185             builder.nodeWithKey(tree.getName(), map);
186         }
187     }
188
189     private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
190                                             final ListSchemaNode listSchemaNode) {
191         XmlElement current = filterContent;
192         //find list element
193         for (final String pathElement : path) {
194             final List<XmlElement> childElements = current.getChildElements(pathElement);
195             // if there are multiple list entries present in the filter, we can't use any keys and must read whole list
196             if (childElements.size() != 1) {
197                 return Map.of();
198             }
199             current = childElements.get(0);
200         }
201         final Map<QName, Object> keys = new HashMap<>();
202         final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
203         for (final QName qualifiedName : keyDefinition) {
204             final Optional<XmlElement> childElements =
205                     current.getOnlyChildElementOptionally(qualifiedName.getLocalName());
206             if (childElements.isEmpty()) {
207                 return Map.of();
208             }
209             final Optional<String> keyValue = childElements.get().getOnlyTextContentOptionally();
210             if (keyValue.isPresent()) {
211                 final LeafSchemaNode listKey = (LeafSchemaNode) listSchemaNode.getDataChildByName(qualifiedName);
212                 if (listKey instanceof IdentityrefTypeDefinition) {
213                     keys.put(qualifiedName, keyValue.get());
214                 } else {
215                     final TypeDefinition<? extends TypeDefinition<?>> keyType = listKey.getType();
216                     if (keyType instanceof IdentityrefTypeDefinition || keyType instanceof LeafrefTypeDefinition) {
217                         final Document document = filterContent.getDomElement().getOwnerDocument();
218                         final NamespaceContext nsContext = new UniversalNamespaceContextImpl(document, false);
219                         final EffectiveModelContext modelContext = schemaContext.getCurrentContext();
220                         final XmlCodecFactory xmlCodecFactory = XmlCodecFactory.create(modelContext);
221                         final TypeAwareCodec<?, NamespaceContext, XMLStreamWriter> typeCodec = xmlCodecFactory.codecFor(
222                             listKey, SchemaInferenceStack.ofInstantiatedPath(modelContext, listKey.getPath()));
223                         final Object deserializedKeyValue = typeCodec.parseValue(nsContext, keyValue.get());
224                         keys.put(qualifiedName, deserializedKeyValue);
225                     } else {
226                         final Object deserializedKey = TypeDefinitionAwareCodec.from(keyType)
227                                 .deserialize(keyValue.get());
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 }