Split off UnkeyedListModificationStrategy
[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.ChoiceNode;
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 ChoiceNode) {
45             return new NormalizedNodeContainerModificationStrategy.ChoiceModificationStrategy((ChoiceNode) 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         AugmentationSchema augSchema = null;
57
58         allAugments:
59             for (AugmentationSchema potential : augSchemas.getAvailableAugmentations()) {
60                 for (DataSchemaNode child : potential.getChildNodes()) {
61                     if (identifier.getPossibleChildNames().contains(child.getQName())) {
62                         augSchema = potential;
63                         break allAugments;
64                     }
65                 }
66             }
67
68         if (augSchema != null) {
69             return new DataNodeContainerModificationStrategy.AugmentationModificationStrategy(augSchema, resolvedTree);
70         }
71         return null;
72     }
73
74     public static boolean checkConflicting(final YangInstanceIdentifier path, final boolean condition, final String message) throws ConflictingModificationAppliedException {
75         if(!condition) {
76             throw new ConflictingModificationAppliedException(path, message);
77         }
78         return condition;
79     }
80
81     private static SchemaAwareApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode) {
82         List<QName> keyDefinition = schemaNode.getKeyDefinition();
83         if (keyDefinition == null || keyDefinition.isEmpty()) {
84             return new UnkeyedListModificationStrategy(schemaNode);
85         }
86         if (schemaNode.isUserOrdered()) {
87             return new NormalizedNodeContainerModificationStrategy.OrderedMapModificationStrategy(schemaNode);
88         }
89
90         return new NormalizedNodeContainerModificationStrategy.UnorderedMapModificationStrategy(schemaNode);
91     }
92
93     private static SchemaAwareApplyOperation fromLeafListSchemaNode(final LeafListSchemaNode schemaNode) {
94         if(schemaNode.isUserOrdered()) {
95             return new NormalizedNodeContainerModificationStrategy.OrderedLeafSetModificationStrategy(schemaNode);
96         } else {
97             return new NormalizedNodeContainerModificationStrategy.UnorderedLeafSetModificationStrategy(schemaNode);
98         }
99     }
100
101     private static final void checkNotConflicting(final YangInstanceIdentifier path, final TreeNode original, 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         Optional<ModificationApplyOperation> potential = getChild(child);
110         Preconditions.checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
111         return potential.get();
112     }
113
114     @Override
115     public void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
116         if (modification.getType() == ModificationType.WRITE) {
117             verifyWrittenStructure(modification.getWrittenValue());
118         }
119     }
120
121     @Override
122     public final void checkApplicable(final YangInstanceIdentifier path,final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
123         switch (modification.getType()) {
124         case DELETE:
125             checkDeleteApplicable(modification, current);
126         case SUBTREE_MODIFIED:
127             checkSubtreeModificationApplicable(path, modification, current);
128             return;
129         case WRITE:
130             checkWriteApplicable(path, modification, current);
131             return;
132         case MERGE:
133             checkMergeApplicable(path, modification, current);
134             return;
135         case UNMODIFIED:
136             return;
137         default:
138             throw new UnsupportedOperationException("Suplied modification type "+ modification.getType()+ "is not supported.");
139         }
140
141     }
142
143     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
144         Optional<TreeNode> original = modification.getOriginal();
145         if (original.isPresent() && current.isPresent()) {
146             /*
147              * We need to do conflict detection only and only if the value of leaf changed
148              * before two transactions. If value of leaf is unchanged between two transactions
149              * it should not cause transaction to fail, since result of this merge
150              * leads to same data.
151              */
152             if(!original.get().getData().equals(current.get().getData())) {
153                 checkNotConflicting(path, original.get(), current.get());
154             }
155         }
156     }
157
158     /**
159      * Checks if write operation can be applied to current TreeNode.
160      * The operation checks if original tree node to which the modification is going to be applied exists and if
161      * current node in TreeNode structure exists.
162      *
163      * @param path Path from current node in TreeNode
164      * @param modification modification to apply
165      * @param current current node in TreeNode for modification to apply
166      * @throws DataValidationFailedException
167      */
168     protected void checkWriteApplicable(final YangInstanceIdentifier path, final NodeModification modification,
169         final Optional<TreeNode> current) throws DataValidationFailedException {
170         Optional<TreeNode> original = modification.getOriginal();
171         if (original.isPresent() && current.isPresent()) {
172             checkNotConflicting(path, original.get(), current.get());
173         } else if(original.isPresent()) {
174             throw new ConflictingModificationAppliedException(path,"Node was deleted by other transaction.");
175         } else if(current.isPresent()) {
176             throw new ConflictingModificationAppliedException(path,"Node was created by other transaction.");
177         }
178     }
179
180     private void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
181         // Delete is always applicable, we do not expose it to subclasses
182         if (current.isPresent()) {
183             LOG.trace("Delete operation turned to no-op on missing node {}", modification);
184         }
185     }
186
187     boolean isOrdered() {
188         return false;
189     }
190
191     @Override
192     public final Optional<TreeNode> apply(final ModifiedNode modification,
193             final Optional<TreeNode> currentMeta, final Version version) {
194
195         switch (modification.getType()) {
196         case DELETE:
197             return modification.setSnapshot(Optional.<TreeNode> absent());
198         case SUBTREE_MODIFIED:
199             Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification",
200                     modification);
201             return modification.setSnapshot(Optional.of(applySubtreeChange(modification, currentMeta.get(),
202                     version)));
203         case MERGE:
204             final TreeNode result;
205
206             // This is a slight optimization: a merge on a non-existing node equals to a write
207             if (currentMeta.isPresent()) {
208                 result = applyMerge(modification,currentMeta.get(), version);
209             } else {
210                 result = applyWrite(modification, currentMeta, version);
211             }
212
213             return modification.setSnapshot(Optional.of(result));
214         case WRITE:
215             return modification.setSnapshot(Optional.of(applyWrite(modification, currentMeta, version)));
216         case UNMODIFIED:
217             return currentMeta;
218         default:
219             throw new IllegalArgumentException("Provided modification type is not supported.");
220         }
221     }
222
223     protected abstract TreeNode applyMerge(ModifiedNode modification,
224             TreeNode currentMeta, Version version);
225
226     protected abstract TreeNode applyWrite(ModifiedNode modification,
227             Optional<TreeNode> currentMeta, Version version);
228
229     protected abstract TreeNode applySubtreeChange(ModifiedNode modification,
230             TreeNode currentMeta, Version version);
231
232     /**
233      *
234      * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
235      *
236      * @param path Path to current node
237      * @param modification Node modification which should be applied.
238      * @param current Current state of data tree
239      * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
240      * @throws IncorrectDataStructureException If subtree modification is not applicable (e.g. leaf node).
241      */
242     protected abstract void checkSubtreeModificationApplicable(YangInstanceIdentifier path, final NodeModification modification,
243             final Optional<TreeNode> current) throws DataValidationFailedException;
244
245     protected abstract void verifyWrittenStructure(NormalizedNode<?, ?> writtenValue);
246 }