41a412c9111bf400436e67523da20a68b7d700a0
[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.HashSet;
19 import java.util.Optional;
20 import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyXmlSchemaNode;
21 import org.opendaylight.yangtools.yang.common.QName;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
25 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
26 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
27 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
30 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
34 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
36 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
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         final Collection<SchemaNode> schemaNodes = SchemaUtils.findParentSchemaNodesOnPath(context, path);
59         checkArgument(!schemaNodes.isEmpty(), "Unable to find schema node for supplied schema path: %s", 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         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         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 CaseSchemaNode caze : parent.getCases().values()) {
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 CaseSchemaNode caze : parent.getCases().values()) {
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         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(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 LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
166         final SchemaNode schema = getSchema(name);
167
168         checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema.getPath());
169         schemaStack.push(schema);
170         return (LeafListSchemaNode)schema;
171     }
172
173     public LeafListSchemaNode leafSetEntryNode(final QName qname) {
174         final Object parent = getParent();
175         if (parent instanceof LeafListSchemaNode) {
176             return (LeafListSchemaNode) parent;
177         }
178
179         final SchemaNode child = SchemaUtils.findDataChildSchemaByQName((SchemaNode) parent, qname);
180         checkArgument(child instanceof LeafListSchemaNode,
181             "Node %s is neither a leaf-list nor currently in a leaf-list", child.getPath());
182         return (LeafListSchemaNode) child;
183     }
184
185     public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
186         LOG.debug("Enter choice {}", name);
187         final SchemaNode schema = getSchema(name);
188
189         checkArgument(schema instanceof ChoiceSchemaNode, "Node %s is not a choice", schema.getPath());
190         schemaStack.push(schema);
191         return (ChoiceSchemaNode)schema;
192     }
193
194     public SchemaNode startContainerNode(final NodeIdentifier name) {
195         LOG.debug("Enter container {}", name);
196         final SchemaNode schema = getSchema(name);
197
198         boolean isAllowed = schema instanceof ContainerSchemaNode;
199         isAllowed |= schema instanceof NotificationDefinition;
200
201         checkArgument(isAllowed, "Node %s is not a container nor a notification", schema.getPath());
202         schemaStack.push(schema);
203
204         return schema;
205     }
206
207     public SchemaNode startYangModeledAnyXmlNode(final NodeIdentifier name) {
208         LOG.debug("Enter yang modeled anyXml {}", name);
209         final SchemaNode schema = getSchema(name);
210
211         checkArgument(schema instanceof YangModeledAnyXmlSchemaNode, "Node %s is not an yang modeled anyXml.",
212             schema.getPath());
213
214         schemaStack.push(((YangModeledAnyXmlSchemaNode) schema).getSchemaOfAnyXmlData());
215
216         return schema;
217     }
218
219     public AugmentationSchemaNode startAugmentationNode(final AugmentationIdentifier identifier) {
220         LOG.debug("Enter augmentation {}", identifier);
221         Object parent = getParent();
222
223         checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
224         if (parent instanceof ChoiceSchemaNode) {
225             final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
226             parent = findCaseByChild((ChoiceSchemaNode) parent, name);
227         }
228         checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer", parent);
229         final AugmentationSchemaNode schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent,
230             identifier.getPossibleChildNames());
231         final HashSet<DataSchemaNode> realChildSchemas = new HashSet<>();
232         for (final DataSchemaNode child : schema.getChildNodes()) {
233             realChildSchemas.add(((DataNodeContainer) parent).getDataChildByName(child.getQName()));
234         }
235         final AugmentationSchemaNode resolvedSchema = new EffectiveAugmentationSchema(schema, realChildSchemas);
236         schemaStack.push(resolvedSchema);
237         return resolvedSchema;
238     }
239
240     public AnyXmlSchemaNode anyxmlNode(final NodeIdentifier name) {
241         final SchemaNode schema = getSchema(name);
242         checkArgument(schema instanceof AnyXmlSchemaNode, "Node %s is not anyxml", schema.getPath());
243         return (AnyXmlSchemaNode)schema;
244     }
245
246     public Object endNode() {
247         return schemaStack.pop();
248     }
249 }