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