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