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 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;
45 * Class validates filter content against schema context.
47 public class FilterContentValidator {
49 private static final Logger LOG = LoggerFactory.getLogger(FilterContentValidator.class);
50 private final CurrentSchemaContext schemaContext;
53 * @param schemaContext current schema context
55 public FilterContentValidator(final CurrentSchemaContext schemaContext) {
56 this.schemaContext = schemaContext;
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.
63 * @param filterContent filter content
64 * @return YangInstanceIdentifier
65 * @throws DocumentedException if filter content is not valid
67 public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
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(),
74 return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
75 } catch (final DocumentedException 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);
87 * Returns module's child data node of given name space and name
89 * @param module module
90 * @param nameSpace name space
92 * @return child data node schema
93 * @throws DocumentedException if child with given name is not present
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)) {
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);
112 * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
114 * @param element element to check
115 * @param parentNodeSchema parent node schema
116 * @param tree parent node tree
118 * @throws ValidationException if filter content is not valid
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) {
125 final Deque<DataSchemaNode> path = findSchemaNodeByNameAndNamespace(parentNodeSchema,
126 childElement.getName(), new URI(childElement.getNamespace()));
127 if (path.isEmpty()) {
128 throw new ValidationException(element, childElement);
130 FilterTree subtree = tree;
131 for (final DataSchemaNode dataSchemaNode : path) {
132 subtree = subtree.addChild(dataSchemaNode);
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());
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.
148 * @param tree QName tree
149 * @param filterContent filter element
150 * @param builder builder @return YangInstanceIdentifier
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) {
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();
170 return builder.build();
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();
179 final Map<QName, Object> map = getKeyValues(pathToList, filterContent, listSchemaNode);
180 if (!map.isEmpty()) {
181 builder.nodeWithKey(tree.getName(), map);
185 private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
186 final ListSchemaNode listSchemaNode) {
187 XmlElement current = filterContent;
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();
195 current = childElements.get(0);
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();
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());
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);
218 final Object deserializedKey = TypeDefinitionAwareCodec.from(listKey.getType())
219 .deserialize(keyValue.get());
220 keys.put(qName, deserializedKey);
229 * Class represents tree of QNames as they are present in the filter.
231 private static class FilterTree {
233 private final QName name;
234 private final Type type;
235 private final DataSchemaNode schemaNode;
236 private final Map<QName, FilterTree> children;
238 FilterTree(final QName name, final Type type, final DataSchemaNode schemaNode) {
241 this.schemaNode = schemaNode;
242 this.children = new HashMap<>();
245 FilterTree addChild(final DataSchemaNode data) {
247 if (data instanceof ChoiceCaseNode) {
248 type = Type.CHOICE_CASE;
249 } else if (data instanceof ListSchemaNode) {
254 final QName name = data.getQName();
255 FilterTree childTree = children.get(name);
256 if (childTree == null) {
257 childTree = new FilterTree(name, type, data);
259 children.put(name, childTree);
263 Collection<FilterTree> getChildren() {
264 return children.values();
275 DataSchemaNode getSchemaNode() {
281 LIST, CHOICE_CASE, OTHER
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);