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.util.ParserStreamUtils.findSchemaNodeByNameAndNamespace;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
15 import java.net.URISyntaxException;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Deque;
20 import java.util.HashMap;
21 import java.util.List;
23 import javax.xml.namespace.NamespaceContext;
24 import javax.xml.stream.XMLStreamWriter;
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.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
32 import org.opendaylight.yangtools.yang.data.codec.xml.XmlCodecFactory;
33 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
34 import org.opendaylight.yangtools.yang.data.util.codec.TypeAwareCodec;
35 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.Module;
40 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Document;
46 * Class validates filter content against schema context.
48 public class FilterContentValidator {
50 private static final Logger LOG = LoggerFactory.getLogger(FilterContentValidator.class);
51 private final CurrentSchemaContext schemaContext;
53 public FilterContentValidator(final CurrentSchemaContext schemaContext) {
54 this.schemaContext = schemaContext;
58 * Validates filter content against this validator schema context. If the filter is valid,
59 * method returns {@link YangInstanceIdentifier} of node which can be used as root for data selection.
61 * @param filterContent filter content
62 * @return YangInstanceIdentifier
63 * @throws DocumentedException if filter content validation failed
65 public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
67 final URI namespace = new URI(filterContent.getNamespace());
68 final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespace, null);
69 final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
70 final FilterTree filterTree = validateNode(
71 filterContent, schema, new FilterTree(schema.getQName(), Type.OTHER, schema));
72 return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
73 } catch (final URISyntaxException e) {
74 throw new RuntimeException("Wrong namespace in element + " + filterContent.toString());
75 } catch (final ValidationException e) {
76 LOG.debug("Filter content isn't valid", e);
77 throw new DocumentedException("Validation failed. Cause: " + e.getMessage(),
78 DocumentedException.ErrorType.APPLICATION,
79 DocumentedException.ErrorTag.UNKNOWN_NAMESPACE,
80 DocumentedException.ErrorSeverity.ERROR);
85 * Returns module's child data node of given name space and name.
87 * @param module module
88 * @param nameSpace name space
90 * @return child data node schema
91 * @throws DocumentedException if child with given name is not present
93 private DataSchemaNode getRootDataSchemaNode(final Module module, final URI nameSpace, final String name)
94 throws DocumentedException {
95 final Collection<DataSchemaNode> childNodes = module.getChildNodes();
96 for (final DataSchemaNode childNode : childNodes) {
97 final QName qName = childNode.getQName();
98 if (qName.getNamespace().equals(nameSpace) && qName.getLocalName().equals(name)) {
102 throw new DocumentedException("Unable to find node with namespace: " + nameSpace
103 + "in schema context: " + schemaContext.getCurrentContext().toString(),
104 DocumentedException.ErrorType.APPLICATION,
105 DocumentedException.ErrorTag.UNKNOWN_NAMESPACE,
106 DocumentedException.ErrorSeverity.ERROR);
110 * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
112 * @param element element to check
113 * @param parentNodeSchema parent node schema
114 * @param tree parent node tree
116 * @throws ValidationException if filter content is not valid
118 private FilterTree validateNode(final XmlElement element, final DataSchemaNode parentNodeSchema,
119 final FilterTree tree) throws ValidationException {
120 final List<XmlElement> childElements = element.getChildElements();
121 for (final XmlElement childElement : childElements) {
123 final Deque<DataSchemaNode> path = findSchemaNodeByNameAndNamespace(parentNodeSchema,
124 childElement.getName(), new URI(childElement.getNamespace()));
125 if (path.isEmpty()) {
126 throw new ValidationException(element, childElement);
128 FilterTree subtree = tree;
129 for (final DataSchemaNode dataSchemaNode : path) {
130 subtree = subtree.addChild(dataSchemaNode);
132 final DataSchemaNode childSchema = path.getLast();
133 validateNode(childElement, childSchema, subtree);
134 } catch (URISyntaxException | MissingNameSpaceException e) {
135 throw new RuntimeException("Wrong namespace in element + " + childElement.toString());
142 * Searches for YangInstanceIdentifier of node, which can be used as root for data selection.
143 * It goes as deep in tree as possible. Method stops traversing, when there are multiple child elements. If element
144 * represents list and child elements are key values, then it builds YangInstanceIdentifier of list entry.
146 * @param tree QName tree
147 * @param filterContent filter element
148 * @param builder builder @return YangInstanceIdentifier
150 private YangInstanceIdentifier getFilterDataRoot(FilterTree tree, final XmlElement filterContent,
151 final InstanceIdentifierBuilder builder) {
152 builder.node(tree.getName());
153 final List<String> path = new ArrayList<>();
154 while (tree.getChildren().size() == 1) {
155 final FilterTree child = tree.getChildren().iterator().next();
156 if (child.getType() == Type.CHOICE_CASE) {
160 builder.node(child.getName());
161 path.add(child.getName().getLocalName());
162 if (child.getType() == Type.LIST) {
163 appendKeyIfPresent(child, filterContent, path, builder);
164 return builder.build();
168 return builder.build();
171 private void appendKeyIfPresent(final FilterTree tree, final XmlElement filterContent,
172 final List<String> pathToList,
173 final InstanceIdentifierBuilder builder) {
174 Preconditions.checkArgument(tree.getSchemaNode() instanceof ListSchemaNode);
175 final ListSchemaNode listSchemaNode = (ListSchemaNode) tree.getSchemaNode();
177 final Map<QName, Object> map = getKeyValues(pathToList, filterContent, listSchemaNode);
178 if (!map.isEmpty()) {
179 builder.nodeWithKey(tree.getName(), map);
183 private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
184 final ListSchemaNode listSchemaNode) {
185 XmlElement current = filterContent;
187 for (final String pathElement : path) {
188 final List<XmlElement> childElements = current.getChildElements(pathElement);
189 // if there are multiple list entries present in the filter, we can't use any keys and must read whole list
190 if (childElements.size() != 1) {
191 return Collections.emptyMap();
193 current = childElements.get(0);
195 final Map<QName, Object> keys = new HashMap<>();
196 final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
197 for (final QName qualifiedName : keyDefinition) {
198 final Optional<XmlElement> childElements =
199 current.getOnlyChildElementOptionally(qualifiedName.getLocalName());
200 if (!childElements.isPresent()) {
201 return Collections.emptyMap();
203 final Optional<String> keyValue = childElements.get().getOnlyTextContentOptionally();
204 if (keyValue.isPresent()) {
205 final LeafSchemaNode listKey = (LeafSchemaNode) listSchemaNode.getDataChildByName(qualifiedName);
206 if (listKey instanceof IdentityrefTypeDefinition) {
207 keys.put(qualifiedName, keyValue.get());
209 if (listKey.getType() instanceof IdentityrefTypeDefinition) {
210 final Document document = filterContent.getDomElement().getOwnerDocument();
211 final NamespaceContext nsContext = new UniversalNamespaceContextImpl(document, false);
212 final XmlCodecFactory xmlCodecFactory =
213 XmlCodecFactory.create(schemaContext.getCurrentContext());
214 final TypeAwareCodec<?, NamespaceContext, XMLStreamWriter> identityrefTypeCodec =
215 xmlCodecFactory.codecFor(listKey);
216 final QName deserializedKey =
217 (QName) identityrefTypeCodec.parseValue(nsContext, keyValue.get());
218 keys.put(qualifiedName, deserializedKey);
220 final Object deserializedKey = TypeDefinitionAwareCodec.from(listKey.getType())
221 .deserialize(keyValue.get());
222 keys.put(qualifiedName, deserializedKey);
231 LIST, CHOICE_CASE, OTHER
235 * Class represents tree of QNames as they are present in the filter.
237 private static class FilterTree {
239 private final QName name;
240 private final Type type;
241 private final DataSchemaNode schemaNode;
242 private final Map<QName, FilterTree> children;
244 FilterTree(final QName name, final Type type, final DataSchemaNode schemaNode) {
247 this.schemaNode = schemaNode;
248 this.children = new HashMap<>();
251 FilterTree addChild(final DataSchemaNode data) {
253 if (data instanceof ChoiceCaseNode) {
254 type = Type.CHOICE_CASE;
255 } else if (data instanceof ListSchemaNode) {
260 final QName name = data.getQName();
261 FilterTree childTree = children.get(name);
262 if (childTree == null) {
263 childTree = new FilterTree(name, type, data);
265 children.put(name, childTree);
269 Collection<FilterTree> getChildren() {
270 return children.values();
281 DataSchemaNode getSchemaNode() {
286 private static class ValidationException extends Exception {
287 private static final long serialVersionUID = 1L;
289 ValidationException(final XmlElement parent, final XmlElement child) {
290 super("Element " + child + " can't be child of " + parent);