Propagate EffectiveModelContext to more places
[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.Collection;
18 import java.util.Deque;
19 import java.util.Optional;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyxmlSchemaNode;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
27 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
28 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
29 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
33 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
37 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
39 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
40 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
41 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
45 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
47 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * Utility class for tracking the underlying state of the underlying
53  * schema node.
54  */
55 @Beta
56 public final class SchemaTracker {
57     private static final Logger LOG = LoggerFactory.getLogger(SchemaTracker.class);
58     private final Deque<WithStatus> schemaStack = new ArrayDeque<>();
59     private final DataNodeContainer root;
60
61     private SchemaTracker(final DataNodeContainer root) {
62         this.root = requireNonNull(root);
63     }
64
65     /**
66      * Create a new writer with the specified node as its root.
67      *
68      * @param root Root node
69      * @return A new {@link NormalizedNodeStreamWriter}
70      */
71     public static @NonNull SchemaTracker create(final DataNodeContainer root) {
72         return new SchemaTracker(root);
73     }
74
75     /**
76      * Create a new writer with the specified context and rooted in the specified schema path.
77      *
78      * @param context Associated {@link EffectiveModelContext}
79      * @param path schema path
80      * @return A new {@link NormalizedNodeStreamWriter}
81      */
82     public static @NonNull SchemaTracker create(final EffectiveModelContext context, final SchemaPath path) {
83         final Collection<SchemaNode> schemaNodes = SchemaUtils.findParentSchemaNodesOnPath(context, path);
84         checkArgument(!schemaNodes.isEmpty(), "Unable to find schema node for supplied schema path: %s", path);
85         if (schemaNodes.size() > 1) {
86             LOG.warn("More possible schema nodes {} for supplied schema path {}", schemaNodes, path);
87         }
88         final Optional<DataNodeContainer> current = schemaNodes.stream()
89                 .filter(node -> node instanceof DataNodeContainer).map(DataNodeContainer.class::cast)
90                 .findFirst();
91         checkArgument(current.isPresent(),
92                 "Schema path must point to container or list or an rpc input/output. Supplied path %s pointed to: %s",
93                 path, current);
94         return new SchemaTracker(current.get());
95     }
96
97     public Object getParent() {
98         if (schemaStack.isEmpty()) {
99             return root;
100         }
101         return schemaStack.peek();
102     }
103
104     private SchemaNode getSchema(final PathArgument name) {
105         final Object parent = getParent();
106         SchemaNode schema = null;
107         final QName qname = name.getNodeType();
108         if (parent instanceof DataNodeContainer) {
109             schema = ((DataNodeContainer)parent).getDataChildByName(qname);
110             if (schema == null) {
111                 if (parent instanceof GroupingDefinition) {
112                     schema = (GroupingDefinition) parent;
113                 } else if (parent instanceof NotificationDefinition) {
114                     schema = (NotificationDefinition) parent;
115                 }
116             }
117         } else if (parent instanceof ChoiceSchemaNode) {
118             schema = findChildInCases((ChoiceSchemaNode) parent, qname);
119         } else {
120             throw new IllegalStateException("Unsupported schema type " + parent.getClass() + " on stack.");
121         }
122
123         checkArgument(schema != null, "Could not find schema for node %s in %s", qname, parent);
124         return schema;
125     }
126
127     private static SchemaNode findChildInCases(final ChoiceSchemaNode parent, final QName qname) {
128         for (final CaseSchemaNode caze : parent.getCases()) {
129             final Optional<DataSchemaNode> potential = caze.findDataChildByName(qname);
130             if (potential.isPresent()) {
131                 return potential.get();
132             }
133         }
134         return null;
135     }
136
137     private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
138         for (final CaseSchemaNode caze : parent.getCases()) {
139             final Optional<DataSchemaNode> potential = caze.findDataChildByName(qname);
140             if (potential.isPresent()) {
141                 return caze;
142             }
143         }
144         return null;
145     }
146
147     public void startList(final PathArgument name) {
148         final SchemaNode schema = getSchema(name);
149         checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema);
150         schemaStack.push(schema);
151     }
152
153     public void startListItem(final PathArgument name) throws IOException {
154         final Object schema = getParent();
155         checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
156         schemaStack.push((ListSchemaNode) schema);
157     }
158
159     public LeafSchemaNode leafNode(final NodeIdentifier name) throws IOException {
160         final SchemaNode schema = getSchema(name);
161         checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema);
162         return (LeafSchemaNode) schema;
163     }
164
165     public void startLeafNode(final NodeIdentifier name) throws IOException {
166         schemaStack.push(leafNode(name));
167     }
168
169     public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
170         final SchemaNode schema = getSchema(name);
171         checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema);
172         schemaStack.push(schema);
173         return (LeafListSchemaNode) schema;
174     }
175
176     public LeafListSchemaNode leafSetEntryNode(final QName qname) {
177         final Object parent = getParent();
178         if (parent instanceof LeafListSchemaNode) {
179             return (LeafListSchemaNode) parent;
180         }
181
182         final SchemaNode child = SchemaUtils.findDataChildSchemaByQName((SchemaNode) parent, qname);
183         checkArgument(child instanceof LeafListSchemaNode,
184             "Node %s is neither a leaf-list nor currently in a leaf-list", child);
185         return (LeafListSchemaNode) child;
186     }
187
188     public void startLeafSetEntryNode(final NodeWithValue<?> name) {
189         schemaStack.push(leafSetEntryNode(name.getNodeType()));
190     }
191
192     public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
193         LOG.debug("Enter choice {}", name);
194         final SchemaNode schema = getSchema(name);
195
196         checkArgument(schema instanceof ChoiceSchemaNode, "Node %s is not a choice", schema);
197         schemaStack.push(schema);
198         return (ChoiceSchemaNode)schema;
199     }
200
201     public SchemaNode startContainerNode(final NodeIdentifier name) {
202         LOG.debug("Enter container {}", name);
203         final SchemaNode schema = getSchema(name);
204
205         boolean isAllowed = schema instanceof ContainerSchemaNode;
206         isAllowed |= schema instanceof NotificationDefinition;
207
208         checkArgument(isAllowed, "Node %s is not a container nor a notification", schema);
209         schemaStack.push(schema);
210         return schema;
211     }
212
213     public SchemaNode startYangModeledAnyXmlNode(final NodeIdentifier name) {
214         LOG.debug("Enter yang modeled anyXml {}", name);
215         final SchemaNode schema = getSchema(name);
216
217         checkArgument(schema instanceof YangModeledAnyxmlSchemaNode, "Node %s is not an yang modeled anyXml.", schema);
218         schemaStack.push(((YangModeledAnyxmlSchemaNode) schema).getSchemaOfAnyXmlData());
219         return schema;
220     }
221
222     public AugmentationSchemaNode startAugmentationNode(final AugmentationIdentifier identifier) {
223         LOG.debug("Enter augmentation {}", identifier);
224         Object parent = getParent();
225
226         checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
227         if (parent instanceof ChoiceSchemaNode) {
228             final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
229             parent = findCaseByChild((ChoiceSchemaNode) parent, name);
230         }
231         checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer", parent);
232         final AugmentationSchemaNode schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent,
233             identifier.getPossibleChildNames());
234         final AugmentationSchemaNode resolvedSchema = EffectiveAugmentationSchema.create(schema,
235             (DataNodeContainer) parent);
236         schemaStack.push(resolvedSchema);
237         return resolvedSchema;
238     }
239
240     public AnyxmlSchemaNode anyxmlNode(final NodeIdentifier name) {
241         final SchemaNode schema = getSchema(name);
242         checkArgument(schema instanceof AnyxmlSchemaNode, "Node %s is not anyxml", schema);
243         return (AnyxmlSchemaNode)schema;
244     }
245
246     public void startAnyxmlNode(final NodeIdentifier name) {
247         schemaStack.push(anyxmlNode(name));
248     }
249
250     public AnydataSchemaNode anydataNode(final NodeIdentifier name) {
251         final SchemaNode schema = getSchema(name);
252         checkArgument(schema instanceof AnydataSchemaNode, "Node %s is not anydata", schema);
253         return (AnydataSchemaNode)schema;
254     }
255
256     public void startAnydataNode(final NodeIdentifier name) {
257         schemaStack.push(anydataNode(name));
258     }
259
260     public Object endNode() {
261         return schemaStack.pop();
262     }
263 }