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