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     @SuppressWarnings({ "rawtypes", "unchecked" })
112     private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
113             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
114
115         for (ModifiedNode mod : modifications) {
116             final YangInstanceIdentifier.PathArgument id = mod.getIdentifier();
117             final Optional<TreeNode> cm = meta.getChild(id);
118
119             Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
120             if (result.isPresent()) {
121                 final TreeNode tn = result.get();
122                 meta.addChild(tn);
123                 data.addChild(tn.getData());
124             } else {
125                 meta.removeChild(id);
126                 data.removeChild(id);
127             }
128         }
129
130         meta.setData(data.build());
131         return meta.seal();
132     }
133
134     @Override
135     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta,
136             final Version version) {
137         // For Node Containers - merge is same as subtree change - we only replace children.
138         return applySubtreeChange(modification, currentMeta, version);
139     }
140
141     @Override
142     public TreeNode applySubtreeChange(final ModifiedNode modification,
143             final TreeNode currentMeta, final Version version) {
144         final MutableTreeNode newMeta = currentMeta.mutable();
145         newMeta.setSubtreeVersion(version);
146
147         @SuppressWarnings("rawtypes")
148         NormalizedNodeContainerBuilder dataBuilder = createBuilder(currentMeta.getData());
149
150         return mutateChildren(newMeta, dataBuilder, version, modification.getChildren());
151     }
152
153     @Override
154     protected void checkSubtreeModificationApplicable(final YangInstanceIdentifier path, final NodeModification modification,
155             final Optional<TreeNode> current) throws DataValidationFailedException {
156         if (!modification.getOriginal().isPresent() && !current.isPresent()) {
157             throw new ModifiedNodeDoesNotExistException(path, String.format("Node %s does not exist. Cannot apply modification to its children.", path));
158         }
159
160         SchemaAwareApplyOperation.checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
161         checkChildPreconditions(path, modification, current);
162     }
163
164     private void checkChildPreconditions(final YangInstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
165         final TreeNode currentMeta = current.get();
166         for (NodeModification childMod : modification.getChildren()) {
167             final YangInstanceIdentifier.PathArgument childId = childMod.getIdentifier();
168             final Optional<TreeNode> childMeta = currentMeta.getChild(childId);
169
170             YangInstanceIdentifier childPath = path.node(childId);
171             resolveChildOperation(childId).checkApplicable(childPath, childMod, childMeta);
172         }
173     }
174
175     @Override
176     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification,
177             final Optional<TreeNode> current) throws DataValidationFailedException {
178         if(current.isPresent()) {
179             checkChildPreconditions(path, modification,current);
180         }
181     }
182
183     @SuppressWarnings("rawtypes")
184     protected abstract NormalizedNodeContainerBuilder createBuilder(NormalizedNode<?, ?> original);
185
186     public static class ChoiceModificationStrategy extends NormalizedNodeContainerModificationStrategy {
187
188         private final Map<YangInstanceIdentifier.PathArgument, ModificationApplyOperation> childNodes;
189
190         public ChoiceModificationStrategy(final ChoiceNode schemaNode) {
191             super(org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode.class);
192             ImmutableMap.Builder<YangInstanceIdentifier.PathArgument, ModificationApplyOperation> child = ImmutableMap.builder();
193
194             for (ChoiceCaseNode caze : schemaNode.getCases()) {
195                 for (DataSchemaNode cazeChild : caze.getChildNodes()) {
196                     SchemaAwareApplyOperation childNode = SchemaAwareApplyOperation.from(cazeChild);
197                     child.put(new YangInstanceIdentifier.NodeIdentifier(cazeChild.getQName()), childNode);
198                 }
199             }
200             childNodes = child.build();
201         }
202
203         @Override
204         public Optional<ModificationApplyOperation> getChild(final YangInstanceIdentifier.PathArgument child) {
205             return Optional.fromNullable(childNodes.get(child));
206         }
207
208         @Override
209         @SuppressWarnings("rawtypes")
210         protected DataContainerNodeBuilder createBuilder(final NormalizedNode<?, ?> original) {
211             checkArgument(original instanceof org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode);
212             return ImmutableChoiceNodeBuilder.create((org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode) original);
213         }
214     }
215
216     public static class OrderedLeafSetModificationStrategy extends NormalizedNodeContainerModificationStrategy {
217
218         private final Optional<ModificationApplyOperation> entryStrategy;
219
220         @SuppressWarnings({ "unchecked", "rawtypes" })
221         protected OrderedLeafSetModificationStrategy(final LeafListSchemaNode schema) {
222             super((Class) LeafSetNode.class);
223             entryStrategy = Optional.<ModificationApplyOperation> of(new ValueNodeModificationStrategy.LeafSetEntryModificationStrategy(schema));
224         }
225
226         @SuppressWarnings("rawtypes")
227         @Override
228         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
229             checkArgument(original instanceof OrderedLeafSetNode<?>);
230             return ImmutableOrderedLeafSetNodeBuilder.create((OrderedLeafSetNode<?>) original);
231         }
232
233         @Override
234         public Optional<ModificationApplyOperation> getChild(final YangInstanceIdentifier.PathArgument identifier) {
235             if (identifier instanceof YangInstanceIdentifier.NodeWithValue) {
236                 return entryStrategy;
237             }
238             return Optional.absent();
239         }
240     }
241
242     public static class OrderedMapModificationStrategy extends NormalizedNodeContainerModificationStrategy {
243
244         private final Optional<ModificationApplyOperation> entryStrategy;
245
246         protected OrderedMapModificationStrategy(final ListSchemaNode schema) {
247             super(OrderedMapNode.class);
248             entryStrategy = Optional.<ModificationApplyOperation> of(new DataNodeContainerModificationStrategy.ListEntryModificationStrategy(schema));
249         }
250
251         @SuppressWarnings("rawtypes")
252         @Override
253         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
254             checkArgument(original instanceof OrderedMapNode);
255             return ImmutableOrderedMapNodeBuilder.create((OrderedMapNode) original);
256         }
257
258         @Override
259         public Optional<ModificationApplyOperation> getChild(final YangInstanceIdentifier.PathArgument identifier) {
260             if (identifier instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
261                 return entryStrategy;
262             }
263             return Optional.absent();
264         }
265
266         @Override
267         public String toString() {
268             return "OrderedMapModificationStrategy [entry=" + entryStrategy + "]";
269         }
270     }
271
272     public static class UnorderedLeafSetModificationStrategy extends NormalizedNodeContainerModificationStrategy {
273
274         private final Optional<ModificationApplyOperation> entryStrategy;
275
276         @SuppressWarnings({ "unchecked", "rawtypes" })
277         protected UnorderedLeafSetModificationStrategy(final LeafListSchemaNode schema) {
278             super((Class) LeafSetNode.class);
279             entryStrategy = Optional.<ModificationApplyOperation> of(new ValueNodeModificationStrategy.LeafSetEntryModificationStrategy(schema));
280         }
281
282         @SuppressWarnings("rawtypes")
283         @Override
284         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
285             checkArgument(original instanceof LeafSetNode<?>);
286             return ImmutableLeafSetNodeBuilder.create((LeafSetNode<?>) original);
287         }
288
289         @Override
290         public Optional<ModificationApplyOperation> getChild(final YangInstanceIdentifier.PathArgument identifier) {
291             if (identifier instanceof YangInstanceIdentifier.NodeWithValue) {
292                 return entryStrategy;
293             }
294             return Optional.absent();
295         }
296     }
297
298     public static class UnorderedMapModificationStrategy extends NormalizedNodeContainerModificationStrategy {
299
300         private final Optional<ModificationApplyOperation> entryStrategy;
301
302         protected UnorderedMapModificationStrategy(final ListSchemaNode schema) {
303             super(MapNode.class);
304             entryStrategy = Optional.<ModificationApplyOperation> of(new DataNodeContainerModificationStrategy.ListEntryModificationStrategy(schema));
305         }
306
307         @SuppressWarnings("rawtypes")
308         @Override
309         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
310             checkArgument(original instanceof MapNode);
311             return ImmutableMapNodeBuilder.create((MapNode) original);
312         }
313
314         @Override
315         public Optional<ModificationApplyOperation> getChild(final YangInstanceIdentifier.PathArgument identifier) {
316             if (identifier instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
317                 return entryStrategy;
318             }
319             return Optional.absent();
320         }
321
322         @Override
323         public String toString() {
324             return "UnorderedMapModificationStrategy [entry=" + entryStrategy + "]";
325         }
326     }
327 }