Remove DelegatingModificationApplyOperation
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / SchemaAwareApplyOperation.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.schema.tree;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verifyNotNull;
12
13 import java.util.List;
14 import java.util.Optional;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
19 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
28 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
35 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 abstract class SchemaAwareApplyOperation<T extends WithStatus> extends ModificationApplyOperation {
42     private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
43
44     public static ModificationApplyOperation from(final DataSchemaNode schemaNode,
45             final DataTreeConfiguration treeConfig) {
46         if (treeConfig.getTreeType() == TreeType.CONFIGURATION) {
47             checkArgument(schemaNode.isConfiguration(), "Supplied %s does not belongs to configuration tree.",
48                 schemaNode.getPath());
49         }
50         if (schemaNode instanceof ContainerSchemaNode) {
51             return ContainerModificationStrategy.of((ContainerSchemaNode) schemaNode, treeConfig);
52         } else if (schemaNode instanceof ListSchemaNode) {
53             return fromListSchemaNode((ListSchemaNode) schemaNode, treeConfig);
54         } else if (schemaNode instanceof ChoiceSchemaNode) {
55             return new ChoiceModificationStrategy((ChoiceSchemaNode) schemaNode, treeConfig);
56         } else if (schemaNode instanceof LeafListSchemaNode) {
57             return MinMaxElementsValidation.from(new LeafSetModificationStrategy((LeafListSchemaNode) schemaNode,
58                 treeConfig));
59         } else if (schemaNode instanceof LeafSchemaNode) {
60             return new ValueNodeModificationStrategy<>(LeafNode.class, (LeafSchemaNode) schemaNode);
61         }
62         throw new IllegalArgumentException("Not supported schema node type for " + schemaNode.getClass());
63     }
64
65     public static AugmentationModificationStrategy from(final DataNodeContainer resolvedTree,
66             final AugmentationTarget augSchemas, final AugmentationIdentifier identifier,
67             final DataTreeConfiguration treeConfig) {
68         for (final AugmentationSchemaNode potential : augSchemas.getAvailableAugmentations()) {
69             for (final DataSchemaNode child : potential.getChildNodes()) {
70                 if (identifier.getPossibleChildNames().contains(child.getQName())) {
71                     return new AugmentationModificationStrategy(potential, resolvedTree, treeConfig);
72                 }
73             }
74         }
75
76         return null;
77     }
78
79     static void checkConflicting(final ModificationPath path, final boolean condition, final String message)
80             throws ConflictingModificationAppliedException {
81         if (!condition) {
82             throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(), message);
83         }
84     }
85
86     private static ModificationApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode,
87             final DataTreeConfiguration treeConfig) {
88         final List<QName> keyDefinition = schemaNode.getKeyDefinition();
89         final SchemaAwareApplyOperation<ListSchemaNode> op;
90         if (keyDefinition == null || keyDefinition.isEmpty()) {
91             op = new UnkeyedListModificationStrategy(schemaNode, treeConfig);
92         } else {
93             op = MapModificationStrategy.of(schemaNode, treeConfig);
94         }
95
96         return MinMaxElementsValidation.from(op);
97     }
98
99     protected static void checkNotConflicting(final ModificationPath path, final TreeNode original,
100             final TreeNode current) throws ConflictingModificationAppliedException {
101         checkConflicting(path, original.getVersion().equals(current.getVersion()),
102                 "Node was replaced by other transaction.");
103         checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
104                 "Node children was modified by other transaction");
105     }
106
107     protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
108         final Optional<ModificationApplyOperation> potential = getChild(child);
109         checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
110         return potential.get();
111     }
112
113     @Override
114     void checkApplicable(final ModificationPath path, final NodeModification modification,
115             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
116         switch (modification.getOperation()) {
117             case DELETE:
118                 checkDeleteApplicable(modification, current);
119                 break;
120             case TOUCH:
121                 checkTouchApplicable(path, modification, current, version);
122                 break;
123             case WRITE:
124                 checkWriteApplicable(path, modification, current, version);
125                 break;
126             case MERGE:
127                 checkMergeApplicable(path, modification, current, version);
128                 break;
129             case NONE:
130                 break;
131             default:
132                 throw new UnsupportedOperationException(
133                     "Suplied modification type " + modification.getOperation() + " is not supported.");
134         }
135     }
136
137     @Override
138     final void quickVerifyStructure(final NormalizedNode<?, ?> writtenValue) {
139         verifyValue(writtenValue);
140     }
141
142     @Override
143     final void fullVerifyStructure(final NormalizedNode<?, ?> writtenValue) {
144         verifyValue(writtenValue);
145         verifyValueChildren(writtenValue);
146     }
147
148     /**
149      * Verify the a written value, without performing deeper tree validation.
150      *
151      * @param writtenValue Written value
152      */
153     abstract void verifyValue(NormalizedNode<?, ?> writtenValue);
154
155     /**
156      * Verify the children implied by a written value after the value itself has been verified by
157      * {@link #verifyValue(NormalizedNode)}. Default implementation does nothing.
158      *
159      * @param writtenValue Written value
160      */
161     void verifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
162         // Defaults to no-op
163     }
164
165     protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
166             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
167         final Optional<TreeNode> original = modification.getOriginal();
168         if (original.isPresent() && current.isPresent()) {
169             /*
170              * We need to do conflict detection only and only if the value of leaf changed
171              * before two transactions. If value of leaf is unchanged between two transactions
172              * it should not cause transaction to fail, since result of this merge
173              * leads to same data.
174              */
175             final TreeNode orig = original.get();
176             final TreeNode cur = current.get();
177             if (!orig.getData().equals(cur.getData())) {
178                 checkNotConflicting(path, orig, cur);
179             }
180         }
181     }
182
183     /**
184      * Checks if write operation can be applied to current TreeNode.
185      * The operation checks if original tree node to which the modification is going to be applied exists and if
186      * current node in TreeNode structure exists.
187      *
188      * @param path Path from current node in TreeNode
189      * @param modification modification to apply
190      * @param current current node in TreeNode for modification to apply
191      * @throws DataValidationFailedException when a data dependency conflict is detected
192      */
193     private static void checkWriteApplicable(final ModificationPath path, final NodeModification modification,
194             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
195         final Optional<TreeNode> original = modification.getOriginal();
196         if (original.isPresent() && current.isPresent()) {
197             checkNotConflicting(path, original.get(), current.get());
198         } else {
199             checkConflicting(path, !original.isPresent(), "Node was deleted by other transaction.");
200             checkConflicting(path, !current.isPresent(), "Node was created by other transaction.");
201         }
202     }
203
204     private static void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
205         // Delete is always applicable, we do not expose it to subclasses
206         if (!current.isPresent()) {
207             LOG.trace("Delete operation turned to no-op on missing node {}", modification);
208         }
209     }
210
211     @Override
212     Optional<TreeNode> apply(final ModifiedNode modification, final Optional<TreeNode> currentMeta,
213             final Version version) {
214         switch (modification.getOperation()) {
215             case DELETE:
216                 // Deletion of a non-existing node is a no-op, report it as such
217                 modification.resolveModificationType(currentMeta.isPresent() ? ModificationType.DELETE
218                         : ModificationType.UNMODIFIED);
219                 return modification.setSnapshot(Optional.empty());
220             case TOUCH:
221                 checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s", modification);
222                 return modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.get(),
223                     version)));
224             case MERGE:
225                 final TreeNode result;
226
227                 if (!currentMeta.isPresent()) {
228                     // This is a slight optimization: a merge on a non-existing node equals to a write. Written data
229                     // structure is usually verified when the transaction is sealed. To preserve correctness, we have
230                     // to run that validation here.
231                     modification.resolveModificationType(ModificationType.WRITE);
232                     result = applyWrite(modification, modification.getWrittenValue(), currentMeta, version);
233                     fullVerifyStructure(result.getData());
234                 } else {
235                     result = applyMerge(modification, currentMeta.get(), version);
236                 }
237
238                 return modification.setSnapshot(Optional.of(result));
239             case WRITE:
240                 modification.resolveModificationType(ModificationType.WRITE);
241                 return modification.setSnapshot(Optional.of(applyWrite(modification,
242                     verifyNotNull(modification.getWrittenValue()), currentMeta, version)));
243             case NONE:
244                 modification.resolveModificationType(ModificationType.UNMODIFIED);
245                 return currentMeta;
246             default:
247                 throw new IllegalArgumentException("Provided modification type is not supported.");
248         }
249     }
250
251     /**
252      * Apply a merge operation. Since the result of merge differs based on the data type
253      * being modified, implementations of this method are responsible for calling
254      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
255      *
256      * @param modification Modified node
257      * @param currentMeta Store Metadata Node on which NodeModification should be applied
258      * @param version New subtree version of parent node
259      * @return A sealed TreeNode representing applied operation.
260      */
261     protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
262
263     protected abstract TreeNode applyWrite(ModifiedNode modification, NormalizedNode<?, ?> newValue,
264             Optional<TreeNode> currentMeta, Version version);
265
266     /**
267      * Apply a nested operation. Since there may not actually be a nested operation
268      * to be applied, implementations of this method are responsible for calling
269      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
270      *
271      * @param modification Modified node
272      * @param currentMeta Store Metadata Node on which NodeModification should be applied
273      * @param version New subtree version of parent node
274      * @return A sealed TreeNode representing applied operation.
275      */
276     protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
277
278     /**
279      * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
280      *
281      * @param path Path to current node
282      * @param modification Node modification which should be applied.
283      * @param current Current state of data tree
284      * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
285      * @throws org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException If subtree
286      *         modification is not applicable (e.g. leaf node).
287      */
288     protected abstract void checkTouchApplicable(ModificationPath path, NodeModification modification,
289             Optional<TreeNode> current, Version version) throws DataValidationFailedException;
290
291     /**
292      * Return the {@link WithStatus}-subclass schema associated with this operation.
293      * @return A model node
294      */
295     abstract @NonNull T getSchema();
296
297     /**
298      * Checks if supplied schema node belong to specified Data Tree type. All nodes belong to the operational tree,
299      * nodes in configuration tree are marked as such.
300      *
301      * @param treeType Tree Type
302      * @param node Schema node
303      * @return {@code true} if the node matches the tree type, {@code false} otherwise.
304      */
305     static boolean belongsToTree(final TreeType treeType, final DataSchemaNode node) {
306         return treeType == TreeType.OPERATIONAL || node.isConfiguration();
307     }
308 }