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 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.AugmentationNode;
17 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
18 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
25 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableAugmentationNodeBuilder;
26 import org.opendaylight.yangtools.yang.data.impl.schema.tree.NormalizedNodeContainerSupport.Single;
27 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
29 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
32 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
36 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 abstract class SchemaAwareApplyOperation extends ModificationApplyOperation {
41     private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
42     private static final Single<AugmentationIdentifier, AugmentationNode> AUGMENTATION_SUPPORT =
43             new Single<>(AugmentationNode.class, ImmutableAugmentationNodeBuilder::create,
44                     ImmutableAugmentationNodeBuilder::create);
45
46     public static ModificationApplyOperation from(final DataSchemaNode schemaNode,
47             final DataTreeConfiguration treeConfig) {
48         if (treeConfig.getTreeType() == TreeType.CONFIGURATION) {
49             Preconditions.checkArgument(schemaNode.isConfiguration(),
50                 "Supplied %s does not belongs to configuration tree.", schemaNode.getPath());
51         }
52         if (schemaNode instanceof ContainerSchemaNode) {
53             return ContainerModificationStrategy.of((ContainerSchemaNode) schemaNode, treeConfig);
54         } else if (schemaNode instanceof ListSchemaNode) {
55             return fromListSchemaNode((ListSchemaNode) schemaNode, treeConfig);
56         } else if (schemaNode instanceof ChoiceSchemaNode) {
57             return new ChoiceModificationStrategy((ChoiceSchemaNode) schemaNode, treeConfig);
58         } else if (schemaNode instanceof LeafListSchemaNode) {
59             return fromLeafListSchemaNode((LeafListSchemaNode) schemaNode, treeConfig);
60         } else if (schemaNode instanceof LeafSchemaNode) {
61             return new LeafModificationStrategy((LeafSchemaNode) schemaNode);
62         }
63         throw new IllegalArgumentException("Not supported schema node type for " + schemaNode.getClass());
64     }
65
66     public static SchemaAwareApplyOperation from(final DataNodeContainer resolvedTree,
67             final AugmentationTarget augSchemas, final AugmentationIdentifier identifier,
68             final DataTreeConfiguration treeConfig) {
69         for (final AugmentationSchemaNode potential : augSchemas.getAvailableAugmentations()) {
70             for (final DataSchemaNode child : potential.getChildNodes()) {
71                 if (identifier.getPossibleChildNames().contains(child.getQName())) {
72                     return from(potential, resolvedTree, treeConfig);
73                 }
74             }
75         }
76
77         return null;
78     }
79
80     static DataNodeContainerModificationStrategy<AugmentationSchemaNode> from(final AugmentationSchemaNode schema,
81             final DataNodeContainer resolved, final DataTreeConfiguration treeConfig) {
82         return new DataNodeContainerModificationStrategy<>(AUGMENTATION_SUPPORT,
83                 EffectiveAugmentationSchema.create(schema, resolved), treeConfig);
84     }
85
86     static void checkConflicting(final ModificationPath path, final boolean condition, final String message)
87             throws ConflictingModificationAppliedException {
88         if (!condition) {
89             throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(), message);
90         }
91     }
92
93     private static ModificationApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode,
94             final DataTreeConfiguration treeConfig) {
95         final List<QName> keyDefinition = schemaNode.getKeyDefinition();
96         final SchemaAwareApplyOperation op;
97         if (keyDefinition == null || keyDefinition.isEmpty()) {
98             op = new UnkeyedListModificationStrategy(schemaNode, treeConfig);
99         } else {
100             op = MapModificationStrategy.of(schemaNode, treeConfig);
101         }
102         return MinMaxElementsValidation.from(op, schemaNode);
103     }
104
105     private static ModificationApplyOperation fromLeafListSchemaNode(final LeafListSchemaNode schemaNode,
106             final DataTreeConfiguration treeConfig) {
107         return MinMaxElementsValidation.from(new LeafSetModificationStrategy(schemaNode, treeConfig), schemaNode);
108     }
109
110     protected static void checkNotConflicting(final ModificationPath 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 ModificationPath 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 ModificationPath 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     private static void checkWriteApplicable(final ModificationPath 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 {
182             checkConflicting(path, !original.isPresent(), "Node was deleted by other transaction.");
183             checkConflicting(path, !current.isPresent(), "Node was created by other transaction.");
184         }
185     }
186
187     private static void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
188         // Delete is always applicable, we do not expose it to subclasses
189         if (!current.isPresent()) {
190             LOG.trace("Delete operation turned to no-op on missing node {}", modification);
191         }
192     }
193
194     @Override
195     final Optional<TreeNode> apply(final ModifiedNode modification, final Optional<TreeNode> currentMeta,
196             final Version version) {
197         switch (modification.getOperation()) {
198             case DELETE:
199                 // Deletion of a non-existing node is a no-op, report it as such
200                 modification.resolveModificationType(currentMeta.isPresent() ? ModificationType.DELETE
201                         : ModificationType.UNMODIFIED);
202                 return modification.setSnapshot(Optional.empty());
203             case TOUCH:
204                 Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s",
205                     modification);
206                 return modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.get(),
207                     version)));
208             case MERGE:
209                 final TreeNode result;
210
211                 if (!currentMeta.isPresent()) {
212                     // This is a slight optimization: a merge on a non-existing node equals to a write. Written data
213                     // structure is usually verified when the transaction is sealed. To preserve correctness, we have
214                     // to run that validation here.
215                     modification.resolveModificationType(ModificationType.WRITE);
216                     result = applyWrite(modification, modification.getWrittenValue(), currentMeta, version);
217                     verifyStructure(result.getData(), true);
218                 } else {
219                     result = applyMerge(modification, currentMeta.get(), version);
220                 }
221
222                 return modification.setSnapshot(Optional.of(result));
223             case WRITE:
224                 modification.resolveModificationType(ModificationType.WRITE);
225                 return modification.setSnapshot(Optional.of(applyWrite(modification, modification.getWrittenValue(),
226                     currentMeta, version)));
227             case NONE:
228                 modification.resolveModificationType(ModificationType.UNMODIFIED);
229                 return currentMeta;
230             default:
231                 throw new IllegalArgumentException("Provided modification type is not supported.");
232         }
233     }
234
235     /**
236      * Apply a merge operation. Since the result of merge differs based on the data type
237      * being modified, implementations of this method are responsible for calling
238      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
239      *
240      * @param modification Modified node
241      * @param currentMeta Store Metadata Node on which NodeModification should be applied
242      * @param version New subtree version of parent node
243      * @return A sealed TreeNode representing applied operation.
244      */
245     protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
246
247     protected abstract TreeNode applyWrite(ModifiedNode modification, NormalizedNode<?, ?> newValue,
248             Optional<TreeNode> currentMeta, Version version);
249
250     /**
251      * Apply a nested operation. Since there may not actually be a nested operation
252      * to be applied, implementations of this method are responsible for calling
253      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
254      *
255      * @param modification Modified node
256      * @param currentMeta Store Metadata Node on which NodeModification should be applied
257      * @param version New subtree version of parent node
258      * @return A sealed TreeNode representing applied operation.
259      */
260     protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
261
262     /**
263      * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
264      *
265      * @param path Path to current node
266      * @param modification Node modification which should be applied.
267      * @param current Current state of data tree
268      * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
269      * @throws org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException If subtree
270      *         modification is not applicable (e.g. leaf node).
271      */
272     protected abstract void checkTouchApplicable(ModificationPath path, NodeModification modification,
273             Optional<TreeNode> current, Version version) throws DataValidationFailedException;
274
275     /**
276      * Checks if supplied schema node belong to specified Data Tree type. All nodes belong to the operational tree,
277      * nodes in configuration tree are marked as such.
278      *
279      * @param treeType Tree Type
280      * @param node Schema node
281      * @return {@code true} if the node matches the tree type, {@code false} otherwise.
282      */
283     static boolean belongsToTree(final TreeType treeType, final DataSchemaNode node) {
284         return treeType == TreeType.OPERATIONAL || node.isConfiguration();
285     }
286 }