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