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