2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3 * Copyright (c) 2021 PANTHEON.tech, s.r.o.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.yangtools.yang.data.util;
11 import static com.google.common.base.Preconditions.checkArgument;
12 import static com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.annotations.Beta;
16 import com.google.common.collect.Iterables;
17 import java.io.IOException;
18 import java.util.ArrayDeque;
19 import java.util.Deque;
20 import java.util.Optional;
22 import java.util.stream.Collectors;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
32 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
36 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
39 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
40 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
42 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
43 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
44 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
50 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
52 import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
53 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
54 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeEffectiveStatement;
55 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
56 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
57 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
59 import org.opendaylight.yangtools.yang.model.util.LeafrefResolver;
60 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
61 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
66 * Utility class for tracking schema state underlying a {@link NormalizedNode} structure.
69 public final class NormalizedNodeStreamWriterStack implements LeafrefResolver {
70 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeStreamWriterStack.class);
72 private final Deque<WithStatus> schemaStack = new ArrayDeque<>();
73 private final SchemaInferenceStack dataTree;
74 private final DataNodeContainer root;
76 private NormalizedNodeStreamWriterStack(final EffectiveModelContext context) {
77 dataTree = SchemaInferenceStack.of(context);
78 root = requireNonNull(context);
81 private NormalizedNodeStreamWriterStack(final SchemaInferenceStack dataTree) {
82 this.dataTree = requireNonNull(dataTree);
83 if (!dataTree.isEmpty()) {
84 final EffectiveStatement<?, ?> current = dataTree.currentStatement();
85 checkArgument(current instanceof DataNodeContainer, "Cannot instantiate on %s", current);
87 root = (DataNodeContainer) current;
89 root = dataTree.getEffectiveModelContext();
94 * Create a new writer with the specified inference state as its root.
96 * @param root Root inference state
97 * @return A new {@link NormalizedNodeStreamWriter}
98 * @throws NullPointerException if {@code root} is null
100 public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveStatementInference root) {
101 return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.ofInference(root));
105 * Create a new writer with the specified inference state as its root.
107 * @param root Root inference state
108 * @return A new {@link NormalizedNodeStreamWriter}
109 * @throws NullPointerException if {@code root} is null
111 public static @NonNull NormalizedNodeStreamWriterStack of(final Inference root) {
112 return new NormalizedNodeStreamWriterStack(root.toSchemaInferenceStack());
116 * Create a new writer at the root of specified {@link EffectiveModelContext}.
118 * @param context effective model context
119 * @return A new {@link NormalizedNodeStreamWriter}
120 * @throws NullPointerException if {@code context} is null
122 public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context) {
123 return new NormalizedNodeStreamWriterStack(context);
127 * Create a new writer with the specified context and rooted in the specified schema path.
129 * @param context Associated {@link EffectiveModelContext}
130 * @param path schema path
131 * @return A new {@link NormalizedNodeStreamWriterStack}
132 * @throws NullPointerException if any argument is null
133 * @throws IllegalArgumentException if {@code path} does not point to a valid root
135 public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
136 final Absolute path) {
137 return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.of(context, path));
141 * Create a new writer with the specified context and rooted in the specified {@link YangInstanceIdentifier}..
143 * @param context Associated {@link EffectiveModelContext}
144 * @param path Normalized path
145 * @return A new {@link NormalizedNodeStreamWriterStack}
146 * @throws NullPointerException if any argument is null
147 * @throws IllegalArgumentException if {@code path} does not point to a valid root
149 public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
150 final YangInstanceIdentifier path) {
151 return new NormalizedNodeStreamWriterStack(DataSchemaContextTree.from(context)
158 * Create a new writer with the specified context and rooted in the specified schema path.
160 * @param context Associated {@link EffectiveModelContext}
161 * @param path schema path
162 * @return A new {@link NormalizedNodeStreamWriterStack}
163 * @throws NullPointerException if any argument is null
164 * @throws IllegalArgumentException if {@code path} does not point to a valid root
167 public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
168 final SchemaPath path) {
169 return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.ofSchemaPath(context, path));
173 * Create a new writer with the specified context and rooted in the specified schema path.
175 * @param context Associated {@link EffectiveModelContext}
176 * @param operation Operation schema path
177 * @param qname Input/Output container QName
178 * @return A new {@link NormalizedNodeStreamWriter}
179 * @throws NullPointerException if any argument is null
180 * @throws IllegalArgumentException if {@code operation} does not point to an actual operation or if {@code qname}
181 * does not identify a valid root underneath it.
183 public static @NonNull NormalizedNodeStreamWriterStack ofOperation(final EffectiveModelContext context,
184 final Absolute operation, final QName qname) {
185 final SchemaInferenceStack stack = SchemaInferenceStack.of(context, operation);
186 final EffectiveStatement<?, ?> current = stack.currentStatement();
187 checkArgument(current instanceof RpcEffectiveStatement || current instanceof ActionEffectiveStatement,
188 "Path %s resolved into non-operation %s", operation, current);
189 stack.enterSchemaTree(qname);
190 return new NormalizedNodeStreamWriterStack(stack);
194 public TypeDefinition<?> resolveLeafref(final LeafrefTypeDefinition type) {
195 return dataTree.resolveLeafref(type);
198 public Object getParent() {
199 final WithStatus schema = schemaStack.peek();
200 return schema == null ? root : schema;
203 private SchemaNode enterDataTree(final PathArgument name) {
204 final QName qname = name.getNodeType();
205 final DataTreeEffectiveStatement<?> stmt = dataTree.enterDataTree(qname);
206 verify(stmt instanceof SchemaNode, "Unexpected result %s", stmt);
207 final SchemaNode ret = (SchemaNode) stmt;
208 final Object parent = getParent();
209 if (parent instanceof ChoiceSchemaNode) {
210 final DataSchemaNode check = ((ChoiceSchemaNode) parent).findDataSchemaChild(qname).orElse(null);
211 verify(check == ret, "Data tree result %s does not match choice result %s", ret, check);
216 public void startList(final PathArgument name) {
217 final SchemaNode schema = enterDataTree(name);
218 checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema);
219 schemaStack.push(schema);
222 public void startListItem(final PathArgument name) throws IOException {
223 final Object schema = getParent();
224 checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
225 schemaStack.push((ListSchemaNode) schema);
228 public void startLeafNode(final NodeIdentifier name) throws IOException {
229 final SchemaNode schema = enterDataTree(name);
230 checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema);
231 schemaStack.push(schema);
234 public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
235 final SchemaNode schema = enterDataTree(name);
236 checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema);
237 schemaStack.push(schema);
238 return (LeafListSchemaNode) schema;
241 public LeafListSchemaNode leafSetEntryNode(final QName qname) {
242 final Object parent = getParent();
243 if (parent instanceof LeafListSchemaNode) {
244 return (LeafListSchemaNode) parent;
246 checkArgument(parent instanceof DataNodeContainer, "Cannot lookup %s in parent %s", qname, parent);
247 final DataSchemaNode child = ((DataNodeContainer) parent).dataChildByName(qname);
248 checkArgument(child instanceof LeafListSchemaNode,
249 "Node %s is neither a leaf-list nor currently in a leaf-list", child);
250 return (LeafListSchemaNode) child;
253 public void startLeafSetEntryNode(final NodeWithValue<?> name) {
254 schemaStack.push(leafSetEntryNode(name.getNodeType()));
257 public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
258 LOG.debug("Enter choice {}", name);
259 final ChoiceEffectiveStatement stmt = dataTree.enterChoice(name.getNodeType());
260 verify(stmt instanceof ChoiceSchemaNode, "Node %s is not a choice", stmt);
261 final ChoiceSchemaNode ret = (ChoiceSchemaNode) stmt;
262 schemaStack.push(ret);
266 public SchemaNode startContainerNode(final NodeIdentifier name) {
267 LOG.debug("Enter container {}", name);
269 final SchemaNode schema;
270 if (schemaStack.isEmpty() && root instanceof NotificationDefinition) {
271 // Special case for stacks initialized at notification. We pretend the first container is contained within
273 // FIXME: 8.0.0: factor this special case out to something more reasonable, like being initialized at the
274 // Notification's parent and knowing to enterSchemaTree() instead of enterDataTree().
275 schema = (NotificationDefinition) root;
277 schema = enterDataTree(name);
278 checkArgument(schema instanceof ContainerLike, "Node %s is not a container", schema);
281 schemaStack.push(schema);
285 public void startAnyxmlNode(final NodeIdentifier name) {
286 final SchemaNode schema = enterDataTree(name);
287 checkArgument(schema instanceof AnyxmlSchemaNode, "Node %s is not anyxml", schema);
288 schemaStack.push(schema);
291 public void startAnydataNode(final NodeIdentifier name) {
292 final SchemaNode schema = enterDataTree(name);
293 checkArgument(schema instanceof AnydataSchemaNode, "Node %s is not anydata", schema);
294 schemaStack.push(schema);
297 public Object endNode() {
298 final Object ret = schemaStack.pop();
299 // If this is a data tree node, make sure it is updated. Before that, though, we need to check if this is not
300 // actually listEntry -> list or leafListEntry -> leafList exit.
301 if (!(ret instanceof AugmentationSchemaNode) && getParent() != ret) {
307 public AugmentationSchemaNode startAugmentationNode(final AugmentationIdentifier identifier) {
308 LOG.debug("Enter augmentation {}", identifier);
309 Object parent = getParent();
311 checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
312 if (parent instanceof ChoiceSchemaNode) {
313 final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
314 parent = findCaseByChild((ChoiceSchemaNode) parent, name);
316 checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer", parent);
317 final AugmentationSchemaNode schema = findSchemaForAugment((AugmentationTarget) parent,
318 identifier.getPossibleChildNames());
319 final AugmentationSchemaNode resolvedSchema = EffectiveAugmentationSchema.create(schema,
320 (DataNodeContainer) parent);
321 schemaStack.push(resolvedSchema);
322 return resolvedSchema;
325 // FIXME: 7.0.0: can we get rid of this?
326 private static @NonNull AugmentationSchemaNode findSchemaForAugment(final AugmentationTarget schema,
327 final Set<QName> qnames) {
328 for (final AugmentationSchemaNode augment : schema.getAvailableAugmentations()) {
329 if (qnames.equals(augment.getChildNodes().stream()
330 .map(DataSchemaNode::getQName)
331 .collect(Collectors.toUnmodifiableSet()))) {
336 throw new IllegalStateException(
337 "Unknown augmentation node detected, identified by: " + qnames + ", in: " + schema);
340 // FIXME: 7.0.0: can we get rid of this?
341 private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
342 for (final CaseSchemaNode caze : parent.getCases()) {
343 final Optional<DataSchemaNode> potential = caze.findDataChildByName(qname);
344 if (potential.isPresent()) {