Cleanup checkstyle warnings and turn enforcement on in yang-data-impl
[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.Optional;
11 import com.google.common.base.Preconditions;
12 import java.util.List;
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.AugmentationSchema;
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             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 AugmentationSchema 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     public static void checkConflicting(final YangInstanceIdentifier path, final boolean condition,
78                                         final String message) throws ConflictingModificationAppliedException {
79         if (!condition) {
80             throw new ConflictingModificationAppliedException(path, 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 YangInstanceIdentifier 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 YangInstanceIdentifier 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 YangInstanceIdentifier 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             if (!original.get().getData().equals(current.get().getData())) {
158                 checkNotConflicting(path, original.get(), current.get());
159             }
160         }
161     }
162
163     /**
164      * Checks if write operation can be applied to current TreeNode.
165      * The operation checks if original tree node to which the modification is going to be applied exists and if
166      * current node in TreeNode structure exists.
167      *
168      * @param path Path from current node in TreeNode
169      * @param modification modification to apply
170      * @param current current node in TreeNode for modification to apply
171      * @throws DataValidationFailedException when a data dependency conflict is detected
172      */
173     protected void checkWriteApplicable(final YangInstanceIdentifier path, final NodeModification modification,
174         final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
175         final Optional<TreeNode> original = modification.getOriginal();
176         if (original.isPresent() && current.isPresent()) {
177             checkNotConflicting(path, original.get(), current.get());
178         } else if (original.isPresent()) {
179             throw new ConflictingModificationAppliedException(path, "Node was deleted by other transaction.");
180         } else if (current.isPresent()) {
181             throw new ConflictingModificationAppliedException(path, "Node was created by other transaction.");
182         }
183     }
184
185     private static void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
186         // Delete is always applicable, we do not expose it to subclasses
187         if (!current.isPresent()) {
188             LOG.trace("Delete operation turned to no-op on missing node {}", modification);
189         }
190     }
191
192     @Override
193     protected ChildTrackingPolicy getChildPolicy() {
194         return ChildTrackingPolicy.UNORDERED;
195     }
196
197     @Override
198     final Optional<TreeNode> apply(final ModifiedNode modification, final Optional<TreeNode> currentMeta,
199             final Version version) {
200         switch (modification.getOperation()) {
201             case DELETE:
202                 // Deletion of a non-existing node is a no-op, report it as such
203                 modification.resolveModificationType(currentMeta.isPresent() ? ModificationType.DELETE
204                         : ModificationType.UNMODIFIED);
205                 return modification.setSnapshot(Optional.absent());
206             case TOUCH:
207                 Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s",
208                     modification);
209                 return modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.get(),
210                     version)));
211             case MERGE:
212                 final TreeNode result;
213
214                 if (!currentMeta.isPresent()) {
215                     // This is a slight optimization: a merge on a non-existing node equals to a write. Written data
216                     // structure is usually verified when the transaction is sealed. To preserve correctness, we have
217                     // to run that validation here.
218                     modification.resolveModificationType(ModificationType.WRITE);
219                     result = applyWrite(modification, currentMeta, version);
220                     verifyStructure(result.getData(), true);
221                 } else {
222                     result = applyMerge(modification, currentMeta.get(), version);
223                 }
224
225                 return modification.setSnapshot(Optional.of(result));
226             case WRITE:
227                 modification.resolveModificationType(ModificationType.WRITE);
228                 return modification.setSnapshot(Optional.of(applyWrite(modification, currentMeta, version)));
229             case NONE:
230                 modification.resolveModificationType(ModificationType.UNMODIFIED);
231                 return currentMeta;
232             default:
233                 throw new IllegalArgumentException("Provided modification type is not supported.");
234         }
235     }
236
237     /**
238      * Apply a merge operation. Since the result of merge differs based on the data type
239      * being modified, implementations of this method are responsible for calling
240      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
241      *
242      * @param modification Modified node
243      * @param currentMeta Store Metadata Node on which NodeModification should be applied
244      * @param version New subtree version of parent node
245      * @return A sealed TreeNode representing applied operation.
246      */
247     protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
248
249     protected abstract TreeNode applyWrite(ModifiedNode modification, Optional<TreeNode> currentMeta, Version version);
250
251     /**
252      * Apply a nested operation. Since there may not actually be a nested operation
253      * to be applied, implementations of this method are responsible for calling
254      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
255      *
256      * @param modification Modified node
257      * @param currentMeta Store Metadata Node on which NodeModification should be applied
258      * @param version New subtree version of parent node
259      * @return A sealed TreeNode representing applied operation.
260      */
261     protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
262
263     /**
264      * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
265      *
266      * @param path Path to current node
267      * @param modification Node modification which should be applied.
268      * @param current Current state of data tree
269      * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
270      * @throws org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException If subtree
271      *         modification is not applicable (e.g. leaf node).
272      */
273     protected abstract void checkTouchApplicable(YangInstanceIdentifier path, NodeModification modification,
274             Optional<TreeNode> current, Version version) throws DataValidationFailedException;
275
276     /**
277      * Checks if supplied schema node belong to specified Data Tree type. All nodes belong to the operational tree,
278      * nodes in configuration tree are marked as such.
279      *
280      * @param treeType Tree Type
281      * @param node Schema node
282      * @return {@code true} if the node matches the tree type, {@code false} otherwise.
283      */
284     static boolean belongsToTree(final TreeType treeType, final DataSchemaNode node) {
285         return treeType == TreeType.OPERATIONAL || node.isConfiguration();
286     }
287 }