Rename NormalizedNodeInferenceStack
[yangtools.git] / yang / 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  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.util;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.Beta;
15 import com.google.common.collect.Iterables;
16 import java.io.IOException;
17 import java.util.ArrayDeque;
18 import java.util.Deque;
19 import java.util.Optional;
20 import java.util.Set;
21 import java.util.stream.Collectors;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.opendaylight.yangtools.concepts.Mutable;
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.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.util.EffectiveAugmentationSchema;
56 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
57 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 /**
62  * Utility class for tracking schema state underlying a {@link NormalizedNode} structure.
63  */
64 @Beta
65 public final class NormalizedNodeStreamWriterStack implements Mutable {
66     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeStreamWriterStack.class);
67
68     private final Deque<WithStatus> schemaStack = new ArrayDeque<>();
69     private final SchemaInferenceStack dataTree;
70     private final DataNodeContainer root;
71
72     private NormalizedNodeStreamWriterStack(final EffectiveModelContext context) {
73         root = requireNonNull(context);
74         dataTree = SchemaInferenceStack.of(context);
75     }
76
77     private NormalizedNodeStreamWriterStack(final SchemaInferenceStack dataTree) {
78         this.dataTree = requireNonNull(dataTree);
79         if (!dataTree.isEmpty()) {
80             final EffectiveStatement<?, ?> current = dataTree.currentStatement();
81             checkArgument(current instanceof DataNodeContainer, "Cannot instantiate on %s", current);
82
83             root = (DataNodeContainer) current;
84         } else {
85             root = dataTree.getEffectiveModelContext();
86         }
87     }
88
89     /**
90      * Create a new writer with the specified inference state as its root.
91      *
92      * @param root Root inference state
93      * @return A new {@link NormalizedNodeStreamWriter}
94      * @throws NullPointerException if {@code root} is null
95      */
96     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveStatementInference root) {
97         return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.ofInference(root));
98     }
99
100     /**
101      * Create a new writer with the specified inference state as its root.
102      *
103      * @param root Root inference state
104      * @return A new {@link NormalizedNodeStreamWriter}
105      * @throws NullPointerException if {@code root} is null
106      */
107     public static @NonNull NormalizedNodeStreamWriterStack of(final Inference root) {
108         return new NormalizedNodeStreamWriterStack(root.toSchemaInferenceStack());
109     }
110
111     /**
112      * Create a new writer at the root of specified {@link EffectiveModelContext}.
113      *
114      * @param context effective model context
115      * @return A new {@link NormalizedNodeStreamWriter}
116      * @throws NullPointerException if {@code context} is null
117      */
118     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context) {
119         return new NormalizedNodeStreamWriterStack(context);
120     }
121
122     /**
123      * Create a new writer with the specified context and rooted in the specified schema path.
124      *
125      * @param context Associated {@link EffectiveModelContext}
126      * @param path schema path
127      * @return A new {@link NormalizedNodeStreamWriterStack}
128      * @throws NullPointerException if any argument is null
129      * @throws IllegalArgumentException if {@code path} does not point to a valid root
130      */
131     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
132             final Absolute path) {
133         return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.of(context, path));
134     }
135
136     /**
137      * Create a new writer with the specified context and rooted in the specified schema path.
138      *
139      * @param context Associated {@link EffectiveModelContext}
140      * @param path schema path
141      * @return A new {@link NormalizedNodeStreamWriterStack}
142      * @throws NullPointerException if any argument is null
143      * @throws IllegalArgumentException if {@code path} does not point to a valid root
144      */
145     @Deprecated
146     public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
147             final SchemaPath path) {
148         return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.ofInstantiatedPath(context, path));
149     }
150
151     /**
152      * Create a new writer with the specified context and rooted in the specified schema path.
153      *
154      * @param context Associated {@link EffectiveModelContext}
155      * @param operation Operation schema path
156      * @param qname Input/Output container QName
157      * @return A new {@link NormalizedNodeStreamWriter}
158      * @throws NullPointerException if any argument is null
159      * @throws IllegalArgumentException if {@code operation} does not point to an actual operation or if {@code qname}
160      *                                  does not identify a valid root underneath it.
161      */
162     public static @NonNull NormalizedNodeStreamWriterStack ofOperation(final EffectiveModelContext context,
163             final Absolute operation, final QName qname) {
164         final SchemaInferenceStack stack = SchemaInferenceStack.of(context, operation);
165         final EffectiveStatement<?, ?> current = stack.currentStatement();
166         checkArgument(current instanceof RpcEffectiveStatement || current instanceof ActionEffectiveStatement,
167             "Path %s resolved into non-operation %s", operation, current);
168         stack.enterSchemaTree(qname);
169         return new NormalizedNodeStreamWriterStack(stack);
170     }
171
172     /**
173      * Return a copy of this tracker's state as an {@link SchemaInferenceStack}.
174      *
175      * @return A SchemaInferenceStack
176      */
177     public @NonNull SchemaInferenceStack toSchemaInferenceStack() {
178         return dataTree.copy();
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         final SchemaNode schema = enterDataTree(name);
252         checkArgument(schema instanceof ContainerLike || schema instanceof NotificationDefinition,
253             "Node %s is not a container nor a notification", schema);
254         schemaStack.push(schema);
255         return schema;
256     }
257
258     public void startAnyxmlNode(final NodeIdentifier name) {
259         final SchemaNode schema = enterDataTree(name);
260         checkArgument(schema instanceof AnyxmlSchemaNode, "Node %s is not anyxml", schema);
261         schemaStack.push(schema);
262     }
263
264     public void startAnydataNode(final NodeIdentifier name) {
265         final SchemaNode schema = enterDataTree(name);
266         checkArgument(schema instanceof AnydataSchemaNode, "Node %s is not anydata", schema);
267         schemaStack.push(schema);
268     }
269
270     public Object endNode() {
271         final Object ret = schemaStack.pop();
272         // If this is a data tree node, make sure it is updated. Before that, though, we need to check if this is not
273         // actually listEntry -> list or leafListEntry -> leafList exit.
274         if (!(ret instanceof AugmentationSchemaNode) && getParent() != ret) {
275             dataTree.exit();
276         }
277         return ret;
278     }
279
280     public AugmentationSchemaNode startAugmentationNode(final AugmentationIdentifier identifier) {
281         LOG.debug("Enter augmentation {}", identifier);
282         Object parent = getParent();
283
284         checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
285         if (parent instanceof ChoiceSchemaNode) {
286             final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
287             parent = findCaseByChild((ChoiceSchemaNode) parent, name);
288         }
289         checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer", parent);
290         final AugmentationSchemaNode schema = findSchemaForAugment((AugmentationTarget) parent,
291             identifier.getPossibleChildNames());
292         final AugmentationSchemaNode resolvedSchema = EffectiveAugmentationSchema.create(schema,
293             (DataNodeContainer) parent);
294         schemaStack.push(resolvedSchema);
295         return resolvedSchema;
296     }
297
298     // FIXME: 7.0.0: can we get rid of this?
299     private static @NonNull AugmentationSchemaNode findSchemaForAugment(final AugmentationTarget schema,
300             final Set<QName> qnames) {
301         for (final AugmentationSchemaNode augment : schema.getAvailableAugmentations()) {
302             if (qnames.equals(augment.getChildNodes().stream()
303                 .map(DataSchemaNode::getQName)
304                 .collect(Collectors.toUnmodifiableSet()))) {
305                 return augment;
306             }
307         }
308
309         throw new IllegalStateException(
310             "Unknown augmentation node detected, identified by: " + qnames + ", in: " + schema);
311     }
312
313     // FIXME: 7.0.0: can we get rid of this?
314     private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
315         for (final CaseSchemaNode caze : parent.getCases()) {
316             final Optional<DataSchemaNode> potential = caze.findDataChildByName(qname);
317             if (potential.isPresent()) {
318                 return caze;
319             }
320         }
321         return null;
322     }
323 }