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