686e0d8739bdbdd8c5a769f13d9386d8e6c9fde7
[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.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 schema path.
141      *
142      * @param context Associated {@link EffectiveModelContext}
143      * @param path schema 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     @Deprecated
149     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
150             final SchemaPath path) {
151         return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.ofSchemaPath(context, path));
152     }
153
154     /**
155      * Create a new writer with the specified context and rooted in the specified schema path.
156      *
157      * @param context Associated {@link EffectiveModelContext}
158      * @param operation Operation schema path
159      * @param qname Input/Output container QName
160      * @return A new {@link NormalizedNodeStreamWriter}
161      * @throws NullPointerException if any argument is null
162      * @throws IllegalArgumentException if {@code operation} does not point to an actual operation or if {@code qname}
163      *                                  does not identify a valid root underneath it.
164      */
165     public static @NonNull NormalizedNodeStreamWriterStack ofOperation(final EffectiveModelContext context,
166             final Absolute operation, final QName qname) {
167         final SchemaInferenceStack stack = SchemaInferenceStack.of(context, operation);
168         final EffectiveStatement<?, ?> current = stack.currentStatement();
169         checkArgument(current instanceof RpcEffectiveStatement || current instanceof ActionEffectiveStatement,
170             "Path %s resolved into non-operation %s", operation, current);
171         stack.enterSchemaTree(qname);
172         return new NormalizedNodeStreamWriterStack(stack);
173     }
174
175     @Override
176     public TypeDefinition<?> resolveLeafref(final LeafrefTypeDefinition type) {
177         return dataTree.resolveLeafref(type);
178     }
179
180     public Object getParent() {
181         final WithStatus schema = schemaStack.peek();
182         return schema == null ? root : schema;
183     }
184
185     private SchemaNode enterDataTree(final PathArgument name) {
186         final QName qname = name.getNodeType();
187         final DataTreeEffectiveStatement<?> stmt = dataTree.enterDataTree(qname);
188         verify(stmt instanceof SchemaNode, "Unexpected result %s", stmt);
189         final SchemaNode ret = (SchemaNode) stmt;
190         final Object parent = getParent();
191         if (parent instanceof ChoiceSchemaNode) {
192             final DataSchemaNode check = ((ChoiceSchemaNode) parent).findDataSchemaChild(qname).orElse(null);
193             verify(check == ret, "Data tree result %s does not match choice result %s", ret, check);
194         }
195         return ret;
196     }
197
198     public void startList(final PathArgument name) {
199         final SchemaNode schema = enterDataTree(name);
200         checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema);
201         schemaStack.push(schema);
202     }
203
204     public void startListItem(final PathArgument name) throws IOException {
205         final Object schema = getParent();
206         checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
207         schemaStack.push((ListSchemaNode) schema);
208     }
209
210     public void startLeafNode(final NodeIdentifier name) throws IOException {
211         final SchemaNode schema = enterDataTree(name);
212         checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema);
213         schemaStack.push(schema);
214     }
215
216     public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
217         final SchemaNode schema = enterDataTree(name);
218         checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema);
219         schemaStack.push(schema);
220         return (LeafListSchemaNode) schema;
221     }
222
223     public LeafListSchemaNode leafSetEntryNode(final QName qname) {
224         final Object parent = getParent();
225         if (parent instanceof LeafListSchemaNode) {
226             return (LeafListSchemaNode) parent;
227         }
228         checkArgument(parent instanceof DataNodeContainer, "Cannot lookup %s in parent %s", qname, parent);
229         final DataSchemaNode child = ((DataNodeContainer) parent).dataChildByName(qname);
230         checkArgument(child instanceof LeafListSchemaNode,
231             "Node %s is neither a leaf-list nor currently in a leaf-list", child);
232         return (LeafListSchemaNode) child;
233     }
234
235     public void startLeafSetEntryNode(final NodeWithValue<?> name) {
236         schemaStack.push(leafSetEntryNode(name.getNodeType()));
237     }
238
239     public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
240         LOG.debug("Enter choice {}", name);
241         final ChoiceEffectiveStatement stmt = dataTree.enterChoice(name.getNodeType());
242         verify(stmt instanceof ChoiceSchemaNode, "Node %s is not a choice", stmt);
243         final ChoiceSchemaNode ret = (ChoiceSchemaNode) stmt;
244         schemaStack.push(ret);
245         return ret;
246     }
247
248     public SchemaNode startContainerNode(final NodeIdentifier name) {
249         LOG.debug("Enter container {}", name);
250
251         final SchemaNode schema;
252         if (schemaStack.isEmpty() && root instanceof NotificationDefinition) {
253             // Special case for stacks initialized at notification. We pretend the first container is contained within
254             // itself.
255             // FIXME: 8.0.0: factor this special case out to something more reasonable, like being initialized at the
256             //               Notification's parent and knowing to enterSchemaTree() instead of enterDataTree().
257             schema = (NotificationDefinition) root;
258         } else {
259             schema = enterDataTree(name);
260             checkArgument(schema instanceof ContainerLike, "Node %s is not a container", schema);
261         }
262
263         schemaStack.push(schema);
264         return schema;
265     }
266
267     public void startAnyxmlNode(final NodeIdentifier name) {
268         final SchemaNode schema = enterDataTree(name);
269         checkArgument(schema instanceof AnyxmlSchemaNode, "Node %s is not anyxml", schema);
270         schemaStack.push(schema);
271     }
272
273     public void startAnydataNode(final NodeIdentifier name) {
274         final SchemaNode schema = enterDataTree(name);
275         checkArgument(schema instanceof AnydataSchemaNode, "Node %s is not anydata", schema);
276         schemaStack.push(schema);
277     }
278
279     public Object endNode() {
280         final Object ret = schemaStack.pop();
281         // If this is a data tree node, make sure it is updated. Before that, though, we need to check if this is not
282         // actually listEntry -> list or leafListEntry -> leafList exit.
283         if (!(ret instanceof AugmentationSchemaNode) && getParent() != ret) {
284             dataTree.exit();
285         }
286         return ret;
287     }
288
289     public AugmentationSchemaNode startAugmentationNode(final AugmentationIdentifier identifier) {
290         LOG.debug("Enter augmentation {}", identifier);
291         Object parent = getParent();
292
293         checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
294         if (parent instanceof ChoiceSchemaNode) {
295             final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
296             parent = findCaseByChild((ChoiceSchemaNode) parent, name);
297         }
298         checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer", parent);
299         final AugmentationSchemaNode schema = findSchemaForAugment((AugmentationTarget) parent,
300             identifier.getPossibleChildNames());
301         final AugmentationSchemaNode resolvedSchema = new EffectiveAugmentationSchema(schema,
302             (DataNodeContainer) parent);
303         schemaStack.push(resolvedSchema);
304         return resolvedSchema;
305     }
306
307     // FIXME: 7.0.0: can we get rid of this?
308     private static @NonNull AugmentationSchemaNode findSchemaForAugment(final AugmentationTarget schema,
309             final Set<QName> qnames) {
310         for (final AugmentationSchemaNode augment : schema.getAvailableAugmentations()) {
311             if (qnames.equals(augment.getChildNodes().stream()
312                 .map(DataSchemaNode::getQName)
313                 .collect(Collectors.toUnmodifiableSet()))) {
314                 return augment;
315             }
316         }
317
318         throw new IllegalStateException(
319             "Unknown augmentation node detected, identified by: " + qnames + ", in: " + schema);
320     }
321
322     // FIXME: 7.0.0: can we get rid of this?
323     private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
324         for (final CaseSchemaNode caze : parent.getCases()) {
325             final Optional<DataSchemaNode> potential = caze.findDataChildByName(qname);
326             if (potential.isPresent()) {
327                 return caze;
328             }
329         }
330         return null;
331     }
332 }