Do not use Optional for augmentation traversal
[yangtools.git] / data / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / NormalizedNodeStreamWriterStack.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  * Copyright (c) 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.yangtools.yang.data.util;
10
11 import static com.google.common.base.Preconditions.checkArgument;
12 import static com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
14
15 import com.google.common.annotations.Beta;
16 import com.google.common.collect.Iterables;
17 import java.io.IOException;
18 import java.util.ArrayDeque;
19 import java.util.Deque;
20 import java.util.Set;
21 import java.util.stream.Collectors;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
31 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
35 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
38 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
41 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
42 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
43 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
49 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
51 import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
52 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
53 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeEffectiveStatement;
54 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
55 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
56 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
57 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
58 import org.opendaylight.yangtools.yang.model.util.LeafrefResolver;
59 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
60 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 /**
65  * Utility class for tracking schema state underlying a {@link NormalizedNode} structure.
66  */
67 @Beta
68 public final class NormalizedNodeStreamWriterStack implements LeafrefResolver {
69     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeStreamWriterStack.class);
70
71     private final Deque<WithStatus> schemaStack = new ArrayDeque<>();
72     private final SchemaInferenceStack dataTree;
73     private final DataNodeContainer root;
74
75     private NormalizedNodeStreamWriterStack(final EffectiveModelContext context) {
76         dataTree = SchemaInferenceStack.of(context);
77         root = requireNonNull(context);
78     }
79
80     private NormalizedNodeStreamWriterStack(final SchemaInferenceStack dataTree) {
81         this.dataTree = requireNonNull(dataTree);
82         if (!dataTree.isEmpty()) {
83             final EffectiveStatement<?, ?> current = dataTree.currentStatement();
84             checkArgument(current instanceof DataNodeContainer, "Cannot instantiate on %s", current);
85
86             root = (DataNodeContainer) current;
87         } else {
88             root = dataTree.getEffectiveModelContext();
89         }
90     }
91
92     /**
93      * Create a new writer with the specified inference state as its root.
94      *
95      * @param root Root inference state
96      * @return A new {@link NormalizedNodeStreamWriter}
97      * @throws NullPointerException if {@code root} is null
98      */
99     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveStatementInference root) {
100         return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.ofInference(root));
101     }
102
103     /**
104      * Create a new writer with the specified inference state as its root.
105      *
106      * @param root Root inference state
107      * @return A new {@link NormalizedNodeStreamWriter}
108      * @throws NullPointerException if {@code root} is null
109      */
110     public static @NonNull NormalizedNodeStreamWriterStack of(final Inference root) {
111         return new NormalizedNodeStreamWriterStack(root.toSchemaInferenceStack());
112     }
113
114     /**
115      * Create a new writer at the root of specified {@link EffectiveModelContext}.
116      *
117      * @param context effective model context
118      * @return A new {@link NormalizedNodeStreamWriter}
119      * @throws NullPointerException if {@code context} is null
120      */
121     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context) {
122         return new NormalizedNodeStreamWriterStack(context);
123     }
124
125     /**
126      * Create a new writer with the specified context and rooted in the specified schema path.
127      *
128      * @param context Associated {@link EffectiveModelContext}
129      * @param path schema path
130      * @return A new {@link NormalizedNodeStreamWriterStack}
131      * @throws NullPointerException if any argument is null
132      * @throws IllegalArgumentException if {@code path} does not point to a valid root
133      */
134     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
135             final Absolute path) {
136         return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.of(context, path));
137     }
138
139     /**
140      * Create a new writer with the specified context and rooted in the specified {@link YangInstanceIdentifier}..
141      *
142      * @param context Associated {@link EffectiveModelContext}
143      * @param path Normalized path
144      * @return A new {@link NormalizedNodeStreamWriterStack}
145      * @throws NullPointerException if any argument is null
146      * @throws IllegalArgumentException if {@code path} does not point to a valid root
147      */
148     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
149             final YangInstanceIdentifier path) {
150         return new NormalizedNodeStreamWriterStack(DataSchemaContextTree.from(context)
151             .enterPath(path)
152             .orElseThrow()
153             .stack());
154     }
155
156     /**
157      * Create a new writer with the specified context and rooted in the specified schema path.
158      *
159      * @param context Associated {@link EffectiveModelContext}
160      * @param path schema path
161      * @return A new {@link NormalizedNodeStreamWriterStack}
162      * @throws NullPointerException if any argument is null
163      * @throws IllegalArgumentException if {@code path} does not point to a valid root
164      */
165     @Deprecated
166     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
167             final SchemaPath path) {
168         return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.ofSchemaPath(context, path));
169     }
170
171     /**
172      * Create a new writer with the specified context and rooted in the specified schema path.
173      *
174      * @param context Associated {@link EffectiveModelContext}
175      * @param operation Operation schema path
176      * @param qname Input/Output container QName
177      * @return A new {@link NormalizedNodeStreamWriter}
178      * @throws NullPointerException if any argument is null
179      * @throws IllegalArgumentException if {@code operation} does not point to an actual operation or if {@code qname}
180      *                                  does not identify a valid root underneath it.
181      */
182     public static @NonNull NormalizedNodeStreamWriterStack ofOperation(final EffectiveModelContext context,
183             final Absolute operation, final QName qname) {
184         final SchemaInferenceStack stack = SchemaInferenceStack.of(context, operation);
185         final EffectiveStatement<?, ?> current = stack.currentStatement();
186         checkArgument(current instanceof RpcEffectiveStatement || current instanceof ActionEffectiveStatement,
187             "Path %s resolved into non-operation %s", operation, current);
188         stack.enterSchemaTree(qname);
189         return new NormalizedNodeStreamWriterStack(stack);
190     }
191
192     @Override
193     public TypeDefinition<?> resolveLeafref(final LeafrefTypeDefinition type) {
194         return dataTree.resolveLeafref(type);
195     }
196
197     public Object getParent() {
198         final WithStatus schema = schemaStack.peek();
199         return schema == null ? root : schema;
200     }
201
202     private SchemaNode enterDataTree(final PathArgument name) {
203         final QName qname = name.getNodeType();
204         final DataTreeEffectiveStatement<?> stmt = dataTree.enterDataTree(qname);
205         verify(stmt instanceof SchemaNode, "Unexpected result %s", stmt);
206         final SchemaNode ret = (SchemaNode) stmt;
207         final Object parent = getParent();
208         if (parent instanceof ChoiceSchemaNode) {
209             final DataSchemaNode check = ((ChoiceSchemaNode) parent).findDataSchemaChild(qname).orElse(null);
210             verify(check == ret, "Data tree result %s does not match choice result %s", ret, check);
211         }
212         return ret;
213     }
214
215     public void startList(final PathArgument name) {
216         final SchemaNode schema = enterDataTree(name);
217         checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema);
218         schemaStack.push(schema);
219     }
220
221     public void startListItem(final PathArgument name) throws IOException {
222         final Object schema = getParent();
223         checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
224         schemaStack.push((ListSchemaNode) schema);
225     }
226
227     public void startLeafNode(final NodeIdentifier name) throws IOException {
228         final SchemaNode schema = enterDataTree(name);
229         checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema);
230         schemaStack.push(schema);
231     }
232
233     public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
234         final SchemaNode schema = enterDataTree(name);
235         checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema);
236         schemaStack.push(schema);
237         return (LeafListSchemaNode) schema;
238     }
239
240     public LeafListSchemaNode leafSetEntryNode(final QName qname) {
241         final Object parent = getParent();
242         if (parent instanceof LeafListSchemaNode) {
243             return (LeafListSchemaNode) parent;
244         }
245         checkArgument(parent instanceof DataNodeContainer, "Cannot lookup %s in parent %s", qname, parent);
246         final DataSchemaNode child = ((DataNodeContainer) parent).dataChildByName(qname);
247         checkArgument(child instanceof LeafListSchemaNode,
248             "Node %s is neither a leaf-list nor currently in a leaf-list", child);
249         return (LeafListSchemaNode) child;
250     }
251
252     public void startLeafSetEntryNode(final NodeWithValue<?> name) {
253         schemaStack.push(leafSetEntryNode(name.getNodeType()));
254     }
255
256     public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
257         LOG.debug("Enter choice {}", name);
258         final ChoiceEffectiveStatement stmt = dataTree.enterChoice(name.getNodeType());
259         verify(stmt instanceof ChoiceSchemaNode, "Node %s is not a choice", stmt);
260         final ChoiceSchemaNode ret = (ChoiceSchemaNode) stmt;
261         schemaStack.push(ret);
262         return ret;
263     }
264
265     public SchemaNode startContainerNode(final NodeIdentifier name) {
266         LOG.debug("Enter container {}", name);
267
268         final SchemaNode schema;
269         if (schemaStack.isEmpty() && root instanceof NotificationDefinition) {
270             // Special case for stacks initialized at notification. We pretend the first container is contained within
271             // itself.
272             // FIXME: 8.0.0: factor this special case out to something more reasonable, like being initialized at the
273             //               Notification's parent and knowing to enterSchemaTree() instead of enterDataTree().
274             schema = (NotificationDefinition) root;
275         } else {
276             schema = enterDataTree(name);
277             checkArgument(schema instanceof ContainerLike, "Node %s is not a container", schema);
278         }
279
280         schemaStack.push(schema);
281         return schema;
282     }
283
284     public void startAnyxmlNode(final NodeIdentifier name) {
285         final SchemaNode schema = enterDataTree(name);
286         checkArgument(schema instanceof AnyxmlSchemaNode, "Node %s is not anyxml", schema);
287         schemaStack.push(schema);
288     }
289
290     public void startAnydataNode(final NodeIdentifier name) {
291         final SchemaNode schema = enterDataTree(name);
292         checkArgument(schema instanceof AnydataSchemaNode, "Node %s is not anydata", schema);
293         schemaStack.push(schema);
294     }
295
296     public Object endNode() {
297         final Object ret = schemaStack.pop();
298         // If this is a data tree node, make sure it is updated. Before that, though, we need to check if this is not
299         // actually listEntry -> list or leafListEntry -> leafList exit.
300         if (!(ret instanceof AugmentationSchemaNode) && getParent() != ret) {
301             dataTree.exit();
302         }
303         return ret;
304     }
305
306     public AugmentationSchemaNode startAugmentationNode(final AugmentationIdentifier identifier) {
307         LOG.debug("Enter augmentation {}", identifier);
308         Object parent = getParent();
309
310         checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
311         if (parent instanceof ChoiceSchemaNode) {
312             final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
313             parent = findCaseByChild((ChoiceSchemaNode) parent, name);
314         }
315         checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer", parent);
316         final AugmentationSchemaNode schema = findSchemaForAugment((AugmentationTarget) parent,
317             identifier.getPossibleChildNames());
318         final AugmentationSchemaNode resolvedSchema = new EffectiveAugmentationSchema(schema,
319             (DataNodeContainer) parent);
320         schemaStack.push(resolvedSchema);
321         return resolvedSchema;
322     }
323
324     // FIXME: 7.0.0: can we get rid of this?
325     private static @NonNull AugmentationSchemaNode findSchemaForAugment(final AugmentationTarget schema,
326             final Set<QName> qnames) {
327         for (final AugmentationSchemaNode augment : schema.getAvailableAugmentations()) {
328             if (qnames.equals(augment.getChildNodes().stream()
329                 .map(DataSchemaNode::getQName)
330                 .collect(Collectors.toUnmodifiableSet()))) {
331                 return augment;
332             }
333         }
334
335         throw new IllegalStateException(
336             "Unknown augmentation node detected, identified by: " + qnames + ", in: " + schema);
337     }
338
339     // FIXME: 7.0.0: can we get rid of this?
340     private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
341         for (final CaseSchemaNode caze : parent.getCases()) {
342             if (caze.dataChildByName(qname) != null) {
343                 return caze;
344             }
345         }
346         return null;
347     }
348 }