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