00ad5a04965642475a815043435ef1e4fcaac881
[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         DataSchemaNode schema = null;
128         for (final CaseSchemaNode caze : parent.getCases().values()) {
129             final DataSchemaNode potential = caze.getDataChildByName(qname);
130             if (potential != null) {
131                 schema = potential;
132                 break;
133             }
134         }
135         return schema;
136     }
137
138     private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
139         DataSchemaNode schema = null;
140         for (final CaseSchemaNode caze : parent.getCases().values()) {
141             final DataSchemaNode potential = caze.getDataChildByName(qname);
142             if (potential != null) {
143                 schema = caze;
144                 break;
145             }
146         }
147         return schema;
148     }
149
150     public void startList(final PathArgument name) {
151         final SchemaNode schema = getSchema(name);
152         checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema.getPath());
153         schemaStack.push(schema);
154     }
155
156     public void startListItem(final PathArgument name) throws IOException {
157         final Object schema = getParent();
158         checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
159         schemaStack.push((ListSchemaNode) schema);
160     }
161
162     public LeafSchemaNode leafNode(final NodeIdentifier name) throws IOException {
163         final SchemaNode schema = getSchema(name);
164
165         checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema.getPath());
166         return (LeafSchemaNode) schema;
167     }
168
169     public void startLeafNode(final NodeIdentifier name) throws IOException {
170         schemaStack.push(leafNode(name));
171     }
172
173     public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
174         final SchemaNode schema = getSchema(name);
175
176         checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema.getPath());
177         schemaStack.push(schema);
178         return (LeafListSchemaNode)schema;
179     }
180
181     public LeafListSchemaNode leafSetEntryNode(final QName qname) {
182         final Object parent = getParent();
183         if (parent instanceof LeafListSchemaNode) {
184             return (LeafListSchemaNode) parent;
185         }
186
187         final SchemaNode child = SchemaUtils.findDataChildSchemaByQName((SchemaNode) parent, qname);
188         checkArgument(child instanceof LeafListSchemaNode,
189             "Node %s is neither a leaf-list nor currently in a leaf-list", child.getPath());
190         return (LeafListSchemaNode) child;
191     }
192
193     public void startLeafSetEntryNode(final NodeWithValue<?> name) {
194         schemaStack.push(leafSetEntryNode(name.getNodeType()));
195     }
196
197     public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
198         LOG.debug("Enter choice {}", name);
199         final SchemaNode schema = getSchema(name);
200
201         checkArgument(schema instanceof ChoiceSchemaNode, "Node %s is not a choice", schema.getPath());
202         schemaStack.push(schema);
203         return (ChoiceSchemaNode)schema;
204     }
205
206     public SchemaNode startContainerNode(final NodeIdentifier name) {
207         LOG.debug("Enter container {}", name);
208         final SchemaNode schema = getSchema(name);
209
210         boolean isAllowed = schema instanceof ContainerSchemaNode;
211         isAllowed |= schema instanceof NotificationDefinition;
212
213         checkArgument(isAllowed, "Node %s is not a container nor a notification", schema.getPath());
214         schemaStack.push(schema);
215
216         return schema;
217     }
218
219     public SchemaNode startYangModeledAnyXmlNode(final NodeIdentifier name) {
220         LOG.debug("Enter yang modeled anyXml {}", name);
221         final SchemaNode schema = getSchema(name);
222
223         checkArgument(schema instanceof YangModeledAnyXmlSchemaNode, "Node %s is not an yang modeled anyXml.",
224             schema.getPath());
225
226         schemaStack.push(((YangModeledAnyXmlSchemaNode) schema).getSchemaOfAnyXmlData());
227
228         return schema;
229     }
230
231     public AugmentationSchemaNode startAugmentationNode(final AugmentationIdentifier identifier) {
232         LOG.debug("Enter augmentation {}", identifier);
233         Object parent = getParent();
234
235         checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
236         if (parent instanceof ChoiceSchemaNode) {
237             final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
238             parent = findCaseByChild((ChoiceSchemaNode) parent, name);
239         }
240         checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer", parent);
241         final AugmentationSchemaNode schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent,
242             identifier.getPossibleChildNames());
243         final AugmentationSchemaNode resolvedSchema = EffectiveAugmentationSchema.create(schema,
244             (DataNodeContainer) parent);
245         schemaStack.push(resolvedSchema);
246         return resolvedSchema;
247     }
248
249     public AnyXmlSchemaNode anyxmlNode(final NodeIdentifier name) {
250         final SchemaNode schema = getSchema(name);
251         checkArgument(schema instanceof AnyXmlSchemaNode, "Node %s is not anyxml", schema.getPath());
252         return (AnyXmlSchemaNode)schema;
253     }
254
255     public void startAnyxmlNode(final NodeIdentifier name) {
256         schemaStack.push(anyxmlNode(name));
257     }
258
259     public Object endNode() {
260         return schemaStack.pop();
261     }
262 }