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