dd1c41ebc9016e27eef0b59aa7d70de3b27c3567
[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         final Collection<DataSchemaNode> childNodes = module.getChildNodes();
98         for (final DataSchemaNode childNode : childNodes) {
99             final QName qName = childNode.getQName();
100             if (qName.getNamespace().equals(nameSpace) && qName.getLocalName().equals(name)) {
101                 return childNode;
102             }
103         }
104         throw new DocumentedException("Unable to find node with namespace: " + nameSpace
105                     + "in schema context: " + schemaContext.getCurrentContext().toString(),
106                 DocumentedException.ErrorType.APPLICATION,
107                 DocumentedException.ErrorTag.UNKNOWN_NAMESPACE,
108                 DocumentedException.ErrorSeverity.ERROR);
109     }
110
111     /**
112      * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
113      *
114      * @param element          element to check
115      * @param parentNodeSchema parent node schema
116      * @param tree             parent node tree
117      * @return tree
118      * @throws ValidationException if filter content is not valid
119      */
120     private FilterTree validateNode(final XmlElement element, final DataSchemaNode parentNodeSchema,
121                                     final FilterTree tree) throws ValidationException {
122         final List<XmlElement> childElements = element.getChildElements();
123         for (final XmlElement childElement : childElements) {
124             try {
125                 final Deque<DataSchemaNode> path = findSchemaNodeByNameAndNamespace(parentNodeSchema,
126                         childElement.getName(), new URI(childElement.getNamespace()));
127                 if (path.isEmpty()) {
128                     throw new ValidationException(element, childElement);
129                 }
130                 FilterTree subtree = tree;
131                 for (final DataSchemaNode dataSchemaNode : path) {
132                     subtree = subtree.addChild(dataSchemaNode);
133                 }
134                 final DataSchemaNode childSchema = path.getLast();
135                 validateNode(childElement, childSchema, subtree);
136             } catch (URISyntaxException | MissingNameSpaceException e) {
137                 throw new RuntimeException("Wrong namespace in element + " + childElement.toString(), e);
138             }
139         }
140         return tree;
141     }
142
143     /**
144      * Searches for YangInstanceIdentifier of node, which can be used as root for data selection.
145      * It goes as deep in tree as possible. Method stops traversing, when there are multiple child elements. If element
146      * represents list and child elements are key values, then it builds YangInstanceIdentifier of list entry.
147      *
148      * @param tree          QName tree
149      * @param filterContent filter element
150      * @param builder       builder  @return YangInstanceIdentifier
151      */
152     private YangInstanceIdentifier getFilterDataRoot(FilterTree tree, final XmlElement filterContent,
153                                                      final InstanceIdentifierBuilder builder) {
154         builder.node(tree.getName());
155         final List<String> path = new ArrayList<>();
156         while (tree.getChildren().size() == 1) {
157             final FilterTree child = tree.getChildren().iterator().next();
158             if (child.getType() == Type.CHOICE_CASE) {
159                 tree = child;
160                 continue;
161             }
162             builder.node(child.getName());
163             path.add(child.getName().getLocalName());
164             if (child.getType() == Type.LIST) {
165                 appendKeyIfPresent(child, filterContent, path, builder);
166                 return builder.build();
167             }
168             tree = child;
169         }
170         return builder.build();
171     }
172
173     private void appendKeyIfPresent(final FilterTree tree, final XmlElement filterContent,
174                                     final List<String> pathToList,
175                                     final InstanceIdentifierBuilder builder) {
176         Preconditions.checkArgument(tree.getSchemaNode() instanceof ListSchemaNode);
177         final ListSchemaNode listSchemaNode = (ListSchemaNode) tree.getSchemaNode();
178
179         final Map<QName, Object> map = getKeyValues(pathToList, filterContent, listSchemaNode);
180         if (!map.isEmpty()) {
181             builder.nodeWithKey(tree.getName(), map);
182         }
183     }
184
185     private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
186                                             final ListSchemaNode listSchemaNode) {
187         XmlElement current = filterContent;
188         //find list element
189         for (final String pathElement : path) {
190             final List<XmlElement> childElements = current.getChildElements(pathElement);
191             // if there are multiple list entries present in the filter, we can't use any keys and must read whole list
192             if (childElements.size() != 1) {
193                 return Collections.emptyMap();
194             }
195             current = childElements.get(0);
196         }
197         final Map<QName, Object> keys = new HashMap<>();
198         final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
199         for (final QName qualifiedName : keyDefinition) {
200             final Optional<XmlElement> childElements =
201                     current.getOnlyChildElementOptionally(qualifiedName.getLocalName());
202             if (!childElements.isPresent()) {
203                 return Collections.emptyMap();
204             }
205             final Optional<String> keyValue = childElements.get().getOnlyTextContentOptionally();
206             if (keyValue.isPresent()) {
207                 final LeafSchemaNode listKey = (LeafSchemaNode) listSchemaNode.getDataChildByName(qualifiedName);
208                 if (listKey instanceof IdentityrefTypeDefinition) {
209                     keys.put(qualifiedName, keyValue.get());
210                 } else {
211                     final TypeDefinition<? extends TypeDefinition<?>> keyType = listKey.getType();
212                     if (keyType instanceof IdentityrefTypeDefinition || keyType instanceof LeafrefTypeDefinition) {
213                         final Document document = filterContent.getDomElement().getOwnerDocument();
214                         final NamespaceContext nsContext = new UniversalNamespaceContextImpl(document, false);
215                         final XmlCodecFactory xmlCodecFactory =
216                                 XmlCodecFactory.create(schemaContext.getCurrentContext());
217                         final TypeAwareCodec<?, NamespaceContext, XMLStreamWriter> typeCodec =
218                                 xmlCodecFactory.codecFor(listKey);
219                         final Object deserializedKeyValue = typeCodec.parseValue(nsContext, keyValue.get());
220                         keys.put(qualifiedName, deserializedKeyValue);
221                     } else {
222                         final Object deserializedKey = TypeDefinitionAwareCodec.from(keyType)
223                                 .deserialize(keyValue.get());
224                         keys.put(qualifiedName, deserializedKey);
225                     }
226                 }
227             }
228         }
229         return keys;
230     }
231
232     private enum Type {
233         LIST, CHOICE_CASE, OTHER
234     }
235
236     /**
237      * Class represents tree of QNames as they are present in the filter.
238      */
239     private static class FilterTree {
240
241         private final QName name;
242         private final Type type;
243         private final DataSchemaNode schemaNode;
244         private final Map<QName, FilterTree> children;
245
246         FilterTree(final QName name, final Type type, final DataSchemaNode schemaNode) {
247             this.name = name;
248             this.type = type;
249             this.schemaNode = schemaNode;
250             this.children = new HashMap<>();
251         }
252
253         FilterTree addChild(final DataSchemaNode data) {
254             final Type childType;
255             if (data instanceof CaseSchemaNode) {
256                 childType = Type.CHOICE_CASE;
257             } else if (data instanceof ListSchemaNode) {
258                 childType = Type.LIST;
259             } else {
260                 childType = Type.OTHER;
261             }
262             final QName childName = data.getQName();
263             FilterTree childTree = children.get(childName);
264             if (childTree == null) {
265                 childTree = new FilterTree(childName, childType, data);
266             }
267             children.put(childName, childTree);
268             return childTree;
269         }
270
271         Collection<FilterTree> getChildren() {
272             return children.values();
273         }
274
275         QName getName() {
276             return name;
277         }
278
279         Type getType() {
280             return type;
281         }
282
283         DataSchemaNode getSchemaNode() {
284             return schemaNode;
285         }
286     }
287
288     private static class ValidationException extends Exception {
289         private static final long serialVersionUID = 1L;
290
291         ValidationException(final XmlElement parent, final XmlElement child) {
292             super("Element " + child + " can't be child of " + parent);
293         }
294     }
295
296 }