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.netconf.api.DocumentedException;
26 import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
27 import org.opendaylight.netconf.api.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.CaseSchemaNode;
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.TypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.w3c.dom.Document;
48 * Class validates filter content against schema context.
50 public class FilterContentValidator {
52 private static final Logger LOG = LoggerFactory.getLogger(FilterContentValidator.class);
53 private final CurrentSchemaContext schemaContext;
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 validation failed
67 public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
69 final URI namespace = new URI(filterContent.getNamespace());
70 final Module module = schemaContext.getCurrentContext().findModules(namespace).iterator().next();
71 final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
72 final FilterTree filterTree = validateNode(
73 filterContent, schema, new FilterTree(schema.getQName(), Type.OTHER, schema));
74 return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
75 } catch (final URISyntaxException e) {
76 throw new RuntimeException("Wrong namespace in element + " + filterContent.toString(), e);
77 } catch (final ValidationException e) {
78 LOG.debug("Filter content isn't valid", e);
79 throw new DocumentedException("Validation failed. Cause: " + e.getMessage(), e,
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
105 + "in schema context: " + 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(), e);
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 qualifiedName : keyDefinition) {
200 final Optional<XmlElement> childElements =
201 current.getOnlyChildElementOptionally(qualifiedName.getLocalName());
202 if (!childElements.isPresent()) {
203 return Collections.emptyMap();
205 final Optional<String> keyValue = childElements.get().getOnlyTextContentOptionally();
206 if (keyValue.isPresent()) {
207 final LeafSchemaNode listKey = (LeafSchemaNode) listSchemaNode.getDataChildByName(qualifiedName);
208 if (listKey instanceof IdentityrefTypeDefinition) {
209 keys.put(qualifiedName, keyValue.get());
211 final TypeDefinition<? extends TypeDefinition<?>> keyType = listKey.getType();
212 if (keyType instanceof IdentityrefTypeDefinition || keyType instanceof LeafrefTypeDefinition) {
213 final Document document = filterContent.getDomElement().getOwnerDocument();
214 final NamespaceContext nsContext = new UniversalNamespaceContextImpl(document, false);
215 final XmlCodecFactory xmlCodecFactory =
216 XmlCodecFactory.create(schemaContext.getCurrentContext());
217 final TypeAwareCodec<?, NamespaceContext, XMLStreamWriter> typeCodec =
218 xmlCodecFactory.codecFor(listKey);
219 final Object deserializedKeyValue = typeCodec.parseValue(nsContext, keyValue.get());
220 keys.put(qualifiedName, deserializedKeyValue);
222 final Object deserializedKey = TypeDefinitionAwareCodec.from(keyType)
223 .deserialize(keyValue.get());
224 keys.put(qualifiedName, deserializedKey);
233 LIST, CHOICE_CASE, OTHER
237 * Class represents tree of QNames as they are present in the filter.
239 private static class FilterTree {
241 private final QName name;
242 private final Type type;
243 private final DataSchemaNode schemaNode;
244 private final Map<QName, FilterTree> children;
246 FilterTree(final QName name, final Type type, final DataSchemaNode schemaNode) {
249 this.schemaNode = schemaNode;
250 this.children = new HashMap<>();
253 FilterTree addChild(final DataSchemaNode data) {
254 final Type childType;
255 if (data instanceof CaseSchemaNode) {
256 childType = Type.CHOICE_CASE;
257 } else if (data instanceof ListSchemaNode) {
258 childType = Type.LIST;
260 childType = Type.OTHER;
262 final QName childName = data.getQName();
263 FilterTree childTree = children.get(childName);
264 if (childTree == null) {
265 childTree = new FilterTree(childName, childType, data);
267 children.put(childName, childTree);
271 Collection<FilterTree> getChildren() {
272 return children.values();
283 DataSchemaNode getSchemaNode() {
288 private static class ValidationException extends Exception {
289 private static final long serialVersionUID = 1L;
291 ValidationException(final XmlElement parent, final XmlElement child) {
292 super("Element " + child + " can't be child of " + parent);