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