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