Merge "BUG-869: added proper handling of nullable parameter"
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / NormalizedNodeContainerModificationStrategy.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.collect.ImmutableMap;
12 import com.google.common.collect.Iterables;
13 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
14 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
15 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
16 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
17 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
18 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
19 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
27 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
28 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
29 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableChoiceNodeBuilder;
30 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder;
31 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
32 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableOrderedLeafSetNodeBuilder;
33 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableOrderedMapNodeBuilder;
34 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
35 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
39
40 import java.util.Map;
41
42 import static com.google.common.base.Preconditions.checkArgument;
43
44 abstract class NormalizedNodeContainerModificationStrategy extends SchemaAwareApplyOperation {
45
46     private final Class<? extends NormalizedNode<?, ?>> nodeClass;
47
48     protected NormalizedNodeContainerModificationStrategy(final Class<? extends NormalizedNode<?, ?>> nodeClass) {
49         this.nodeClass = nodeClass;
50     }
51
52     @Override
53     public void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
54         if (modification.getType() == ModificationType.WRITE) {
55
56         }
57         for (ModifiedNode childModification : modification.getChildren()) {
58             resolveChildOperation(childModification.getIdentifier()).verifyStructure(childModification);
59         }
60     }
61
62     @SuppressWarnings("rawtypes")
63     @Override
64     protected void verifyWrittenStructure(final NormalizedNode<?, ?> writtenValue) {
65         checkArgument(nodeClass.isInstance(writtenValue), "Node should must be of type %s", nodeClass);
66         checkArgument(writtenValue instanceof NormalizedNodeContainer);
67
68         NormalizedNodeContainer container = (NormalizedNodeContainer) writtenValue;
69         for (Object child : container.getValue()) {
70             checkArgument(child instanceof NormalizedNode);
71
72             /*
73              * FIXME: fail-fast semantics:
74              *
75              * We can validate the data structure here, aborting the commit
76              * before it ever progresses to being committed.
77              */
78         }
79     }
80
81     @Override
82     protected TreeNode applyWrite(final ModifiedNode modification,
83             final Optional<TreeNode> currentMeta, final Version version) {
84         final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
85         final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
86
87         if (Iterables.isEmpty(modification.getChildren())) {
88             return newValueMeta;
89         }
90
91         /*
92          * This is where things get interesting. The user has performed a write and
93          * then she applied some more modifications to it. So we need to make sense
94          * of that an apply the operations on top of the written value. We could have
95          * done it during the write, but this operation is potentially expensive, so
96          * we have left it out of the fast path.
97          *
98          * As it turns out, once we materialize the written data, we can share the
99          * code path with the subtree change. So let's create an unsealed TreeNode
100          * and run the common parts on it -- which end with the node being sealed.
101          */
102         final MutableTreeNode mutable = newValueMeta.mutable();
103         mutable.setSubtreeVersion(version);
104
105         @SuppressWarnings("rawtypes")
106         final NormalizedNodeContainerBuilder dataBuilder = createBuilder(newValue);
107
108         return mutateChildren(mutable, dataBuilder, version, modification.getChildren());
109     }
110
111     /**
112      * Applies write/remove diff operation for each modification child in modification subtree.
113      * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
114      *
115      * @param meta MutableTreeNode (IndexTreeNode)
116      * @param data DataBuilder
117      * @param nodeVersion Version of TreeNode
118      * @param modifications modification operations to apply
119      * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
120      */
121     @SuppressWarnings({ "rawtypes", "unchecked" })
122     private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
123             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
124
125         for (ModifiedNode mod : modifications) {
126             final YangInstanceIdentifier.PathArgument id = mod.getIdentifier();
127             final Optional<TreeNode> cm = meta.getChild(id);
128
129             Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
130             if (result.isPresent()) {
131                 final TreeNode tn = result.get();
132                 meta.addChild(tn);
133                 data.addChild(tn.getData());
134             } else {
135                 meta.removeChild(id);
136                 data.removeChild(id);
137             }
138         }
139
140         meta.setData(data.build());
141         return meta.seal();
142     }
143
144     @Override
145     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta,
146             final Version version) {
147         // For Node Containers - merge is same as subtree change - we only replace children.
148         return applySubtreeChange(modification, currentMeta, version);
149     }
150
151     @Override
152     public TreeNode applySubtreeChange(final ModifiedNode modification,
153             final TreeNode currentMeta, final Version version) {
154         final MutableTreeNode newMeta = currentMeta.mutable();
155         newMeta.setSubtreeVersion(version);
156
157         @SuppressWarnings("rawtypes")
158         NormalizedNodeContainerBuilder dataBuilder = createBuilder(currentMeta.getData());
159
160         return mutateChildren(newMeta, dataBuilder, version, modification.getChildren());
161     }
162
163     @Override
164     protected void checkSubtreeModificationApplicable(final YangInstanceIdentifier path, final NodeModification modification,
165             final Optional<TreeNode> current) throws DataValidationFailedException {
166         if (!modification.getOriginal().isPresent() && !current.isPresent()) {
167             throw new ModifiedNodeDoesNotExistException(path, String.format("Node %s does not exist. Cannot apply modification to its children.", path));
168         }
169
170         SchemaAwareApplyOperation.checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
171         checkChildPreconditions(path, modification, current);
172     }
173
174     private void checkChildPreconditions(final YangInstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
175         final TreeNode currentMeta = current.get();
176         for (NodeModification childMod : modification.getChildren()) {
177             final YangInstanceIdentifier.PathArgument childId = childMod.getIdentifier();
178             final Optional<TreeNode> childMeta = currentMeta.getChild(childId);
179
180             YangInstanceIdentifier childPath = path.node(childId);
181             resolveChildOperation(childId).checkApplicable(childPath, childMod, childMeta);
182         }
183     }
184
185     @Override
186     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification,
187             final Optional<TreeNode> current) throws DataValidationFailedException {
188         if(current.isPresent()) {
189             checkChildPreconditions(path, modification,current);
190         }
191     }
192
193     @SuppressWarnings("rawtypes")
194     protected abstract NormalizedNodeContainerBuilder createBuilder(NormalizedNode<?, ?> original);
195
196     public static class ChoiceModificationStrategy extends NormalizedNodeContainerModificationStrategy {
197
198         private final Map<YangInstanceIdentifier.PathArgument, ModificationApplyOperation> childNodes;
199
200         public ChoiceModificationStrategy(final ChoiceNode schemaNode) {
201             super(org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode.class);
202             ImmutableMap.Builder<YangInstanceIdentifier.PathArgument, ModificationApplyOperation> child = ImmutableMap.builder();
203
204             for (ChoiceCaseNode caze : schemaNode.getCases()) {
205                 for (DataSchemaNode cazeChild : caze.getChildNodes()) {
206                     SchemaAwareApplyOperation childNode = SchemaAwareApplyOperation.from(cazeChild);
207                     child.put(new YangInstanceIdentifier.NodeIdentifier(cazeChild.getQName()), childNode);
208                 }
209             }
210             childNodes = child.build();
211         }
212
213         @Override
214         public Optional<ModificationApplyOperation> getChild(final YangInstanceIdentifier.PathArgument child) {
215             return Optional.fromNullable(childNodes.get(child));
216         }
217
218         @Override
219         @SuppressWarnings("rawtypes")
220         protected DataContainerNodeBuilder createBuilder(final NormalizedNode<?, ?> original) {
221             checkArgument(original instanceof org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode);
222             return ImmutableChoiceNodeBuilder.create((org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode) original);
223         }
224     }
225
226     public static class OrderedLeafSetModificationStrategy extends NormalizedNodeContainerModificationStrategy {
227
228         private final Optional<ModificationApplyOperation> entryStrategy;
229
230         @SuppressWarnings({ "unchecked", "rawtypes" })
231         protected OrderedLeafSetModificationStrategy(final LeafListSchemaNode schema) {
232             super((Class) LeafSetNode.class);
233             entryStrategy = Optional.<ModificationApplyOperation> of(new ValueNodeModificationStrategy.LeafSetEntryModificationStrategy(schema));
234         }
235
236         @Override
237         boolean isOrdered() {
238             return true;
239         }
240
241         @SuppressWarnings("rawtypes")
242         @Override
243         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
244             checkArgument(original instanceof OrderedLeafSetNode<?>);
245             return ImmutableOrderedLeafSetNodeBuilder.create((OrderedLeafSetNode<?>) original);
246         }
247
248         @Override
249         public Optional<ModificationApplyOperation> getChild(final YangInstanceIdentifier.PathArgument identifier) {
250             if (identifier instanceof YangInstanceIdentifier.NodeWithValue) {
251                 return entryStrategy;
252             }
253             return Optional.absent();
254         }
255     }
256
257     public static class OrderedMapModificationStrategy extends NormalizedNodeContainerModificationStrategy {
258
259         private final Optional<ModificationApplyOperation> entryStrategy;
260
261         protected OrderedMapModificationStrategy(final ListSchemaNode schema) {
262             super(OrderedMapNode.class);
263             entryStrategy = Optional.<ModificationApplyOperation> of(new DataNodeContainerModificationStrategy.ListEntryModificationStrategy(schema));
264         }
265
266         @Override
267         boolean isOrdered() {
268             return true;
269         }
270
271         @SuppressWarnings("rawtypes")
272         @Override
273         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
274             checkArgument(original instanceof OrderedMapNode);
275             return ImmutableOrderedMapNodeBuilder.create((OrderedMapNode) original);
276         }
277
278         @Override
279         public Optional<ModificationApplyOperation> getChild(final YangInstanceIdentifier.PathArgument identifier) {
280             if (identifier instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
281                 return entryStrategy;
282             }
283             return Optional.absent();
284         }
285
286         @Override
287         public String toString() {
288             return "OrderedMapModificationStrategy [entry=" + entryStrategy + "]";
289         }
290     }
291
292     public static class UnorderedLeafSetModificationStrategy extends NormalizedNodeContainerModificationStrategy {
293
294         private final Optional<ModificationApplyOperation> entryStrategy;
295
296         @SuppressWarnings({ "unchecked", "rawtypes" })
297         protected UnorderedLeafSetModificationStrategy(final LeafListSchemaNode schema) {
298             super((Class) LeafSetNode.class);
299             entryStrategy = Optional.<ModificationApplyOperation> of(new ValueNodeModificationStrategy.LeafSetEntryModificationStrategy(schema));
300         }
301
302         @SuppressWarnings("rawtypes")
303         @Override
304         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
305             checkArgument(original instanceof LeafSetNode<?>);
306             return ImmutableLeafSetNodeBuilder.create((LeafSetNode<?>) original);
307         }
308
309         @Override
310         public Optional<ModificationApplyOperation> getChild(final YangInstanceIdentifier.PathArgument identifier) {
311             if (identifier instanceof YangInstanceIdentifier.NodeWithValue) {
312                 return entryStrategy;
313             }
314             return Optional.absent();
315         }
316     }
317
318     public static class UnorderedMapModificationStrategy extends NormalizedNodeContainerModificationStrategy {
319
320         private final Optional<ModificationApplyOperation> entryStrategy;
321
322         protected UnorderedMapModificationStrategy(final ListSchemaNode schema) {
323             super(MapNode.class);
324             entryStrategy = Optional.<ModificationApplyOperation> of(new DataNodeContainerModificationStrategy.ListEntryModificationStrategy(schema));
325         }
326
327         @SuppressWarnings("rawtypes")
328         @Override
329         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
330             checkArgument(original instanceof MapNode);
331             return ImmutableMapNodeBuilder.create((MapNode) original);
332         }
333
334         @Override
335         public Optional<ModificationApplyOperation> getChild(final YangInstanceIdentifier.PathArgument identifier) {
336             if (identifier instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
337                 return entryStrategy;
338             }
339             return Optional.absent();
340         }
341
342         @Override
343         public String toString() {
344             return "UnorderedMapModificationStrategy [entry=" + entryStrategy + "]";
345         }
346     }
347 }