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