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