Merge "Do not use InetAddress.getByName()"
[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     /**
53      * @param schemaContext current schema context
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 is not valid
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().findModuleByNamespaceAndRevision(namespace, null);
71             final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
72             final FilterTree filterTree = validateNode(filterContent, schema, new FilterTree(schema.getQName(),
73                     Type.OTHER, schema));
74             return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
75         } catch (final DocumentedException e) {
76             throw e;
77         } catch (final Exception e) {
78             LOG.debug("Filter content isn't valid", e);
79             throw new DocumentedException("Validation failed. Cause: " + e.getMessage(),
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 + "in schema context: " +
105                 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());
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 qName : keyDefinition) {
200             final Optional<XmlElement> childElements = current.getOnlyChildElementOptionally(qName.getLocalName());
201             if (!childElements.isPresent()) {
202                 return Collections.emptyMap();
203             }
204             final Optional<String> keyValue = childElements.get().getOnlyTextContentOptionally();
205             if (keyValue.isPresent()) {
206                 final LeafSchemaNode listKey = (LeafSchemaNode) listSchemaNode.getDataChildByName(qName);
207                 if (listKey instanceof IdentityrefTypeDefinition) {
208                     keys.put(qName, keyValue.get());
209                 } else {
210                     if (listKey.getType() instanceof IdentityrefTypeDefinition) {
211                         final Document document = filterContent.getDomElement().getOwnerDocument();
212                         final NamespaceContext nsContext = new UniversalNamespaceContextImpl(document, false);
213                         final XmlCodecFactory xmlCodecFactory = XmlCodecFactory.create(schemaContext.getCurrentContext());
214                         final TypeAwareCodec identityrefTypeCodec = xmlCodecFactory.codecFor(listKey);
215                         final QName deserializedKey = (QName) identityrefTypeCodec.parseValue(nsContext, keyValue.get());
216                         keys.put(qName, deserializedKey);
217                     } else {
218                         final Object deserializedKey = TypeDefinitionAwareCodec.from(listKey.getType())
219                                 .deserialize(keyValue.get());
220                         keys.put(qName, deserializedKey);
221                     }
222                 }
223             }
224         }
225         return keys;
226     }
227
228     /**
229      * Class represents tree of QNames as they are present in the filter.
230      */
231     private static class FilterTree {
232
233         private final QName name;
234         private final Type type;
235         private final DataSchemaNode schemaNode;
236         private final Map<QName, FilterTree> children;
237
238         FilterTree(final QName name, final Type type, final DataSchemaNode schemaNode) {
239             this.name = name;
240             this.type = type;
241             this.schemaNode = schemaNode;
242             this.children = new HashMap<>();
243         }
244
245         FilterTree addChild(final DataSchemaNode data) {
246             final Type type;
247             if (data instanceof ChoiceCaseNode) {
248                 type = Type.CHOICE_CASE;
249             } else if (data instanceof ListSchemaNode) {
250                 type = Type.LIST;
251             } else {
252                 type = Type.OTHER;
253             }
254             final QName name = data.getQName();
255             FilterTree childTree = children.get(name);
256             if (childTree == null) {
257                 childTree = new FilterTree(name, type, data);
258             }
259             children.put(name, childTree);
260             return childTree;
261         }
262
263         Collection<FilterTree> getChildren() {
264             return children.values();
265         }
266
267         QName getName() {
268             return name;
269         }
270
271         Type getType() {
272             return type;
273         }
274
275         DataSchemaNode getSchemaNode() {
276             return schemaNode;
277         }
278     }
279
280     private enum Type {
281         LIST, CHOICE_CASE, OTHER
282     }
283
284     private static class ValidationException extends Exception {
285         public ValidationException(final XmlElement parent, final XmlElement child) {
286             super("Element " + child + " can't be child of " + parent);
287         }
288     }
289
290 }