a77b78f82b9efee739f8dd9cccd5f0888b7489cd
[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.NormalizedNode;
18 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
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 implements ModificationApplyOperation {
37     private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
38
39     public static SchemaAwareApplyOperation from(final DataSchemaNode schemaNode) {
40         if (schemaNode instanceof ContainerSchemaNode) {
41             return new DataNodeContainerModificationStrategy.ContainerModificationStrategy((ContainerSchemaNode) schemaNode);
42         } else if (schemaNode instanceof ListSchemaNode) {
43             return fromListSchemaNode((ListSchemaNode) schemaNode);
44         } else if (schemaNode instanceof ChoiceSchemaNode) {
45             return new NormalizedNodeContainerModificationStrategy.ChoiceModificationStrategy((ChoiceSchemaNode) schemaNode);
46         } else if (schemaNode instanceof LeafListSchemaNode) {
47             return fromLeafListSchemaNode((LeafListSchemaNode) schemaNode);
48         } else if (schemaNode instanceof LeafSchemaNode) {
49             return new ValueNodeModificationStrategy.LeafModificationStrategy((LeafSchemaNode) schemaNode);
50         }
51         throw new IllegalArgumentException("Not supported schema node type for " + schemaNode.getClass());
52     }
53
54     public static SchemaAwareApplyOperation from(final DataNodeContainer resolvedTree,
55             final AugmentationTarget augSchemas, final AugmentationIdentifier identifier) {
56         for (AugmentationSchema potential : augSchemas.getAvailableAugmentations()) {
57             for (DataSchemaNode child : potential.getChildNodes()) {
58                 if (identifier.getPossibleChildNames().contains(child.getQName())) {
59                     return new DataNodeContainerModificationStrategy.AugmentationModificationStrategy(potential, resolvedTree);
60                 }
61             }
62         }
63
64         return null;
65     }
66
67     public static boolean checkConflicting(final YangInstanceIdentifier path, final boolean condition, final String message) throws ConflictingModificationAppliedException {
68         if(!condition) {
69             throw new ConflictingModificationAppliedException(path, message);
70         }
71         return condition;
72     }
73
74     private static SchemaAwareApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode) {
75         List<QName> keyDefinition = schemaNode.getKeyDefinition();
76         if (keyDefinition == null || keyDefinition.isEmpty()) {
77             return new UnkeyedListModificationStrategy(schemaNode);
78         }
79         if (schemaNode.isUserOrdered()) {
80             return new NormalizedNodeContainerModificationStrategy.OrderedMapModificationStrategy(schemaNode);
81         }
82
83         return new NormalizedNodeContainerModificationStrategy.UnorderedMapModificationStrategy(schemaNode);
84     }
85
86     private static SchemaAwareApplyOperation fromLeafListSchemaNode(final LeafListSchemaNode schemaNode) {
87         if(schemaNode.isUserOrdered()) {
88             return new NormalizedNodeContainerModificationStrategy.OrderedLeafSetModificationStrategy(schemaNode);
89         } else {
90             return new NormalizedNodeContainerModificationStrategy.UnorderedLeafSetModificationStrategy(schemaNode);
91         }
92     }
93
94     private static final void checkNotConflicting(final YangInstanceIdentifier path, final TreeNode original, final TreeNode current) throws ConflictingModificationAppliedException {
95         checkConflicting(path, original.getVersion().equals(current.getVersion()),
96                 "Node was replaced by other transaction.");
97         checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
98                 "Node children was modified by other transaction");
99     }
100
101     protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
102         Optional<ModificationApplyOperation> potential = getChild(child);
103         Preconditions.checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
104         return potential.get();
105     }
106
107     @Override
108     public void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
109         if (modification.getOperation() == LogicalOperation.WRITE) {
110             verifyWrittenStructure(modification.getWrittenValue());
111         }
112     }
113
114     @Override
115     public final void checkApplicable(final YangInstanceIdentifier path,final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
116         switch (modification.getOperation()) {
117         case DELETE:
118             checkDeleteApplicable(modification, current);
119             break;
120         case TOUCH:
121             checkSubtreeModificationApplicable(path, modification, current);
122             break;
123         case WRITE:
124             checkWriteApplicable(path, modification, current);
125             break;
126         case MERGE:
127             checkMergeApplicable(path, modification, current);
128             break;
129         case NONE:
130             break;
131         default:
132             throw new UnsupportedOperationException("Suplied modification type "+ modification.getOperation()+ " is not supported.");
133         }
134
135     }
136
137     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
138         Optional<TreeNode> original = modification.getOriginal();
139         if (original.isPresent() && current.isPresent()) {
140             /*
141              * We need to do conflict detection only and only if the value of leaf changed
142              * before two transactions. If value of leaf is unchanged between two transactions
143              * it should not cause transaction to fail, since result of this merge
144              * leads to same data.
145              */
146             if(!original.get().getData().equals(current.get().getData())) {
147                 checkNotConflicting(path, original.get(), current.get());
148             }
149         }
150     }
151
152     /**
153      * Checks if write operation can be applied to current TreeNode.
154      * The operation checks if original tree node to which the modification is going to be applied exists and if
155      * current node in TreeNode structure exists.
156      *
157      * @param path Path from current node in TreeNode
158      * @param modification modification to apply
159      * @param current current node in TreeNode for modification to apply
160      * @throws DataValidationFailedException
161      */
162     protected void checkWriteApplicable(final YangInstanceIdentifier path, final NodeModification modification,
163         final Optional<TreeNode> current) throws DataValidationFailedException {
164         Optional<TreeNode> original = modification.getOriginal();
165         if (original.isPresent() && current.isPresent()) {
166             checkNotConflicting(path, original.get(), current.get());
167         } else if(original.isPresent()) {
168             throw new ConflictingModificationAppliedException(path,"Node was deleted by other transaction.");
169         } else if(current.isPresent()) {
170             throw new ConflictingModificationAppliedException(path,"Node was created by other transaction.");
171         }
172     }
173
174     private void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
175         // Delete is always applicable, we do not expose it to subclasses
176         if (current.isPresent()) {
177             LOG.trace("Delete operation turned to no-op on missing node {}", modification);
178         }
179     }
180
181     boolean isOrdered() {
182         return false;
183     }
184
185     @Override
186     public final Optional<TreeNode> apply(final ModifiedNode modification,
187             final Optional<TreeNode> currentMeta, final Version version) {
188
189         switch (modification.getOperation()) {
190         case DELETE:
191             modification.resolveModificationType(ModificationType.DELETE);
192             return modification.setSnapshot(Optional.<TreeNode> absent());
193         case TOUCH:
194             Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification",
195                     modification);
196             return modification.setSnapshot(Optional.of(applySubtreeChange(modification, currentMeta.get(),
197                     version)));
198         case MERGE:
199             final TreeNode result;
200
201             // This is a slight optimization: a merge on a non-existing node equals to a write
202             if (currentMeta.isPresent()) {
203                 result = applyMerge(modification,currentMeta.get(), version);
204             } else {
205                 modification.resolveModificationType(ModificationType.WRITE);
206                 result = applyWrite(modification, currentMeta, version);
207             }
208
209             return modification.setSnapshot(Optional.of(result));
210         case WRITE:
211             modification.resolveModificationType(ModificationType.WRITE);
212             return modification.setSnapshot(Optional.of(applyWrite(modification, currentMeta, version)));
213         case NONE:
214             modification.resolveModificationType(ModificationType.UNMODIFIED);
215             return currentMeta;
216         default:
217             throw new IllegalArgumentException("Provided modification type is not supported.");
218         }
219     }
220
221     /**
222      * Apply a merge operation. Since the result of merge differs based on the data type
223      * being modified, implementations of this method are responsible for calling
224      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
225      *
226      * @param modification Modified node
227      * @param currentMeta Store Metadata Node on which NodeModification should be applied
228      * @param version New subtree version of parent node
229      * @return A sealed TreeNode representing applied operation.
230      */
231     protected abstract TreeNode applyMerge(ModifiedNode modification,
232             TreeNode currentMeta, Version version);
233
234     protected abstract TreeNode applyWrite(ModifiedNode modification,
235             Optional<TreeNode> currentMeta, Version version);
236
237     /**
238      * Apply a nested operation. Since there may not actually be a nested operation
239      * to be applied, 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 applySubtreeChange(ModifiedNode modification,
248             TreeNode currentMeta, Version version);
249
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 IncorrectDataStructureException If subtree modification is not applicable (e.g. leaf node).
259      */
260     protected abstract void checkSubtreeModificationApplicable(YangInstanceIdentifier path, final NodeModification modification,
261             final Optional<TreeNode> current) throws DataValidationFailedException;
262
263     protected abstract void verifyWrittenStructure(NormalizedNode<?, ?> writtenValue);
264 }