Split out ApiPathCanonizer
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / utils / parser / NetconfFieldsTranslator.java
1 /*
2  * Copyright © 2020 FRINX s.r.o. and others.  All rights reserved.
3  * Copyright © 2021 PANTHEON.tech, s.r.o.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9 package org.opendaylight.restconf.nb.rfc8040.utils.parser;
10
11 import static java.util.Objects.requireNonNull;
12
13 import java.util.ArrayList;
14 import java.util.HashSet;
15 import java.util.LinkedList;
16 import java.util.List;
17 import java.util.Set;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
21 import org.opendaylight.restconf.api.query.FieldsParam;
22 import org.opendaylight.restconf.api.query.FieldsParam.NodeSelector;
23 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
24 import org.opendaylight.yangtools.yang.common.Empty;
25 import org.opendaylight.yangtools.yang.common.ErrorTag;
26 import org.opendaylight.yangtools.yang.common.ErrorType;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.common.QNameModule;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
33 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
34 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext.PathMixin;
35 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
36 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
38
39 /**
40  * A translator between {@link FieldsParam} and {@link YangInstanceIdentifier}s suitable for use as field identifiers
41  * in {@code netconf-dom-api}.
42  *
43  * <p>
44  * Fields parser that stores a set of all the leaf {@link LinkedPathElement}s specified in {@link FieldsParam}.
45  * Using {@link LinkedPathElement} it is possible to create a chain of path arguments and build complete paths
46  * since this element contains identifiers of intermediary mixin nodes and also linked to its parent
47  * {@link LinkedPathElement}.
48  *
49  * <p>
50  * Example: field 'a(b/c;d/e)' ('e' is place under choice node 'x') is parsed into following levels:
51  * <pre>
52  *   - './a' +- 'a/b' - 'b/c'
53  *           |
54  *           +- 'a/d' - 'd/x/e'
55  * </pre>
56  */
57 public final class NetconfFieldsTranslator {
58     /**
59      * {@link DataSchemaContext} of data element grouped with identifiers of leading mixin nodes and previous path
60      * element.<br>
61      *  - identifiers of mixin nodes on the path to the target node - required for construction of full valid
62      *    DOM paths,<br>
63      *  - {@link LinkedPathElement} of the previous non-mixin node - required to successfully create a chain
64      *    of {@link PathArgument}s
65      *
66      * @param parentPathElement     parent path element
67      * @param mixinNodesToTarget    identifiers of mixin nodes on the path to the target node
68      * @param targetNode            target non-mixin node
69      */
70     private record LinkedPathElement(
71             @Nullable LinkedPathElement parentPathElement,
72             @NonNull List<PathArgument> mixinNodesToTarget,
73             @NonNull DataSchemaContext targetNode) {
74         LinkedPathElement {
75             requireNonNull(mixinNodesToTarget);
76             requireNonNull(targetNode);
77         }
78     }
79
80     private NetconfFieldsTranslator() {
81         // Hidden on purpose
82     }
83
84     /**
85      * Translate a {@link FieldsParam} to a list of child node paths saved in lists, suitable for use with
86      * {@link NetconfDataTreeService}.
87      *
88      * @param modelContext EffectiveModelContext
89      * @param startNode Root DataSchemaNode
90      * @param input input value of fields parameter
91      * @return {@link List} of {@link YangInstanceIdentifier} that are relative to the last {@link PathArgument}
92      *         of provided {@code identifier}
93      */
94     public static @NonNull List<YangInstanceIdentifier> translate(
95             final @NonNull EffectiveModelContext modelContext, final @NonNull DataSchemaContext startNode,
96             final @NonNull FieldsParam input) {
97         final var parsed = new HashSet<LinkedPathElement>();
98         processSelectors(parsed, modelContext, startNode.dataSchemaNode().getQName().getModule(),
99             new LinkedPathElement(null, List.of(), startNode), input.nodeSelectors());
100         return parsed.stream().map(NetconfFieldsTranslator::buildPath).toList();
101     }
102
103     private static void processSelectors(final Set<LinkedPathElement> parsed, final EffectiveModelContext context,
104             final QNameModule startNamespace, final LinkedPathElement startPathElement,
105             final List<NodeSelector> selectors) {
106         for (var selector : selectors) {
107             var pathElement = startPathElement;
108             var namespace = startNamespace;
109
110             // Note: path is guaranteed to have at least one step
111             final var it = selector.path().iterator();
112             do {
113                 final var step = it.next();
114                 final var module = step.module();
115                 if (module != null) {
116                     // FIXME: this is not defensive enough, as we can fail to find the module
117                     namespace = context.findModules(module).iterator().next().getQNameModule();
118                 }
119
120                 // add parsed path element linked to its parent
121                 pathElement = addChildPathElement(pathElement, step.identifier().bindTo(namespace));
122             } while (it.hasNext());
123
124             final var subs = selector.subSelectors();
125             if (!subs.isEmpty()) {
126                 processSelectors(parsed, context, namespace, pathElement, subs);
127             } else {
128                 parsed.add(pathElement);
129             }
130         }
131     }
132
133     private static LinkedPathElement addChildPathElement(final LinkedPathElement currentElement,
134             final QName childQName) {
135         final var collectedMixinNodes = new ArrayList<PathArgument>();
136
137         DataSchemaContext currentNode = currentElement.targetNode;
138         DataSchemaContext actualContextNode = childByQName(currentNode, childQName);
139         if (actualContextNode == null) {
140             actualContextNode = resolveMixinNode(currentNode, currentNode.getPathStep().getNodeType());
141             actualContextNode = childByQName(actualContextNode, childQName);
142         }
143
144         while (actualContextNode != null && actualContextNode instanceof PathMixin) {
145             final var actualDataSchemaNode = actualContextNode.dataSchemaNode();
146             if (actualDataSchemaNode instanceof ListSchemaNode listSchema && listSchema.getKeyDefinition().isEmpty()) {
147                 // we need just a single node identifier from list in the path IFF it is an unkeyed list, otherwise
148                 // we need both (which is the default case)
149                 actualContextNode = childByQName(actualContextNode, childQName);
150             } else if (actualDataSchemaNode instanceof LeafListSchemaNode) {
151                 // NodeWithValue is unusable - stop parsing
152                 break;
153             } else {
154                 collectedMixinNodes.add(actualContextNode.getPathStep());
155                 actualContextNode = childByQName(actualContextNode, childQName);
156             }
157         }
158
159         if (actualContextNode == null) {
160             throw new RestconfDocumentedException("Child " + childQName.getLocalName() + " node missing in "
161                 + currentNode.getPathStep().getNodeType().getLocalName(),
162                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
163         }
164
165         return new LinkedPathElement(currentElement, collectedMixinNodes, actualContextNode);
166     }
167
168     private static @Nullable DataSchemaContext childByQName(final DataSchemaContext parent, final QName qname) {
169         return parent instanceof DataSchemaContext.Composite composite ? composite.childByQName(qname) : null;
170     }
171
172     private static YangInstanceIdentifier buildPath(final LinkedPathElement lastPathElement) {
173         LinkedPathElement pathElement = lastPathElement;
174         final var path = new LinkedList<PathArgument>();
175         do {
176             path.addFirst(contextPathArgument(pathElement.targetNode));
177             path.addAll(0, pathElement.mixinNodesToTarget);
178             pathElement = pathElement.parentPathElement;
179         } while (pathElement.parentPathElement != null);
180
181         return YangInstanceIdentifier.of(path);
182     }
183
184     private static @NonNull PathArgument contextPathArgument(final DataSchemaContext context) {
185         final var arg = context.pathStep();
186         if (arg != null) {
187             return arg;
188         }
189
190         final var schema = context.dataSchemaNode();
191         if (schema instanceof ListSchemaNode listSchema && !listSchema.getKeyDefinition().isEmpty()) {
192             return NodeIdentifierWithPredicates.of(listSchema.getQName());
193         }
194         if (schema instanceof LeafListSchemaNode leafListSchema) {
195             return new NodeWithValue<>(leafListSchema.getQName(), Empty.value());
196         }
197         throw new UnsupportedOperationException("Unsupported schema " + schema);
198     }
199
200     private static DataSchemaContext resolveMixinNode(final DataSchemaContext node,
201             final @NonNull QName qualifiedName) {
202         DataSchemaContext currentNode = node;
203         while (currentNode != null && currentNode instanceof PathMixin currentMixin) {
204             currentNode = currentMixin.childByQName(qualifiedName);
205         }
206         return currentNode;
207     }
208 }