2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.mdsal.connector.ops.get;
10 import static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
11 import static org.opendaylight.yangtools.yang.data.util.ParserStreamUtils.findSchemaNodeByNameAndNamespace;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
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;
24 import org.opendaylight.controller.config.util.xml.DocumentedException;
25 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
26 import org.opendaylight.controller.config.util.xml.XmlElement;
27 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
31 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.Module;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
38 * Class validates filter content against schema context.
40 public class FilterContentValidator {
42 private static final Logger LOG = LoggerFactory.getLogger(FilterContentValidator.class);
43 private final CurrentSchemaContext schemaContext;
46 * @param schemaContext current schema context
48 public FilterContentValidator(final CurrentSchemaContext schemaContext) {
49 this.schemaContext = schemaContext;
53 * Validates filter content against this validator schema context. If the filter is valid,
54 * method returns {@link YangInstanceIdentifier} of node which can be used as root for data selection.
55 * @param filterContent filter content
56 * @return YangInstanceIdentifier
57 * @throws DocumentedException if filter content is not valid
59 public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
61 final URI namespace = new URI(filterContent.getNamespace());
62 final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespace, null);
63 final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
64 final FilterTree filterTree = validateNode(filterContent, schema, new FilterTree(schema.getQName(),
66 return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
67 } catch (final DocumentedException e) {
69 } catch (final Exception e) {
70 LOG.debug("Filter content isn't valid", e);
71 throw new DocumentedException("Validation failed. Cause: " + e.getMessage(),
72 DocumentedException.ErrorType.APPLICATION,
73 DocumentedException.ErrorTag.UNKNOWN_NAMESPACE,
74 DocumentedException.ErrorSeverity.ERROR);
79 * Returns module's child data node of given name space and name
80 * @param module module
81 * @param nameSpace name space
83 * @return child data node schema
84 * @throws DocumentedException if child with given name is not present
86 private DataSchemaNode getRootDataSchemaNode(final Module module, final URI nameSpace, final String name)
87 throws DocumentedException {
88 final Collection<DataSchemaNode> childNodes = module.getChildNodes();
89 for (final DataSchemaNode childNode : childNodes) {
90 final QName qName = childNode.getQName();
91 if (qName.getNamespace().equals(nameSpace) && qName.getLocalName().equals(name)) {
95 throw new DocumentedException("Unable to find node with namespace: " + nameSpace + "in schema context: " +
96 schemaContext.getCurrentContext().toString(),
97 DocumentedException.ErrorType.APPLICATION,
98 DocumentedException.ErrorTag.UNKNOWN_NAMESPACE,
99 DocumentedException.ErrorSeverity.ERROR);
103 * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
104 * @param element element to check
105 * @param parentNodeSchema parent node schema
106 * @param tree parent node tree
108 * @throws ValidationException if filter content is not valid
110 private FilterTree validateNode(final XmlElement element, final DataSchemaNode parentNodeSchema,
111 final FilterTree tree) throws ValidationException {
112 final List<XmlElement> childElements = element.getChildElements();
113 for (final XmlElement childElement : childElements) {
115 final Deque<DataSchemaNode> path = findSchemaNodeByNameAndNamespace(parentNodeSchema,
116 childElement.getName(), new URI(childElement.getNamespace()));
117 if (path.isEmpty()) {
118 throw new ValidationException(element, childElement);
120 FilterTree subtree = tree;
121 for (final DataSchemaNode dataSchemaNode : path) {
122 subtree = subtree.addChild(dataSchemaNode);
124 final DataSchemaNode childSchema = path.getLast();
125 validateNode(childElement, childSchema, subtree);
126 } catch (URISyntaxException | MissingNameSpaceException e) {
127 throw new RuntimeException("Wrong namespace in element + " + childElement.toString());
134 * Searches for YangInstanceIdentifier of node, which can be used as root for data selection.
135 * It goes as deep in tree as possible. Method stops traversing, when there are multiple child elements. If element
136 * represents list and child elements are key values, then it builds YangInstanceIdentifier of list entry.
137 * @param tree QName tree
138 * @param filterContent filter element
139 * @param builder builder @return YangInstanceIdentifier
141 private YangInstanceIdentifier getFilterDataRoot(FilterTree tree, final XmlElement filterContent,
142 final InstanceIdentifierBuilder builder) {
143 builder.node(tree.getName());
144 final List<String> path = new ArrayList<>();
145 while (tree.getChildren().size() == 1) {
146 final FilterTree child = tree.getChildren().iterator().next();
147 if (child.getType() == Type.CHOICE_CASE) {
151 builder.node(child.getName());
152 path.add(child.getName().getLocalName());
153 if (child.getType() == Type.LIST) {
154 appendKeyIfPresent(child, filterContent, path, builder);
155 return builder.build();
159 return builder.build();
162 private void appendKeyIfPresent(final FilterTree tree, final XmlElement filterContent,
163 final List<String> pathToList,
164 final InstanceIdentifierBuilder builder) {
165 Preconditions.checkArgument(tree.getSchemaNode() instanceof ListSchemaNode);
166 final ListSchemaNode listSchemaNode = (ListSchemaNode) tree.getSchemaNode();
167 final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
168 final Map<QName, Object> map = getKeyValues(pathToList, filterContent, keyDefinition);
169 if (!map.isEmpty()) {
170 builder.nodeWithKey(tree.getName(), map);
174 private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
175 final List<QName> keyDefinition) {
176 XmlElement current = filterContent;
178 for (final String pathElement : path) {
179 final List<XmlElement> childElements = current.getChildElements(pathElement);
180 // if there are multiple list entries present in the filter, we can't use any keys and must read whole list
181 if (childElements.size() != 1) {
182 return Collections.emptyMap();
184 current = childElements.get(0);
186 final Map<QName, Object> keys = new HashMap<>();
187 for (final QName qName : keyDefinition) {
188 final Optional<XmlElement> childElements = current.getOnlyChildElementOptionally(qName.getLocalName());
189 if (!childElements.isPresent()) {
190 return Collections.emptyMap();
192 final Optional<String> keyValue = childElements.get().getOnlyTextContentOptionally();
193 if (keyValue.isPresent()) {
194 keys.put(qName, keyValue.get());
201 * Class represents tree of QNames as they are present in the filter.
203 private static class FilterTree {
205 private final QName name;
206 private final Type type;
207 private final DataSchemaNode schemaNode;
208 private final Map<QName, FilterTree> children;
210 FilterTree(final QName name, final Type type, final DataSchemaNode schemaNode) {
213 this.schemaNode = schemaNode;
214 this.children = new HashMap<>();
217 FilterTree addChild(final DataSchemaNode data) {
219 if (data instanceof ChoiceCaseNode) {
220 type = Type.CHOICE_CASE;
221 } else if (data instanceof ListSchemaNode) {
226 final QName name = data.getQName();
227 FilterTree childTree = children.get(name);
228 if (childTree == null) {
229 childTree = new FilterTree(name, type, data);
231 children.put(name, childTree);
235 Collection<FilterTree> getChildren() {
236 return children.values();
247 DataSchemaNode getSchemaNode() {
253 LIST, CHOICE_CASE, OTHER
256 private static class ValidationException extends Exception {
257 public ValidationException(final XmlElement parent, final XmlElement child) {
258 super("Element " + child + " can't be child of " + parent);