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