2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.impl.schema.tree;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verifyNotNull;
13 import java.util.List;
14 import java.util.Optional;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
20 import org.opendaylight.yangtools.yang.data.api.schema.AnydataNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
29 import org.opendaylight.yangtools.yang.data.spi.tree.TreeNode;
30 import org.opendaylight.yangtools.yang.data.spi.tree.Version;
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.ChoiceSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
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.LeafListSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 abstract class SchemaAwareApplyOperation<T extends WithStatus> extends ModificationApplyOperation {
48 private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
50 static ModificationApplyOperation from(final DataSchemaNode schemaNode,
51 final DataTreeConfiguration treeConfig) throws ExcludedDataSchemaNodeException {
52 if (!belongsToTree(treeConfig.getTreeType(), schemaNode)) {
53 throw new ExcludedDataSchemaNodeException(schemaNode + " does not belong to configuration tree");
55 if (schemaNode instanceof ContainerSchemaNode) {
56 return ContainerModificationStrategy.of((ContainerSchemaNode) schemaNode, treeConfig);
57 } else if (schemaNode instanceof ListSchemaNode) {
58 return fromListSchemaNode((ListSchemaNode) schemaNode, treeConfig);
59 } else if (schemaNode instanceof ChoiceSchemaNode) {
60 return new ChoiceModificationStrategy((ChoiceSchemaNode) schemaNode, treeConfig);
61 } else if (schemaNode instanceof LeafListSchemaNode) {
62 return MinMaxElementsValidation.from(new LeafSetModificationStrategy((LeafListSchemaNode) schemaNode,
64 } else if (schemaNode instanceof LeafSchemaNode) {
65 return new ValueNodeModificationStrategy<>(LeafNode.class, (LeafSchemaNode) schemaNode);
66 } else if (schemaNode instanceof AnydataSchemaNode) {
67 return new ValueNodeModificationStrategy<>(AnydataNode.class, (AnydataSchemaNode) schemaNode);
68 } else if (schemaNode instanceof AnyxmlSchemaNode) {
69 return new ValueNodeModificationStrategy<>(AnyxmlNode.class, (AnyxmlSchemaNode) schemaNode);
70 } else if (schemaNode instanceof SchemaContext) {
71 return new StructuralContainerModificationStrategy((SchemaContext) schemaNode, treeConfig);
73 throw new IllegalStateException("Unsupported schema " + schemaNode);
77 static @Nullable AugmentationModificationStrategy from(final DataNodeContainer resolvedTree,
78 final AugmentationTarget augSchemas, final AugmentationIdentifier identifier,
79 final DataTreeConfiguration treeConfig) {
80 for (final AugmentationSchemaNode potential : augSchemas.getAvailableAugmentations()) {
81 for (final DataSchemaNode child : potential.getChildNodes()) {
82 if (identifier.getPossibleChildNames().contains(child.getQName())) {
83 return new AugmentationModificationStrategy(potential, resolvedTree, treeConfig);
91 static void checkConflicting(final ModificationPath path, final boolean condition, final String message)
92 throws ConflictingModificationAppliedException {
94 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(), message);
98 private static ModificationApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode,
99 final DataTreeConfiguration treeConfig) {
100 final List<QName> keyDefinition = schemaNode.getKeyDefinition();
101 final SchemaAwareApplyOperation<ListSchemaNode> op;
102 if (keyDefinition == null || keyDefinition.isEmpty()) {
103 op = new ListModificationStrategy(schemaNode, treeConfig);
105 op = MapModificationStrategy.of(schemaNode, treeConfig);
108 return UniqueValidation.of(schemaNode, treeConfig, MinMaxElementsValidation.from(op));
111 protected static void checkNotConflicting(final ModificationPath path, final TreeNode original,
112 final TreeNode current) throws ConflictingModificationAppliedException {
113 checkConflicting(path, original.getVersion().equals(current.getVersion()),
114 "Node was replaced by other transaction.");
115 checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
116 "Node children was modified by other transaction");
119 protected final @NonNull ModificationApplyOperation resolveChildOperation(final PathArgument child) {
120 final ModificationApplyOperation potential = childByArg(child);
121 checkArgument(potential != null, "Operation for child %s is not defined.", child);
126 final void checkApplicable(final ModificationPath path, final NodeModification modification,
127 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
128 switch (modification.getOperation()) {
130 checkDeleteApplicable(modification, current);
133 checkTouchApplicable(path, modification, current, version);
136 checkWriteApplicable(path, modification, current, version);
139 checkMergeApplicable(path, modification, current, version);
144 throw new UnsupportedOperationException(
145 "Suplied modification type " + modification.getOperation() + " is not supported.");
150 final void quickVerifyStructure(final NormalizedNode writtenValue) {
151 verifyValue(writtenValue);
155 final void fullVerifyStructure(final NormalizedNode writtenValue) {
156 verifyValue(writtenValue);
157 verifyValueChildren(writtenValue);
161 * Verify the a written value, without performing deeper tree validation.
163 * @param writtenValue Written value
165 abstract void verifyValue(NormalizedNode writtenValue);
168 * Verify the children implied by a written value after the value itself has been verified by
169 * {@link #verifyValue(NormalizedNode)}. Default implementation does nothing.
171 * @param writtenValue Written value
173 void verifyValueChildren(final NormalizedNode writtenValue) {
177 protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
178 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
179 final Optional<? extends TreeNode> original = modification.getOriginal();
180 if (original.isPresent() && current.isPresent()) {
182 * We need to do conflict detection only and only if the value of leaf changed
183 * before two transactions. If value of leaf is unchanged between two transactions
184 * it should not cause transaction to fail, since result of this merge
185 * leads to same data.
187 final TreeNode orig = original.get();
188 final TreeNode cur = current.get();
189 if (!orig.getData().equals(cur.getData())) {
190 checkNotConflicting(path, orig, cur);
196 * Checks if write operation can be applied to current TreeNode.
197 * The operation checks if original tree node to which the modification is going to be applied exists and if
198 * current node in TreeNode structure exists.
200 * @param path Path from current node in TreeNode
201 * @param modification modification to apply
202 * @param current current node in TreeNode for modification to apply
203 * @throws DataValidationFailedException when a data dependency conflict is detected
205 private static void checkWriteApplicable(final ModificationPath path, final NodeModification modification,
206 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
207 final Optional<? extends TreeNode> original = modification.getOriginal();
208 if (original.isPresent() && current.isPresent()) {
209 checkNotConflicting(path, original.get(), current.get());
211 checkConflicting(path, !original.isPresent(), "Node was deleted by other transaction.");
212 checkConflicting(path, !current.isPresent(), "Node was created by other transaction.");
216 private static void checkDeleteApplicable(final NodeModification modification,
217 final Optional<? extends TreeNode> current) {
218 // Delete is always applicable, we do not expose it to subclasses
219 if (!current.isPresent()) {
220 LOG.trace("Delete operation turned to no-op on missing node {}", modification);
225 Optional<? extends TreeNode> apply(final ModifiedNode modification, final Optional<? extends TreeNode> currentMeta,
226 final Version version) {
227 switch (modification.getOperation()) {
229 // Deletion of a non-existing node is a no-op, report it as such
230 modification.resolveModificationType(currentMeta.isPresent() ? ModificationType.DELETE
231 : ModificationType.UNMODIFIED);
232 return modification.setSnapshot(Optional.empty());
234 checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s", modification);
235 return modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.get(),
238 final TreeNode result;
240 if (!currentMeta.isPresent()) {
241 // This is a slight optimization: a merge on a non-existing node equals to a write. Written data
242 // structure is usually verified when the transaction is sealed. To preserve correctness, we have
243 // to run that validation here.
244 modification.resolveModificationType(ModificationType.WRITE);
245 result = applyWrite(modification, modification.getWrittenValue(), currentMeta, version);
246 fullVerifyStructure(result.getData());
248 result = applyMerge(modification, currentMeta.get(), version);
251 return modification.setSnapshot(Optional.of(result));
253 modification.resolveModificationType(ModificationType.WRITE);
254 return modification.setSnapshot(Optional.of(applyWrite(modification,
255 verifyNotNull(modification.getWrittenValue()), currentMeta, version)));
257 modification.resolveModificationType(ModificationType.UNMODIFIED);
260 throw new IllegalArgumentException("Provided modification type is not supported.");
265 * Apply a merge operation. Since the result of merge differs based on the data type
266 * being modified, implementations of this method are responsible for calling
267 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
269 * @param modification Modified node
270 * @param currentMeta Store Metadata Node on which NodeModification should be applied
271 * @param version New subtree version of parent node
272 * @return A sealed TreeNode representing applied operation.
274 protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
276 protected abstract TreeNode applyWrite(ModifiedNode modification, NormalizedNode newValue,
277 Optional<? extends TreeNode> currentMeta, Version version);
280 * Apply a nested operation. Since there may not actually be a nested operation
281 * to be applied, implementations of this method are responsible for calling
282 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
284 * @param modification Modified node
285 * @param currentMeta Store Metadata Node on which NodeModification should be applied
286 * @param version New subtree version of parent node
287 * @return A sealed TreeNode representing applied operation.
289 protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
292 * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
294 * @param path Path to current node
295 * @param modification Node modification which should be applied.
296 * @param current Current state of data tree
297 * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
298 * @throws org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException If subtree
299 * modification is not applicable (e.g. leaf node).
301 protected abstract void checkTouchApplicable(ModificationPath path, NodeModification modification,
302 Optional<? extends TreeNode> current, Version version) throws DataValidationFailedException;
305 * Return the {@link WithStatus}-subclass schema associated with this operation.
306 * @return A model node
308 abstract @NonNull T getSchema();
311 * Checks if supplied schema node belong to specified Data Tree type. All nodes belong to the operational tree,
312 * nodes in configuration tree are marked as such.
314 * @param treeType Tree Type
315 * @param node Schema node
316 * @return {@code true} if the node matches the tree type, {@code false} otherwise.
318 static final boolean belongsToTree(final TreeType treeType, final DataSchemaNode node) {
319 return treeType == TreeType.OPERATIONAL || node.effectiveConfig().orElse(Boolean.TRUE);