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