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;
52 public FilterContentValidator(final CurrentSchemaContext schemaContext) {
53 this.schemaContext = schemaContext;
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.
60 * @param filterContent filter content
61 * @return YangInstanceIdentifier
62 * @throws DocumentedException if filter content validation failed
64 public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
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);
84 * Returns module's child data node of given name space and name.
86 * @param module module
87 * @param nameSpace name space
89 * @return child data node schema
90 * @throws DocumentedException if child with given name is not present
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)) {
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);
109 * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
111 * @param element element to check
112 * @param parentNodeSchema parent node schema
113 * @param tree parent node tree
115 * @throws ValidationException if filter content is not valid
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) {
122 final Deque<DataSchemaNode> path = findSchemaNodeByNameAndNamespace(parentNodeSchema,
123 childElement.getName(), new URI(childElement.getNamespace()));
124 if (path.isEmpty()) {
125 throw new ValidationException(element, childElement);
127 FilterTree subtree = tree;
128 for (final DataSchemaNode dataSchemaNode : path) {
129 subtree = subtree.addChild(dataSchemaNode);
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());
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.
145 * @param tree QName tree
146 * @param filterContent filter element
147 * @param builder builder @return YangInstanceIdentifier
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) {
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();
167 return builder.build();
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();
176 final Map<QName, Object> map = getKeyValues(pathToList, filterContent, listSchemaNode);
177 if (!map.isEmpty()) {
178 builder.nodeWithKey(tree.getName(), map);
182 private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
183 final ListSchemaNode listSchemaNode) {
184 XmlElement current = filterContent;
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();
192 current = childElements.get(0);
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();
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());
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);
218 final Object deserializedKey = TypeDefinitionAwareCodec.from(listKey.getType())
219 .deserialize(keyValue.get());
220 keys.put(qualifiedName, deserializedKey);
229 LIST, CHOICE_CASE, OTHER
233 * Class represents tree of QNames as they are present in the filter.
235 private static class FilterTree {
237 private final QName name;
238 private final Type type;
239 private final DataSchemaNode schemaNode;
240 private final Map<QName, FilterTree> children;
242 FilterTree(final QName name, final Type type, final DataSchemaNode schemaNode) {
245 this.schemaNode = schemaNode;
246 this.children = new HashMap<>();
249 FilterTree addChild(final DataSchemaNode data) {
251 if (data instanceof ChoiceCaseNode) {
252 type = Type.CHOICE_CASE;
253 } else if (data instanceof ListSchemaNode) {
258 final QName name = data.getQName();
259 FilterTree childTree = children.get(name);
260 if (childTree == null) {
261 childTree = new FilterTree(name, type, data);
263 children.put(name, childTree);
267 Collection<FilterTree> getChildren() {
268 return children.values();
279 DataSchemaNode getSchemaNode() {
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);