Convert SchemaTracker to use SchemaInferenceStack
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / SchemaTracker.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.impl.codec;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.collect.Iterables;
15 import java.io.IOException;
16 import java.util.ArrayDeque;
17 import java.util.Deque;
18 import java.util.Optional;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
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.stream.NormalizedNodeStreamWriter;
26 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
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.AugmentationTarget;
31 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
34 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
37 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
38 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
39 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
43 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
45 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
46 import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
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.util.EffectiveAugmentationSchema;
50 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * Utility class for tracking the underlying state of the underlying schema node.
56  */
57 @Beta
58 public final class SchemaTracker {
59     private static final Logger LOG = LoggerFactory.getLogger(SchemaTracker.class);
60
61     private final Deque<WithStatus> schemaStack = new ArrayDeque<>();
62     private final DataNodeContainer root;
63
64     private SchemaTracker(final DataNodeContainer root) {
65         this.root = requireNonNull(root);
66     }
67
68     private static @NonNull SchemaTracker create(final SchemaInferenceStack root) {
69         if (root.isEmpty()) {
70             return new SchemaTracker(root.getEffectiveModelContext());
71         }
72
73         final EffectiveStatement<QName, ?> current = root.currentStatement();
74         checkArgument(current instanceof DataNodeContainer, "Cannot instantiate on %s", current);
75         return new SchemaTracker((DataNodeContainer) current);
76     }
77
78     /**
79      * Create a new writer with the specified node as its root.
80      *
81      * @param root Root node
82      * @return A new {@link NormalizedNodeStreamWriter}
83      * @throws NullPointerException if {@code root} is null
84      */
85     public static @NonNull SchemaTracker create(final DataNodeContainer root) {
86         return new SchemaTracker(root);
87     }
88
89     /**
90      * Create a new writer with the specified context and rooted in the specified schema path.
91      *
92      * @param context Associated {@link EffectiveModelContext}
93      * @param path schema path
94      * @return A new {@link SchemaTracker}
95      * @throws NullPointerException if any argument is null
96      * @throws IllegalArgumentException if {@code path} does not point to a valid root
97      */
98     public static @NonNull SchemaTracker create(final EffectiveModelContext context, final Absolute path) {
99         return create(SchemaInferenceStack.of(context, path));
100     }
101
102     /**
103      * Create a new writer with the specified context and rooted in the specified schema path.
104      *
105      * @param context Associated {@link EffectiveModelContext}
106      * @param path schema path
107      * @return A new {@link SchemaTracker}
108      * @throws NullPointerException if any argument is null
109      * @throws IllegalArgumentException if {@code path} does not point to a valid root
110      */
111     public static @NonNull SchemaTracker create(final EffectiveModelContext context, final SchemaPath path) {
112         return create(SchemaInferenceStack.ofInstantiatedPath(context, path));
113     }
114
115     /**
116      * Create a new writer with the specified context and rooted in the specified schema path.
117      *
118      * @param context Associated {@link EffectiveModelContext}
119      * @param operation Operation schema path
120      * @param qname Input/Output container QName
121      * @return A new {@link NormalizedNodeStreamWriter}
122      * @throws NullPointerException if any argument is null
123      * @throws IllegalArgumentException if {@code operation} does not point to an actual operation or if {@code qname}
124      *                                  does not identify a valid root underneath it.
125      */
126     public static @NonNull SchemaTracker forOperation(final EffectiveModelContext context, final Absolute operation,
127             final QName qname) {
128         final SchemaInferenceStack stack = SchemaInferenceStack.of(context, operation);
129         final EffectiveStatement<QName, ?> current = stack.currentStatement();
130         checkArgument(current instanceof RpcEffectiveStatement || current instanceof ActionEffectiveStatement,
131             "Path %s resolved into non-operation %s", operation, current);
132         stack.enterSchemaTree(qname);
133         return create(stack);
134     }
135
136     public Object getParent() {
137         if (schemaStack.isEmpty()) {
138             return root;
139         }
140         return schemaStack.peek();
141     }
142
143     private SchemaNode getSchema(final PathArgument name) {
144         final Object parent = getParent();
145         SchemaNode schema = null;
146         final QName qname = name.getNodeType();
147         if (parent instanceof DataNodeContainer) {
148             schema = ((DataNodeContainer)parent).dataChildByName(qname);
149             if (schema == null) {
150                 if (parent instanceof GroupingDefinition) {
151                     schema = (GroupingDefinition) parent;
152                 } else if (parent instanceof NotificationDefinition) {
153                     schema = (NotificationDefinition) parent;
154                 }
155             }
156         } else if (parent instanceof ChoiceSchemaNode) {
157             schema = findChildInCases((ChoiceSchemaNode) parent, qname);
158         } else {
159             throw new IllegalStateException("Unsupported schema type " + parent.getClass() + " on stack.");
160         }
161
162         checkArgument(schema != null, "Could not find schema for node %s in %s", qname, parent);
163         return schema;
164     }
165
166     private static SchemaNode findChildInCases(final ChoiceSchemaNode parent, final QName qname) {
167         for (final CaseSchemaNode caze : parent.getCases()) {
168             final Optional<DataSchemaNode> potential = caze.findDataChildByName(qname);
169             if (potential.isPresent()) {
170                 return potential.get();
171             }
172         }
173         return null;
174     }
175
176     private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
177         for (final CaseSchemaNode caze : parent.getCases()) {
178             final Optional<DataSchemaNode> potential = caze.findDataChildByName(qname);
179             if (potential.isPresent()) {
180                 return caze;
181             }
182         }
183         return null;
184     }
185
186     public void startList(final PathArgument name) {
187         final SchemaNode schema = getSchema(name);
188         checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema);
189         schemaStack.push(schema);
190     }
191
192     public void startListItem(final PathArgument name) throws IOException {
193         final Object schema = getParent();
194         checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
195         schemaStack.push((ListSchemaNode) schema);
196     }
197
198     public LeafSchemaNode leafNode(final NodeIdentifier name) throws IOException {
199         final SchemaNode schema = getSchema(name);
200         checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema);
201         return (LeafSchemaNode) schema;
202     }
203
204     public void startLeafNode(final NodeIdentifier name) throws IOException {
205         schemaStack.push(leafNode(name));
206     }
207
208     public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
209         final SchemaNode schema = getSchema(name);
210         checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema);
211         schemaStack.push(schema);
212         return (LeafListSchemaNode) schema;
213     }
214
215     public LeafListSchemaNode leafSetEntryNode(final QName qname) {
216         final Object parent = getParent();
217         if (parent instanceof LeafListSchemaNode) {
218             return (LeafListSchemaNode) parent;
219         }
220
221         final SchemaNode child = SchemaUtils.findDataChildSchemaByQName((SchemaNode) parent, qname);
222         checkArgument(child instanceof LeafListSchemaNode,
223             "Node %s is neither a leaf-list nor currently in a leaf-list", child);
224         return (LeafListSchemaNode) child;
225     }
226
227     public void startLeafSetEntryNode(final NodeWithValue<?> name) {
228         schemaStack.push(leafSetEntryNode(name.getNodeType()));
229     }
230
231     public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
232         LOG.debug("Enter choice {}", name);
233         final SchemaNode schema = getSchema(name);
234
235         checkArgument(schema instanceof ChoiceSchemaNode, "Node %s is not a choice", schema);
236         schemaStack.push(schema);
237         return (ChoiceSchemaNode)schema;
238     }
239
240     public SchemaNode startContainerNode(final NodeIdentifier name) {
241         LOG.debug("Enter container {}", name);
242         final SchemaNode schema = getSchema(name);
243         final boolean isAllowed = schema instanceof ContainerLike || schema instanceof NotificationDefinition;
244
245         checkArgument(isAllowed, "Node %s is not a container nor a notification", schema);
246         schemaStack.push(schema);
247         return schema;
248     }
249
250     public AugmentationSchemaNode startAugmentationNode(final AugmentationIdentifier identifier) {
251         LOG.debug("Enter augmentation {}", identifier);
252         Object parent = getParent();
253
254         checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
255         if (parent instanceof ChoiceSchemaNode) {
256             final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
257             parent = findCaseByChild((ChoiceSchemaNode) parent, name);
258         }
259         checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer", parent);
260         final AugmentationSchemaNode schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent,
261             identifier.getPossibleChildNames());
262         final AugmentationSchemaNode resolvedSchema = EffectiveAugmentationSchema.create(schema,
263             (DataNodeContainer) parent);
264         schemaStack.push(resolvedSchema);
265         return resolvedSchema;
266     }
267
268     public AnyxmlSchemaNode anyxmlNode(final NodeIdentifier name) {
269         final SchemaNode schema = getSchema(name);
270         checkArgument(schema instanceof AnyxmlSchemaNode, "Node %s is not anyxml", schema);
271         return (AnyxmlSchemaNode)schema;
272     }
273
274     public void startAnyxmlNode(final NodeIdentifier name) {
275         schemaStack.push(anyxmlNode(name));
276     }
277
278     public AnydataSchemaNode anydataNode(final NodeIdentifier name) {
279         final SchemaNode schema = getSchema(name);
280         checkArgument(schema instanceof AnydataSchemaNode, "Node %s is not anydata", schema);
281         return (AnydataSchemaNode)schema;
282     }
283
284     public void startAnydataNode(final NodeIdentifier name) {
285         schemaStack.push(anydataNode(name));
286     }
287
288     public Object endNode() {
289         return schemaStack.pop();
290     }
291 }