Merge "Bug 762: Verify input in typedef codecs"
[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
13 import java.util.List;
14
15 import org.opendaylight.yangtools.yang.common.QName;
16 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.AugmentationIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
20 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
28 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
29 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
31 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 abstract class SchemaAwareApplyOperation implements ModificationApplyOperation {
41     private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
42
43     public static SchemaAwareApplyOperation from(final DataSchemaNode schemaNode) {
44         if (schemaNode instanceof ContainerSchemaNode) {
45             return new DataNodeContainerModificationStrategy.ContainerModificationStrategy((ContainerSchemaNode) schemaNode);
46         } else if (schemaNode instanceof ListSchemaNode) {
47             return fromListSchemaNode((ListSchemaNode) schemaNode);
48         } else if (schemaNode instanceof ChoiceNode) {
49             return new NormalizedNodeContainerModificationStrategy.ChoiceModificationStrategy((ChoiceNode) schemaNode);
50         } else if (schemaNode instanceof LeafListSchemaNode) {
51             return fromLeafListSchemaNode((LeafListSchemaNode) schemaNode);
52         } else if (schemaNode instanceof LeafSchemaNode) {
53             return new ValueNodeModificationStrategy.LeafModificationStrategy((LeafSchemaNode) schemaNode);
54         }
55         throw new IllegalArgumentException("Not supported schema node type for " + schemaNode.getClass());
56     }
57
58     public static SchemaAwareApplyOperation from(final DataNodeContainer resolvedTree,
59             final AugmentationTarget augSchemas, final AugmentationIdentifier identifier) {
60         AugmentationSchema augSchema = null;
61
62         allAugments:
63             for (AugmentationSchema potential : augSchemas.getAvailableAugmentations()) {
64                 for (DataSchemaNode child : potential.getChildNodes()) {
65                     if (identifier.getPossibleChildNames().contains(child.getQName())) {
66                         augSchema = potential;
67                         break allAugments;
68                     }
69                 }
70             }
71
72         if (augSchema != null) {
73             return new DataNodeContainerModificationStrategy.AugmentationModificationStrategy(augSchema, resolvedTree);
74         }
75         return null;
76     }
77
78     public static boolean checkConflicting(final InstanceIdentifier path, final boolean condition, final String message) throws ConflictingModificationAppliedException {
79         if(!condition) {
80             throw new ConflictingModificationAppliedException(path, message);
81         }
82         return condition;
83     }
84
85     private static SchemaAwareApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode) {
86         List<QName> keyDefinition = schemaNode.getKeyDefinition();
87         if (keyDefinition == null || keyDefinition.isEmpty()) {
88             return new UnkeyedListModificationStrategy(schemaNode);
89         }
90         if (schemaNode.isUserOrdered()) {
91             return new NormalizedNodeContainerModificationStrategy.OrderedMapModificationStrategy(schemaNode);
92         }
93
94         return new NormalizedNodeContainerModificationStrategy.UnorderedMapModificationStrategy(schemaNode);
95     }
96
97     private static SchemaAwareApplyOperation fromLeafListSchemaNode(final LeafListSchemaNode schemaNode) {
98         if(schemaNode.isUserOrdered()) {
99             return new NormalizedNodeContainerModificationStrategy.OrderedLeafSetModificationStrategy(schemaNode);
100         } else {
101             return new NormalizedNodeContainerModificationStrategy.UnorderedLeafSetModificationStrategy(schemaNode);
102         }
103     }
104
105     private static final void checkNotConflicting(final InstanceIdentifier path, final TreeNode original, final TreeNode current) throws ConflictingModificationAppliedException {
106         checkConflicting(path, original.getVersion().equals(current.getVersion()),
107                 "Node was replaced by other transaction.");
108         checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
109                 "Node children was modified by other transaction");
110     }
111
112     protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
113         Optional<ModificationApplyOperation> potential = getChild(child);
114         Preconditions.checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
115         return potential.get();
116     }
117
118     @Override
119     public void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
120         if (modification.getType() == ModificationType.WRITE) {
121             verifyWrittenStructure(modification.getWrittenValue());
122         }
123     }
124
125     @Override
126     public final void checkApplicable(final InstanceIdentifier path,final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
127         switch (modification.getType()) {
128         case DELETE:
129             checkDeleteApplicable(modification, current);
130         case SUBTREE_MODIFIED:
131             checkSubtreeModificationApplicable(path, modification, current);
132             return;
133         case WRITE:
134             checkWriteApplicable(path, modification, current);
135             return;
136         case MERGE:
137             checkMergeApplicable(path, modification, current);
138             return;
139         case UNMODIFIED:
140             return;
141         default:
142             throw new UnsupportedOperationException("Suplied modification type "+ modification.getType()+ "is not supported.");
143         }
144
145     }
146
147     protected void checkMergeApplicable(final InstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
148         Optional<TreeNode> original = modification.getOriginal();
149         if (original.isPresent() && current.isPresent()) {
150             /*
151              * We need to do conflict detection only and only if the value of leaf changed
152              * before two transactions. If value of leaf is unchanged between two transactions
153              * it should not cause transaction to fail, since result of this merge
154              * leads to same data.
155              */
156             if(!original.get().getData().equals(current.get().getData())) {
157                 checkNotConflicting(path, original.get(), current.get());
158             }
159         }
160     }
161
162     protected void checkWriteApplicable(final InstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
163         Optional<TreeNode> original = modification.getOriginal();
164         if (original.isPresent() && current.isPresent()) {
165             checkNotConflicting(path, original.get(), current.get());
166         } else if(original.isPresent()) {
167             throw new ConflictingModificationAppliedException(path,"Node was deleted by other transaction.");
168         }
169     }
170
171     private void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
172         // Delete is always applicable, we do not expose it to subclasses
173         if (current.isPresent()) {
174             LOG.trace("Delete operation turned to no-op on missing node {}", modification);
175         }
176     }
177
178     @Override
179     public final Optional<TreeNode> apply(final ModifiedNode modification,
180             final Optional<TreeNode> currentMeta, final Version version) {
181
182         switch (modification.getType()) {
183         case DELETE:
184             return modification.storeSnapshot(Optional.<TreeNode> absent());
185         case SUBTREE_MODIFIED:
186             Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification",
187                     modification);
188             return modification.storeSnapshot(Optional.of(applySubtreeChange(modification, currentMeta.get(),
189                     version)));
190         case MERGE:
191             if(currentMeta.isPresent()) {
192                 return modification.storeSnapshot(Optional.of(applyMerge(modification,currentMeta.get(), version)));
193             }
194             // intentional fall-through: if the node does not exist a merge is same as a write
195         case WRITE:
196             return modification.storeSnapshot(Optional.of(applyWrite(modification, currentMeta, version)));
197         case UNMODIFIED:
198             return currentMeta;
199         default:
200             throw new IllegalArgumentException("Provided modification type is not supported.");
201         }
202     }
203
204     protected abstract TreeNode applyMerge(ModifiedNode modification,
205             TreeNode currentMeta, Version version);
206
207     protected abstract TreeNode applyWrite(ModifiedNode modification,
208             Optional<TreeNode> currentMeta, Version version);
209
210     protected abstract TreeNode applySubtreeChange(ModifiedNode modification,
211             TreeNode currentMeta, Version version);
212
213     /**
214      *
215      * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
216      *
217      * @param path Path to current node
218      * @param modification Node modification which should be applied.
219      * @param current Current state of data tree
220      * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
221      * @throws IncorrectDataStructureException If subtree modification is not applicable (e.g. leaf node).
222      */
223     protected abstract void checkSubtreeModificationApplicable(InstanceIdentifier path, final NodeModification modification,
224             final Optional<TreeNode> current) throws DataValidationFailedException;
225
226     protected abstract void verifyWrittenStructure(NormalizedNode<?, ?> writtenValue);
227
228     public static class UnkeyedListModificationStrategy extends SchemaAwareApplyOperation {
229
230         private final Optional<ModificationApplyOperation> entryStrategy;
231
232         protected UnkeyedListModificationStrategy(final ListSchemaNode schema) {
233             entryStrategy = Optional.<ModificationApplyOperation> of(new DataNodeContainerModificationStrategy.UnkeyedListItemModificationStrategy(schema));
234         }
235
236         @Override
237         protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta,
238                 final Version version) {
239             return applyWrite(modification, Optional.of(currentMeta), version);
240         }
241
242         @Override
243         protected TreeNode applySubtreeChange(final ModifiedNode modification,
244                 final TreeNode currentMeta, final Version version) {
245             throw new UnsupportedOperationException("UnkeyedList does not support subtree change.");
246         }
247
248         @Override
249         protected TreeNode applyWrite(final ModifiedNode modification,
250                 final Optional<TreeNode> currentMeta, final Version version) {
251             /*
252              * FIXME: BUG-1258: This is inefficient: it needlessly creates index nodes for the entire subtree.
253              *        We can determine the depth into which metadata need to be created from the modification
254              *        -- if it does not have children, no need to bother with metadata.
255              */
256             return TreeNodeFactory.createTreeNode(modification.getWrittenValue(), version);
257         }
258
259         @Override
260         public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
261             if (child instanceof NodeIdentifier) {
262                 return entryStrategy;
263             }
264             return Optional.absent();
265         }
266
267         @Override
268         protected void verifyWrittenStructure(final NormalizedNode<?, ?> writtenValue) {
269
270         }
271
272         @Override
273         protected void checkSubtreeModificationApplicable(final InstanceIdentifier path, final NodeModification modification,
274                 final Optional<TreeNode> current) throws IncorrectDataStructureException {
275             throw new IncorrectDataStructureException(path, "Subtree modification is not allowed.");
276         }
277     }
278 }