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.server.mdsal.operations;
10 import static org.opendaylight.yangtools.yang.data.util.ParserStreamUtils.findSchemaNodeByNameAndNamespace;
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.Preconditions;
14 import java.io.Serial;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Deque;
18 import java.util.HashMap;
19 import java.util.List;
21 import javax.xml.namespace.NamespaceContext;
22 import javax.xml.stream.XMLStreamWriter;
23 import org.opendaylight.netconf.api.DocumentedException;
24 import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
25 import org.opendaylight.netconf.api.xml.XmlElement;
26 import org.opendaylight.netconf.server.mdsal.CurrentSchemaContext;
27 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
28 import org.opendaylight.yangtools.yang.common.ErrorTag;
29 import org.opendaylight.yangtools.yang.common.ErrorType;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.XMLNamespace;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
34 import org.opendaylight.yangtools.yang.data.codec.xml.XmlCodecFactory;
35 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
36 import org.opendaylight.yangtools.yang.data.util.codec.TypeAwareCodec;
37 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
40 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
45 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.w3c.dom.Document;
54 * Class validates filter content against schema context.
56 public class FilterContentValidator {
58 private static final Logger LOG = LoggerFactory.getLogger(FilterContentValidator.class);
59 private final CurrentSchemaContext schemaContext;
61 public FilterContentValidator(final CurrentSchemaContext schemaContext) {
62 this.schemaContext = schemaContext;
66 * Validates filter content against this validator schema context. If the filter is valid,
67 * method returns {@link YangInstanceIdentifier} of node which can be used as root for data selection.
69 * @param filterContent filter content
70 * @return YangInstanceIdentifier
71 * @throws DocumentedException if filter content validation failed
73 public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
74 final XMLNamespace namespace;
76 namespace = XMLNamespace.of(filterContent.getNamespace());
77 } catch (final IllegalArgumentException e) {
78 // FIXME: throw DocumentedException
79 throw new IllegalArgumentException("Wrong namespace in element + " + filterContent.toString(), e);
83 final Module module = schemaContext.getCurrentContext().findModules(namespace).iterator().next();
84 final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
85 final FilterTree filterTree = validateNode(
86 filterContent, schema, new FilterTree(schema.getQName(), Type.OTHER, schema));
87 return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
88 } catch (final ValidationException e) {
89 LOG.debug("Filter content isn't valid", e);
90 throw new DocumentedException("Validation failed. Cause: " + e.getMessage(), e,
91 ErrorType.APPLICATION, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
96 * Returns module's child data node of given name space and name.
98 * @param module module
99 * @param nameSpace name space
101 * @return child data node schema
102 * @throws DocumentedException if child with given name is not present
104 private DataSchemaNode getRootDataSchemaNode(final Module module, final XMLNamespace nameSpace, final String name)
105 throws DocumentedException {
106 for (final DataSchemaNode childNode : module.getChildNodes()) {
107 final QName qName = childNode.getQName();
108 if (qName.getNamespace().equals(nameSpace) && qName.getLocalName().equals(name)) {
112 throw new DocumentedException("Unable to find node with namespace: " + nameSpace + " in schema context: "
113 + schemaContext.getCurrentContext(),
114 ErrorType.APPLICATION, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
118 * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
120 * @param element element to check
121 * @param parentNodeSchema parent node schema
122 * @param tree parent node tree
124 * @throws ValidationException if filter content is not valid
126 private FilterTree validateNode(final XmlElement element, final DataSchemaNode parentNodeSchema,
127 final FilterTree tree) throws ValidationException {
128 for (final XmlElement childElement : element.getChildElements()) {
130 final Deque<DataSchemaNode> path = findSchemaNodeByNameAndNamespace(parentNodeSchema,
131 childElement.getName(), XMLNamespace.of(childElement.getNamespace()));
132 if (path.isEmpty()) {
133 throw new ValidationException(element, childElement);
135 FilterTree subtree = tree;
136 for (final DataSchemaNode dataSchemaNode : path) {
137 subtree = subtree.addChild(dataSchemaNode);
139 final DataSchemaNode childSchema = path.getLast();
140 validateNode(childElement, childSchema, subtree);
141 } catch (IllegalArgumentException | MissingNameSpaceException e) {
142 throw new IllegalArgumentException("Wrong namespace in element + " + childElement.toString(), e);
149 * Searches for YangInstanceIdentifier of node, which can be used as root for data selection.
150 * It goes as deep in tree as possible. Method stops traversing, when there are multiple child elements. If element
151 * represents list and child elements are key values, then it builds YangInstanceIdentifier of list entry.
153 * @param tree QName tree
154 * @param filterContent filter element
155 * @param builder builder @return YangInstanceIdentifier
157 private YangInstanceIdentifier getFilterDataRoot(final FilterTree tree, final XmlElement filterContent,
158 final InstanceIdentifierBuilder builder) {
159 builder.node(tree.getName());
160 final List<String> path = new ArrayList<>();
162 FilterTree current = tree;
163 while (current.size() == 1) {
164 final FilterTree child = current.getChildren().iterator().next();
165 if (child.getType() == Type.CHOICE_CASE) {
169 builder.node(child.getName());
170 path.add(child.getName().getLocalName());
171 if (child.getType() == Type.LIST) {
172 appendKeyIfPresent(current, child, filterContent, path, builder);
173 return builder.build();
177 return builder.build();
180 private void appendKeyIfPresent(final FilterTree parent, final FilterTree list, final XmlElement filterContent,
181 final List<String> pathToList, final InstanceIdentifierBuilder builder) {
182 Preconditions.checkArgument(list.getSchemaNode() instanceof ListSchemaNode);
183 final ListSchemaNode listSchemaNode = (ListSchemaNode) list.getSchemaNode();
184 final DataSchemaNode parentSchemaNode = parent.getSchemaNode();
186 final Map<QName, Object> map = getKeyValues(pathToList, filterContent, parentSchemaNode, listSchemaNode);
187 if (!map.isEmpty()) {
188 builder.nodeWithKey(list.getName(), map);
192 private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
193 final DataSchemaNode parentSchemaNode, final ListSchemaNode listSchemaNode) {
194 XmlElement current = filterContent;
196 for (final String pathElement : path) {
197 final List<XmlElement> childElements = current.getChildElements(pathElement);
198 // if there are multiple list entries present in the filter, we can't use any keys and must read whole list
199 if (childElements.size() != 1) {
202 current = childElements.get(0);
204 final Map<QName, Object> keys = new HashMap<>();
205 final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
206 for (final QName qualifiedName : keyDefinition) {
207 final var optChildElements = current.getOnlyChildElementOptionally(qualifiedName.getLocalName());
208 if (optChildElements.isEmpty()) {
211 optChildElements.orElseThrow().getOnlyTextContentOptionally().ifPresent(keyValue -> {
212 final LeafSchemaNode listKey = (LeafSchemaNode) listSchemaNode.getDataChildByName(qualifiedName);
213 if (listKey instanceof IdentityrefTypeDefinition) {
214 keys.put(qualifiedName, keyValue);
216 final TypeDefinition<? extends TypeDefinition<?>> keyType = listKey.getType();
217 if (keyType instanceof IdentityrefTypeDefinition || keyType instanceof LeafrefTypeDefinition
218 || keyType instanceof InstanceIdentifierTypeDefinition) {
219 final Document document = filterContent.getDomElement().getOwnerDocument();
220 final NamespaceContext nsContext = new UniversalNamespaceContextImpl(document, false);
221 final EffectiveModelContext modelContext = schemaContext.getCurrentContext();
222 final XmlCodecFactory xmlCodecFactory = XmlCodecFactory.create(modelContext);
223 final SchemaInferenceStack resolver = SchemaInferenceStack.of(modelContext, Absolute.of(
224 parentSchemaNode.getQName(), listSchemaNode.getQName(), listKey.getQName()));
225 final TypeAwareCodec<?, NamespaceContext, XMLStreamWriter> typeCodec = xmlCodecFactory
226 .codecFor(listKey, resolver);
227 final Object deserializedKeyValue = typeCodec.parseValue(nsContext, keyValue);
228 keys.put(qualifiedName, deserializedKeyValue);
230 final Object deserializedKey = TypeDefinitionAwareCodec.from(keyType).deserialize(keyValue);
231 keys.put(qualifiedName, deserializedKey);
240 LIST, CHOICE_CASE, OTHER
244 * Class represents tree of QNames as they are present in the filter.
246 private static final class FilterTree {
247 private final Map<QName, FilterTree> children = new HashMap<>();
248 private final DataSchemaNode schemaNode;
249 private final QName name;
250 private final Type type;
252 FilterTree(final QName name, final Type type, final DataSchemaNode schemaNode) {
255 this.schemaNode = schemaNode;
258 FilterTree addChild(final DataSchemaNode data) {
259 final Type childType;
260 if (data instanceof CaseSchemaNode) {
261 childType = Type.CHOICE_CASE;
262 } else if (data instanceof ListSchemaNode) {
263 childType = Type.LIST;
265 childType = Type.OTHER;
267 final QName childName = data.getQName();
268 FilterTree childTree = children.get(childName);
269 if (childTree == null) {
270 childTree = new FilterTree(childName, childType, data);
272 children.put(childName, childTree);
276 Collection<FilterTree> getChildren() {
277 return children.values();
288 DataSchemaNode getSchemaNode() {
293 return children.size();
297 public String toString() {
298 return MoreObjects.toStringHelper(this).add("name", name).add("type", type).add("size", size()).toString();
302 private static class ValidationException extends Exception {
304 private static final long serialVersionUID = 1L;
306 ValidationException(final XmlElement parent, final XmlElement child) {
307 super("Element " + child + " can't be child of " + parent);