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