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