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.AugmentationIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
31 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
35 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
38 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
41 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
42 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
43 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
49 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
51 import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
52 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
53 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeEffectiveStatement;
54 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
55 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
56 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
57 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
58 import org.opendaylight.yangtools.yang.model.util.LeafrefResolver;
59 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
60 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
65 * Utility class for tracking schema state underlying a {@link NormalizedNode} structure.
68 public final class NormalizedNodeStreamWriterStack implements LeafrefResolver {
69 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeStreamWriterStack.class);
71 private final Deque<WithStatus> schemaStack = new ArrayDeque<>();
72 private final SchemaInferenceStack dataTree;
73 private final DataNodeContainer root;
75 private NormalizedNodeStreamWriterStack(final EffectiveModelContext context) {
76 dataTree = SchemaInferenceStack.of(context);
77 root = requireNonNull(context);
80 private NormalizedNodeStreamWriterStack(final SchemaInferenceStack dataTree) {
81 this.dataTree = requireNonNull(dataTree);
82 if (!dataTree.isEmpty()) {
83 final EffectiveStatement<?, ?> current = dataTree.currentStatement();
84 checkArgument(current instanceof DataNodeContainer, "Cannot instantiate on %s", current);
86 root = (DataNodeContainer) current;
88 root = dataTree.getEffectiveModelContext();
93 * Create a new writer with the specified inference state as its root.
95 * @param root Root inference state
96 * @return A new {@link NormalizedNodeStreamWriter}
97 * @throws NullPointerException if {@code root} is null
99 public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveStatementInference root) {
100 return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.ofInference(root));
104 * Create a new writer with the specified inference state as its root.
106 * @param root Root inference state
107 * @return A new {@link NormalizedNodeStreamWriter}
108 * @throws NullPointerException if {@code root} is null
110 public static @NonNull NormalizedNodeStreamWriterStack of(final Inference root) {
111 return new NormalizedNodeStreamWriterStack(root.toSchemaInferenceStack());
115 * Create a new writer at the root of specified {@link EffectiveModelContext}.
117 * @param context effective model context
118 * @return A new {@link NormalizedNodeStreamWriter}
119 * @throws NullPointerException if {@code context} is null
121 public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context) {
122 return new NormalizedNodeStreamWriterStack(context);
126 * Create a new writer with the specified context and rooted in the specified schema path.
128 * @param context Associated {@link EffectiveModelContext}
129 * @param path schema path
130 * @return A new {@link NormalizedNodeStreamWriterStack}
131 * @throws NullPointerException if any argument is null
132 * @throws IllegalArgumentException if {@code path} does not point to a valid root
134 public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
135 final Absolute path) {
136 return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.of(context, path));
140 * Create a new writer with the specified context and rooted in the specified schema path.
142 * @param context Associated {@link EffectiveModelContext}
143 * @param path schema path
144 * @return A new {@link NormalizedNodeStreamWriterStack}
145 * @throws NullPointerException if any argument is null
146 * @throws IllegalArgumentException if {@code path} does not point to a valid root
149 public static @NonNull NormalizedNodeStreamWriterStack of(final EffectiveModelContext context,
150 final SchemaPath path) {
151 return new NormalizedNodeStreamWriterStack(SchemaInferenceStack.ofInstantiatedPath(context, path));
155 * Create a new writer with the specified context and rooted in the specified schema path.
157 * @param context Associated {@link EffectiveModelContext}
158 * @param operation Operation schema path
159 * @param qname Input/Output container QName
160 * @return A new {@link NormalizedNodeStreamWriter}
161 * @throws NullPointerException if any argument is null
162 * @throws IllegalArgumentException if {@code operation} does not point to an actual operation or if {@code qname}
163 * does not identify a valid root underneath it.
165 public static @NonNull NormalizedNodeStreamWriterStack ofOperation(final EffectiveModelContext context,
166 final Absolute operation, final QName qname) {
167 final SchemaInferenceStack stack = SchemaInferenceStack.of(context, operation);
168 final EffectiveStatement<?, ?> current = stack.currentStatement();
169 checkArgument(current instanceof RpcEffectiveStatement || current instanceof ActionEffectiveStatement,
170 "Path %s resolved into non-operation %s", operation, current);
171 stack.enterSchemaTree(qname);
172 return new NormalizedNodeStreamWriterStack(stack);
176 public TypeDefinition<?> resolveLeafref(final LeafrefTypeDefinition type) {
177 return dataTree.resolveLeafref(type);
180 public Object getParent() {
181 final WithStatus schema = schemaStack.peek();
182 return schema == null ? root : schema;
185 private SchemaNode enterDataTree(final PathArgument name) {
186 final QName qname = name.getNodeType();
187 final DataTreeEffectiveStatement<?> stmt = dataTree.enterDataTree(qname);
188 verify(stmt instanceof SchemaNode, "Unexpected result %s", stmt);
189 final SchemaNode ret = (SchemaNode) stmt;
190 final Object parent = getParent();
191 if (parent instanceof ChoiceSchemaNode) {
192 final DataSchemaNode check = ((ChoiceSchemaNode) parent).findDataSchemaChild(qname).orElse(null);
193 verify(check == ret, "Data tree result %s does not match choice result %s", ret, check);
198 public void startList(final PathArgument name) {
199 final SchemaNode schema = enterDataTree(name);
200 checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema);
201 schemaStack.push(schema);
204 public void startListItem(final PathArgument name) throws IOException {
205 final Object schema = getParent();
206 checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
207 schemaStack.push((ListSchemaNode) schema);
210 public void startLeafNode(final NodeIdentifier name) throws IOException {
211 final SchemaNode schema = enterDataTree(name);
212 checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema);
213 schemaStack.push(schema);
216 public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
217 final SchemaNode schema = enterDataTree(name);
218 checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema);
219 schemaStack.push(schema);
220 return (LeafListSchemaNode) schema;
223 public LeafListSchemaNode leafSetEntryNode(final QName qname) {
224 final Object parent = getParent();
225 if (parent instanceof LeafListSchemaNode) {
226 return (LeafListSchemaNode) parent;
228 checkArgument(parent instanceof DataNodeContainer, "Cannot lookup %s in parent %s", qname, parent);
229 final DataSchemaNode child = ((DataNodeContainer) parent).dataChildByName(qname);
230 checkArgument(child instanceof LeafListSchemaNode,
231 "Node %s is neither a leaf-list nor currently in a leaf-list", child);
232 return (LeafListSchemaNode) child;
235 public void startLeafSetEntryNode(final NodeWithValue<?> name) {
236 schemaStack.push(leafSetEntryNode(name.getNodeType()));
239 public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
240 LOG.debug("Enter choice {}", name);
241 final ChoiceEffectiveStatement stmt = dataTree.enterChoice(name.getNodeType());
242 verify(stmt instanceof ChoiceSchemaNode, "Node %s is not a choice", stmt);
243 final ChoiceSchemaNode ret = (ChoiceSchemaNode) stmt;
244 schemaStack.push(ret);
248 public SchemaNode startContainerNode(final NodeIdentifier name) {
249 LOG.debug("Enter container {}", name);
251 final SchemaNode schema;
252 if (schemaStack.isEmpty() && root instanceof NotificationDefinition) {
253 // Special case for stacks initialized at notification. We pretend the first container is contained within
255 // FIXME: 8.0.0: factor this special case out to something more reasonable, like being initialized at the
256 // Notification's parent and knowing to enterSchemaTree() instead of enterDataTree().
257 schema = (NotificationDefinition) root;
259 schema = enterDataTree(name);
260 checkArgument(schema instanceof ContainerLike, "Node %s is not a container", schema);
263 schemaStack.push(schema);
267 public void startAnyxmlNode(final NodeIdentifier name) {
268 final SchemaNode schema = enterDataTree(name);
269 checkArgument(schema instanceof AnyxmlSchemaNode, "Node %s is not anyxml", schema);
270 schemaStack.push(schema);
273 public void startAnydataNode(final NodeIdentifier name) {
274 final SchemaNode schema = enterDataTree(name);
275 checkArgument(schema instanceof AnydataSchemaNode, "Node %s is not anydata", schema);
276 schemaStack.push(schema);
279 public Object endNode() {
280 final Object ret = schemaStack.pop();
281 // If this is a data tree node, make sure it is updated. Before that, though, we need to check if this is not
282 // actually listEntry -> list or leafListEntry -> leafList exit.
283 if (!(ret instanceof AugmentationSchemaNode) && getParent() != ret) {
289 public AugmentationSchemaNode startAugmentationNode(final AugmentationIdentifier identifier) {
290 LOG.debug("Enter augmentation {}", identifier);
291 Object parent = getParent();
293 checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
294 if (parent instanceof ChoiceSchemaNode) {
295 final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
296 parent = findCaseByChild((ChoiceSchemaNode) parent, name);
298 checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer", parent);
299 final AugmentationSchemaNode schema = findSchemaForAugment((AugmentationTarget) parent,
300 identifier.getPossibleChildNames());
301 final AugmentationSchemaNode resolvedSchema = EffectiveAugmentationSchema.create(schema,
302 (DataNodeContainer) parent);
303 schemaStack.push(resolvedSchema);
304 return resolvedSchema;
307 // FIXME: 7.0.0: can we get rid of this?
308 private static @NonNull AugmentationSchemaNode findSchemaForAugment(final AugmentationTarget schema,
309 final Set<QName> qnames) {
310 for (final AugmentationSchemaNode augment : schema.getAvailableAugmentations()) {
311 if (qnames.equals(augment.getChildNodes().stream()
312 .map(DataSchemaNode::getQName)
313 .collect(Collectors.toUnmodifiableSet()))) {
318 throw new IllegalStateException(
319 "Unknown augmentation node detected, identified by: " + qnames + ", in: " + schema);
322 // FIXME: 7.0.0: can we get rid of this?
323 private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
324 for (final CaseSchemaNode caze : parent.getCases()) {
325 final Optional<DataSchemaNode> potential = caze.findDataChildByName(qname);
326 if (potential.isPresent()) {