57ab071a6e87f1d0fb1a76ed869336d604c85304
[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 java.io.IOException;
17 import java.util.ArrayDeque;
18 import java.util.Deque;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
25 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
27 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
35 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
36 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
37 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
41 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
45 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
46 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeEffectiveStatement;
47 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
48 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
49 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.util.LeafrefResolver;
51 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
52 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * Utility class for tracking schema state underlying a {@link NormalizedNode} structure.
58  */
59 @Beta
60 public final class NormalizedNodeStreamWriterStack implements LeafrefResolver {
61     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeStreamWriterStack.class);
62
63     private final Deque<WithStatus> schemaStack = new ArrayDeque<>();
64     private final SchemaInferenceStack dataTree;
65     private final DataNodeContainer root;
66
67     private NormalizedNodeStreamWriterStack(final EffectiveModelContext context) {
68         dataTree = SchemaInferenceStack.of(context);
69         root = requireNonNull(context);
70     }
71
72     private NormalizedNodeStreamWriterStack(final SchemaInferenceStack dataTree) {
73         this.dataTree = requireNonNull(dataTree);
74         if (!dataTree.isEmpty()) {
75             final EffectiveStatement<?, ?> current = dataTree.currentStatement();
76             checkArgument(current instanceof DataNodeContainer, "Cannot instantiate on %s", current);
77
78             root = (DataNodeContainer) current;
79         } else {
80             root = dataTree.getEffectiveModelContext();
81         }
82     }
83
84     /**
85      * Create a new writer with the specified inference state as its root.
86      *
87      * @param root Root inference state
88      * @return A new {@link NormalizedNodeStreamWriter}
89      * @throws NullPointerException if {@code root} is null
90      */
91     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveStatementInference root) {
92         return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.ofInference(root));
93     }
94
95     /**
96      * Create a new writer with the specified inference state as its root.
97      *
98      * @param root Root inference state
99      * @return A new {@link NormalizedNodeStreamWriter}
100      * @throws NullPointerException if {@code root} is null
101      */
102     public static @NonNull NormalizedNodeStreamWriterStack of(final Inference root) {
103         return new NormalizedNodeStreamWriterStack(root.toSchemaInferenceStack());
104     }
105
106     /**
107      * Create a new writer at the root of specified {@link EffectiveModelContext}.
108      *
109      * @param context effective model context
110      * @return A new {@link NormalizedNodeStreamWriter}
111      * @throws NullPointerException if {@code context} is null
112      */
113     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context) {
114         return new NormalizedNodeStreamWriterStack(context);
115     }
116
117     /**
118      * Create a new writer with the specified context and rooted in the specified schema path.
119      *
120      * @param context Associated {@link EffectiveModelContext}
121      * @param path schema path
122      * @return A new {@link NormalizedNodeStreamWriterStack}
123      * @throws NullPointerException if any argument is null
124      * @throws IllegalArgumentException if {@code path} does not point to a valid root
125      */
126     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
127             final Absolute path) {
128         return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.of(context, path));
129     }
130
131     /**
132      * Create a new writer with the specified context and rooted in the specified {@link YangInstanceIdentifier}..
133      *
134      * @param context Associated {@link EffectiveModelContext}
135      * @param path Normalized path
136      * @return A new {@link NormalizedNodeStreamWriterStack}
137      * @throws NullPointerException if any argument is null
138      * @throws IllegalArgumentException if {@code path} does not point to a valid root
139      */
140     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
141             final YangInstanceIdentifier path) {
142         return new NormalizedNodeStreamWriterStack(DataSchemaContextTree.from(context)
143             .enterPath(path)
144             .orElseThrow()
145             .stack());
146     }
147
148     /**
149      * Create a new writer with the specified context and rooted in the specified schema path.
150      *
151      * @param context Associated {@link EffectiveModelContext}
152      * @param operation Operation schema path
153      * @param qname Input/Output container QName
154      * @return A new {@link NormalizedNodeStreamWriter}
155      * @throws NullPointerException if any argument is null
156      * @throws IllegalArgumentException if {@code operation} does not point to an actual operation or if {@code qname}
157      *                                  does not identify a valid root underneath it.
158      */
159     public static @NonNull NormalizedNodeStreamWriterStack ofOperation(final EffectiveModelContext context,
160             final Absolute operation, final QName qname) {
161         final SchemaInferenceStack stack = SchemaInferenceStack.of(context, operation);
162         final EffectiveStatement<?, ?> current = stack.currentStatement();
163         checkArgument(current instanceof RpcEffectiveStatement || current instanceof ActionEffectiveStatement,
164             "Path %s resolved into non-operation %s", operation, current);
165         stack.enterSchemaTree(qname);
166         return new NormalizedNodeStreamWriterStack(stack);
167     }
168
169     @Override
170     public TypeDefinition<?> resolveLeafref(final LeafrefTypeDefinition type) {
171         return dataTree.resolveLeafref(type);
172     }
173
174     public Object getParent() {
175         final WithStatus schema = schemaStack.peek();
176         return schema == null ? root : schema;
177     }
178
179     private SchemaNode enterDataTree(final PathArgument name) {
180         final QName qname = name.getNodeType();
181         final DataTreeEffectiveStatement<?> stmt = dataTree.enterDataTree(qname);
182         verify(stmt instanceof SchemaNode, "Unexpected result %s", stmt);
183         final SchemaNode ret = (SchemaNode) stmt;
184         final Object parent = getParent();
185         if (parent instanceof ChoiceSchemaNode choice) {
186             final DataSchemaNode check = choice.findDataSchemaChild(qname).orElse(null);
187             verify(check == ret, "Data tree result %s does not match choice result %s", ret, check);
188         }
189         return ret;
190     }
191
192     public void startList(final PathArgument name) {
193         final SchemaNode schema = enterDataTree(name);
194         checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema);
195         schemaStack.push(schema);
196     }
197
198     public void startListItem(final PathArgument name) throws IOException {
199         final Object schema = getParent();
200         checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
201         schemaStack.push((ListSchemaNode) schema);
202     }
203
204     public void startLeafNode(final NodeIdentifier name) throws IOException {
205         final SchemaNode schema = enterDataTree(name);
206         checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema);
207         schemaStack.push(schema);
208     }
209
210     public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
211         final SchemaNode schema = enterDataTree(name);
212         checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema);
213         schemaStack.push(schema);
214         return (LeafListSchemaNode) schema;
215     }
216
217     public LeafListSchemaNode leafSetEntryNode(final QName qname) {
218         final Object parent = getParent();
219         if (parent instanceof LeafListSchemaNode leafList) {
220             return leafList;
221         }
222         checkArgument(parent instanceof DataNodeContainer, "Cannot lookup %s in parent %s", qname, parent);
223         final DataSchemaNode child = ((DataNodeContainer) parent).dataChildByName(qname);
224         checkArgument(child instanceof LeafListSchemaNode,
225             "Node %s is neither a leaf-list nor currently in a leaf-list", child);
226         return (LeafListSchemaNode) child;
227     }
228
229     public void startLeafSetEntryNode(final NodeWithValue<?> name) {
230         schemaStack.push(leafSetEntryNode(name.getNodeType()));
231     }
232
233     public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
234         LOG.debug("Enter choice {}", name);
235         final ChoiceEffectiveStatement stmt = dataTree.enterChoice(name.getNodeType());
236         verify(stmt instanceof ChoiceSchemaNode, "Node %s is not a choice", stmt);
237         final ChoiceSchemaNode ret = (ChoiceSchemaNode) stmt;
238         schemaStack.push(ret);
239         return ret;
240     }
241
242     public SchemaNode startContainerNode(final NodeIdentifier name) {
243         LOG.debug("Enter container {}", name);
244
245         final SchemaNode schema;
246         if (schemaStack.isEmpty() && root instanceof NotificationDefinition notification) {
247             // Special case for stacks initialized at notification. We pretend the first container is contained within
248             // itself.
249             // FIXME: 8.0.0: factor this special case out to something more reasonable, like being initialized at the
250             //               Notification's parent and knowing to enterSchemaTree() instead of enterDataTree().
251             schema = notification;
252         } else {
253             schema = enterDataTree(name);
254             checkArgument(schema instanceof ContainerLike, "Node %s is not a container", schema);
255         }
256
257         schemaStack.push(schema);
258         return schema;
259     }
260
261     public void startAnyxmlNode(final NodeIdentifier name) {
262         final SchemaNode schema = enterDataTree(name);
263         checkArgument(schema instanceof AnyxmlSchemaNode, "Node %s is not anyxml", schema);
264         schemaStack.push(schema);
265     }
266
267     public void startAnydataNode(final NodeIdentifier name) {
268         final SchemaNode schema = enterDataTree(name);
269         checkArgument(schema instanceof AnydataSchemaNode, "Node %s is not anydata", schema);
270         schemaStack.push(schema);
271     }
272
273     public Object endNode() {
274         final Object ret = schemaStack.pop();
275         // If this is a data tree node, make sure it is updated. Before that, though, we need to check if this is not
276         // actually listEntry -> list or leafListEntry -> leafList exit.
277         if (!(ret instanceof AugmentationSchemaNode) && getParent() != ret) {
278             dataTree.exit();
279         }
280         return ret;
281     }
282 }