Merge "Bug 3051: Fixed pattern checks in generated DTOs"
[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 extends 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 ContainerModificationStrategy((ContainerSchemaNode) schemaNode);
42         } else if (schemaNode instanceof ListSchemaNode) {
43             return fromListSchemaNode((ListSchemaNode) schemaNode);
44         } else if (schemaNode instanceof ChoiceSchemaNode) {
45             return new ChoiceModificationStrategy((ChoiceSchemaNode) schemaNode);
46         } else if (schemaNode instanceof LeafListSchemaNode) {
47             return fromLeafListSchemaNode((LeafListSchemaNode) schemaNode);
48         } else if (schemaNode instanceof LeafSchemaNode) {
49             return new 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 (final AugmentationSchema potential : augSchemas.getAvailableAugmentations()) {
57             for (final DataSchemaNode child : potential.getChildNodes()) {
58                 if (identifier.getPossibleChildNames().contains(child.getQName())) {
59                     return new 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         final List<QName> keyDefinition = schemaNode.getKeyDefinition();
76         final SchemaAwareApplyOperation op;
77         if (keyDefinition == null || keyDefinition.isEmpty()) {
78             op = new UnkeyedListModificationStrategy(schemaNode);
79         } else if (schemaNode.isUserOrdered()) {
80             op =  new OrderedMapModificationStrategy(schemaNode);
81         } else {
82             op = new UnorderedMapModificationStrategy(schemaNode);
83         }
84         return MinMaxElementsValidation.from(op, schemaNode);
85     }
86
87     private static SchemaAwareApplyOperation fromLeafListSchemaNode(final LeafListSchemaNode schemaNode) {
88         final SchemaAwareApplyOperation op;
89         if(schemaNode.isUserOrdered()) {
90             op =  new OrderedLeafSetModificationStrategy(schemaNode);
91         } else {
92             op = new UnorderedLeafSetModificationStrategy(schemaNode);
93         }
94         return MinMaxElementsValidation.from(op, schemaNode);
95     }
96
97     protected static final void checkNotConflicting(final YangInstanceIdentifier path, final TreeNode original, final TreeNode current) throws ConflictingModificationAppliedException {
98         checkConflicting(path, original.getVersion().equals(current.getVersion()),
99                 "Node was replaced by other transaction.");
100         checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
101                 "Node children was modified by other transaction");
102     }
103
104     protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
105         final Optional<ModificationApplyOperation> potential = getChild(child);
106         Preconditions.checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
107         return potential.get();
108     }
109
110     @Override
111     void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
112         if (modification.getOperation() == LogicalOperation.WRITE) {
113             verifyWrittenStructure(modification.getWrittenValue());
114         }
115     }
116
117     @Override
118     final void checkApplicable(final YangInstanceIdentifier path,final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
119         switch (modification.getOperation()) {
120         case DELETE:
121             checkDeleteApplicable(modification, current);
122             break;
123         case TOUCH:
124             checkTouchApplicable(path, modification, current);
125             break;
126         case WRITE:
127             checkWriteApplicable(path, modification, current);
128             break;
129         case MERGE:
130             checkMergeApplicable(path, modification, current);
131             break;
132         case NONE:
133             break;
134         default:
135             throw new UnsupportedOperationException("Suplied modification type "+ modification.getOperation()+ " is not supported.");
136         }
137     }
138
139     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) 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             if(!original.get().getData().equals(current.get().getData())) {
149                 checkNotConflicting(path, original.get(), current.get());
150             }
151         }
152     }
153
154     /**
155      * Checks if write operation can be applied to current TreeNode.
156      * The operation checks if original tree node to which the modification is going to be applied exists and if
157      * current node in TreeNode structure exists.
158      *
159      * @param path Path from current node in TreeNode
160      * @param modification modification to apply
161      * @param current current node in TreeNode for modification to apply
162      * @throws DataValidationFailedException
163      */
164     protected void checkWriteApplicable(final YangInstanceIdentifier path, final NodeModification modification,
165         final Optional<TreeNode> current) throws DataValidationFailedException {
166         final Optional<TreeNode> original = modification.getOriginal();
167         if (original.isPresent() && current.isPresent()) {
168             checkNotConflicting(path, original.get(), current.get());
169         } else if(original.isPresent()) {
170             throw new ConflictingModificationAppliedException(path,"Node was deleted by other transaction.");
171         } else if(current.isPresent()) {
172             throw new ConflictingModificationAppliedException(path,"Node was created by other transaction.");
173         }
174     }
175
176     private static void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
177         // Delete is always applicable, we do not expose it to subclasses
178         if (current.isPresent()) {
179             LOG.trace("Delete operation turned to no-op on missing node {}", modification);
180         }
181     }
182
183     @Override
184     protected ChildTrackingPolicy getChildPolicy() {
185         return ChildTrackingPolicy.UNORDERED;
186     }
187
188     @Override
189     final Optional<TreeNode> apply(final ModifiedNode modification, final Optional<TreeNode> currentMeta, final Version version) {
190         switch (modification.getOperation()) {
191         case DELETE:
192             modification.resolveModificationType(ModificationType.DELETE);
193             return modification.setSnapshot(Optional.<TreeNode> absent());
194         case TOUCH:
195             Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s",
196                     modification);
197             return modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.get(),
198                     version)));
199         case MERGE:
200             final TreeNode result;
201
202             // This is a slight optimization: a merge on a non-existing node equals to a write
203             if (currentMeta.isPresent()) {
204                 result = applyMerge(modification,currentMeta.get(), version);
205             } else {
206                 modification.resolveModificationType(ModificationType.WRITE);
207                 result = applyWrite(modification, currentMeta, version);
208             }
209
210             return modification.setSnapshot(Optional.of(result));
211         case WRITE:
212             modification.resolveModificationType(ModificationType.WRITE);
213             return modification.setSnapshot(Optional.of(applyWrite(modification, currentMeta, version)));
214         case NONE:
215             modification.resolveModificationType(ModificationType.UNMODIFIED);
216             return currentMeta;
217         default:
218             throw new IllegalArgumentException("Provided modification type is not supported.");
219         }
220     }
221
222     /**
223      * Apply a merge operation. Since the result of merge differs based on the data type
224      * being modified, implementations of this method are responsible for calling
225      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
226      *
227      * @param modification Modified node
228      * @param currentMeta Store Metadata Node on which NodeModification should be applied
229      * @param version New subtree version of parent node
230      * @return A sealed TreeNode representing applied operation.
231      */
232     protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
233
234     protected abstract TreeNode applyWrite(ModifiedNode modification, Optional<TreeNode> currentMeta, Version version);
235
236     /**
237      * Apply a nested operation. Since there may not actually be a nested operation
238      * to be applied, implementations of this method are responsible for calling
239      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
240      *
241      * @param modification Modified node
242      * @param currentMeta Store Metadata Node on which NodeModification should be applied
243      * @param version New subtree version of parent node
244      * @return A sealed TreeNode representing applied operation.
245      */
246     protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
247
248     /**
249      *
250      * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
251      *
252      * @param path Path to current node
253      * @param modification Node modification which should be applied.
254      * @param current Current state of data tree
255      * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
256      * @throws IncorrectDataStructureException If subtree modification is not applicable (e.g. leaf node).
257      */
258     protected abstract void checkTouchApplicable(YangInstanceIdentifier path, final NodeModification modification,
259             final Optional<TreeNode> current) throws DataValidationFailedException;
260
261     protected abstract void verifyWrittenStructure(NormalizedNode<?, ?> writtenValue);
262 }