Bug-6195: Fix issue with leafSetEntryNode in SchemaTracker
[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 com.google.common.annotations.Beta;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicate;
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.HashSet;
19 import org.opendaylight.yangtools.yang.common.QName;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
23 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
24 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
25 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
27 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
28 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
29 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
32 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
34 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
38 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
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.api.YangModeledAnyXmlSchemaNode;
43 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Utility class for tracking the underlying state of the underlying
49  * schema node.
50  */
51 @Beta
52 public final class SchemaTracker {
53     private static final Logger LOG = LoggerFactory.getLogger(SchemaTracker.class);
54     private final Deque<Object> schemaStack = new ArrayDeque<>();
55     private final DataNodeContainer root;
56
57     private SchemaTracker(final SchemaContext context, final SchemaPath path) {
58         SchemaNode current = Preconditions.checkNotNull(context);
59         for (final QName qname : path.getPathFromRoot()) {
60             current = getChild(current, qname);
61         }
62         Preconditions.checkArgument(current instanceof DataNodeContainer,"Schema path must point to container or list or an rpc input/output. Supplied path %s pointed to: %s",path,current);
63         root = (DataNodeContainer) current;
64     }
65
66     private SchemaNode getChild(final SchemaNode node, final QName qname) {
67         SchemaNode child = null;
68
69         if (node instanceof DataNodeContainer) {
70             child = ((DataNodeContainer) node).getDataChildByName(qname);
71
72             if (child == null && node instanceof SchemaContext) {
73                 child = tryFindGroupings((SchemaContext) node, qname).orNull();
74             }
75
76             if(child == null && node instanceof SchemaContext) {
77                 child = tryFindNotification((SchemaContext) node, qname)
78                         .or(tryFindRpc(((SchemaContext) node), qname)).orNull();
79             }
80         } else if (node instanceof ChoiceSchemaNode) {
81             child = ((ChoiceSchemaNode) node).getCaseNodeByName(qname);
82         } else if (node instanceof RpcDefinition) {
83             switch (qname.getLocalName()) {
84                 case "input":
85                     child = ((RpcDefinition) node).getInput();
86                     break;
87                 case "output":
88                     child = ((RpcDefinition) node).getOutput();
89                     break;
90                 default:
91                     child = null;
92                     break;
93             }
94         } else {
95             throw new IllegalArgumentException(String.format("Schema node %s does not allow children.", node));
96         }
97
98         return child;
99     }
100
101     private static Optional<SchemaNode> tryFindGroupings(final SchemaContext ctx, final QName qname) {
102         return Optional.<SchemaNode> fromNullable(Iterables.find(ctx.getGroupings(), new SchemaNodePredicate(qname), null));
103     }
104
105     private static Optional<SchemaNode> tryFindRpc(final SchemaContext ctx, final QName qname) {
106         return Optional.<SchemaNode>fromNullable(Iterables.find(ctx.getOperations(), new SchemaNodePredicate(qname), null));
107     }
108
109     private static Optional<SchemaNode> tryFindNotification(final SchemaContext ctx, final QName qname) {
110         return Optional.<SchemaNode>fromNullable(Iterables.find(ctx.getNotifications(), new SchemaNodePredicate(qname), null));
111     }
112
113     /**
114      * Create a new writer with the specified context as its root.
115      *
116      * @param context Associated {@link SchemaContext}.
117      * @return A new {@link NormalizedNodeStreamWriter}
118      */
119     public static SchemaTracker create(final SchemaContext context) {
120         return create(context, SchemaPath.ROOT);
121     }
122
123     /**
124      * Create a new writer with the specified context and rooted in the specified schema path
125      *
126      * @param context Associated {@link SchemaContext}
127      * @param path schema path
128      *
129      * @return A new {@link NormalizedNodeStreamWriter}
130      */
131     public static SchemaTracker create(final SchemaContext context, final SchemaPath path) {
132         return new SchemaTracker(context, path);
133     }
134
135     public Object getParent() {
136         if (schemaStack.isEmpty()) {
137             return root;
138         }
139         return schemaStack.peek();
140     }
141
142     private SchemaNode getSchema(final PathArgument name) {
143         final Object parent = getParent();
144         SchemaNode schema = null;
145         final QName qname = name.getNodeType();
146         if(parent instanceof DataNodeContainer) {
147             schema = ((DataNodeContainer)parent).getDataChildByName(qname);
148
149             if(schema == null && parent instanceof GroupingDefinition) {
150                 schema = ((GroupingDefinition) parent);
151             }
152
153             if(schema == null && parent instanceof NotificationDefinition) {
154                 schema = ((NotificationDefinition) parent);
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         Preconditions.checkArgument(schema != null, "Could not find schema for node %s in %s", qname, parent);
162         return schema;
163     }
164
165     private static SchemaNode findChildInCases(final ChoiceSchemaNode parent, final QName qname) {
166         DataSchemaNode schema = null;
167         for(final ChoiceCaseNode caze : parent.getCases()) {
168             final DataSchemaNode potential = caze.getDataChildByName(qname);
169             if(potential != null) {
170                 schema = potential;
171                 break;
172             }
173         }
174         return schema;
175     }
176
177     private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
178         DataSchemaNode schema = null;
179         for(final ChoiceCaseNode caze : parent.getCases()) {
180             final DataSchemaNode potential = caze.getDataChildByName(qname);
181             if(potential != null) {
182                 schema = caze;
183                 break;
184             }
185         }
186         return schema;
187     }
188
189     public void startList(final PathArgument name) {
190         final SchemaNode schema = getSchema(name);
191         Preconditions.checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema.getPath());
192         schemaStack.push(schema);
193     }
194
195     public void startListItem(final PathArgument name) throws IOException {
196         final Object schema = getParent();
197         Preconditions.checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
198         schemaStack.push(schema);
199     }
200
201     public LeafSchemaNode leafNode(final NodeIdentifier name) throws IOException {
202         final SchemaNode schema = getSchema(name);
203
204         Preconditions.checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema.getPath());
205         return (LeafSchemaNode) schema;
206     }
207
208     public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
209         final SchemaNode schema = getSchema(name);
210
211         Preconditions.checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema.getPath());
212         schemaStack.push(schema);
213         return (LeafListSchemaNode)schema;
214     }
215
216     /*
217      * FIXME: This method is kept for API compatability in stable/beryllium and should be removed in boron.
218      * It has been marked Deprecated to dissuade continued use in the stable/beryllium branch.
219      */
220     @Deprecated
221     public LeafListSchemaNode leafSetEntryNode() {
222         final Object parent = getParent();
223
224         Preconditions.checkArgument(parent instanceof LeafListSchemaNode, "Not currently in a leaf-list");
225         return (LeafListSchemaNode) parent;
226     }
227
228     public LeafListSchemaNode leafSetEntryNode(final QName qname) {
229         final Object parent = getParent();
230         if (parent instanceof LeafListSchemaNode) {
231             return (LeafListSchemaNode) parent;
232         } else {
233             final SchemaNode child = getChild((SchemaNode) parent, qname);
234             Preconditions.checkArgument(child instanceof LeafListSchemaNode,
235                     "Node %s is neither a leaf-list nor currently in a leaf-list", child.getPath());
236             return (LeafListSchemaNode) child;
237         }
238     }
239
240     public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
241         LOG.debug("Enter choice {}", name);
242         final SchemaNode schema = getSchema(name);
243
244         Preconditions.checkArgument(schema instanceof ChoiceSchemaNode, "Node %s is not a choice", schema.getPath());
245         schemaStack.push(schema);
246         return (ChoiceSchemaNode)schema;
247     }
248
249     public SchemaNode startContainerNode(final NodeIdentifier name) {
250         LOG.debug("Enter container {}", name);
251         final SchemaNode schema = getSchema(name);
252
253         boolean isAllowed = schema instanceof ContainerSchemaNode;
254         isAllowed |= schema instanceof NotificationDefinition;
255
256         Preconditions.checkArgument(isAllowed, "Node %s is not a container nor a notification", schema.getPath());
257         schemaStack.push(schema);
258
259         return schema;
260     }
261
262     public SchemaNode startYangModeledAnyXmlNode(final NodeIdentifier name) {
263         LOG.debug("Enter yang modeled anyXml {}", name);
264         final SchemaNode schema = getSchema(name);
265
266         Preconditions.checkArgument(schema instanceof YangModeledAnyXmlSchemaNode,
267                 "Node %s is not an yang modeled anyXml.", schema.getPath());
268
269         schemaStack.push(((YangModeledAnyXmlSchemaNode) schema).getSchemaOfAnyXmlData());
270
271         return schema;
272     }
273
274     public AugmentationSchema startAugmentationNode(final AugmentationIdentifier identifier) {
275         LOG.debug("Enter augmentation {}", identifier);
276         Object parent = getParent();
277
278         Preconditions.checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
279         if(parent instanceof ChoiceSchemaNode) {
280             final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
281             parent = findCaseByChild((ChoiceSchemaNode) parent, name);
282         }
283         Preconditions.checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer",parent);
284         final AugmentationSchema schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent, identifier.getPossibleChildNames());
285         final HashSet<DataSchemaNode> realChildSchemas = new HashSet<>();
286         for(final DataSchemaNode child : schema.getChildNodes()) {
287             realChildSchemas.add(((DataNodeContainer) parent).getDataChildByName(child.getQName()));
288         }
289         final AugmentationSchema resolvedSchema = new EffectiveAugmentationSchema(schema, realChildSchemas);
290         schemaStack.push(resolvedSchema);
291         return resolvedSchema;
292     }
293
294     public AnyXmlSchemaNode anyxmlNode(final NodeIdentifier name) {
295         final SchemaNode schema = getSchema(name);
296
297         Preconditions.checkArgument(schema instanceof AnyXmlSchemaNode, "Node %s is not anyxml", schema.getPath());
298         return (AnyXmlSchemaNode)schema;
299     }
300
301     public Object endNode() {
302         return schemaStack.pop();
303     }
304
305     private static final class SchemaNodePredicate implements Predicate<SchemaNode> {
306         private final QName qname;
307
308         public SchemaNodePredicate(final QName qname) {
309             this.qname = qname;
310         }
311
312         @Override
313         public boolean apply(final SchemaNode input) {
314             return input.getQName().equals(qname);
315         }
316     }
317 }