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