Turn ModificationApplyOperation into an abstract class
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / AbstractNodeContainerModificationStrategy.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.base.Preconditions;
13 import java.util.Collection;
14 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
15 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
16 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
17 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
18 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
24 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
25
26 abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareApplyOperation {
27
28     private final Class<? extends NormalizedNode<?, ?>> nodeClass;
29
30     protected AbstractNodeContainerModificationStrategy(final Class<? extends NormalizedNode<?, ?>> nodeClass) {
31         this.nodeClass = Preconditions.checkNotNull(nodeClass);
32     }
33
34     @Override
35     void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
36         for (ModifiedNode childModification : modification.getChildren()) {
37             resolveChildOperation(childModification.getIdentifier()).verifyStructure(childModification);
38         }
39     }
40
41     @SuppressWarnings("rawtypes")
42     @Override
43     protected void verifyWrittenStructure(final NormalizedNode<?, ?> writtenValue) {
44         checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
45         checkArgument(writtenValue instanceof NormalizedNodeContainer);
46
47         NormalizedNodeContainer container = (NormalizedNodeContainer) writtenValue;
48         for (Object child : container.getValue()) {
49             checkArgument(child instanceof NormalizedNode);
50
51             /*
52              * FIXME: fail-fast semantics:
53              *
54              * We can validate the data structure here, aborting the commit
55              * before it ever progresses to being committed.
56              */
57         }
58     }
59
60     @Override
61     protected TreeNode applyWrite(final ModifiedNode modification,
62             final Optional<TreeNode> currentMeta, final Version version) {
63         final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
64         final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
65
66         if (modification.getChildren().isEmpty()) {
67             return newValueMeta;
68         }
69
70         /*
71          * This is where things get interesting. The user has performed a write and
72          * then she applied some more modifications to it. So we need to make sense
73          * of that an apply the operations on top of the written value. We could have
74          * done it during the write, but this operation is potentially expensive, so
75          * we have left it out of the fast path.
76          *
77          * As it turns out, once we materialize the written data, we can share the
78          * code path with the subtree change. So let's create an unsealed TreeNode
79          * and run the common parts on it -- which end with the node being sealed.
80          *
81          * FIXME: this code needs to be moved out from the prepare() path and into
82          *        the read() and seal() paths. Merging of writes needs to be charged
83          *        to the code which originated this, not to the code which is
84          *        attempting to make it visible.
85          */
86         final MutableTreeNode mutable = newValueMeta.mutable();
87         mutable.setSubtreeVersion(version);
88
89         @SuppressWarnings("rawtypes")
90         final NormalizedNodeContainerBuilder dataBuilder = createBuilder(newValue);
91
92         return mutateChildren(mutable, dataBuilder, version, modification.getChildren());
93     }
94
95     /**
96      * Applies write/remove diff operation for each modification child in modification subtree.
97      * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
98      *
99      * @param meta MutableTreeNode (IndexTreeNode)
100      * @param data DataBuilder
101      * @param nodeVersion Version of TreeNode
102      * @param modifications modification operations to apply
103      * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
104      */
105     @SuppressWarnings({ "rawtypes", "unchecked" })
106     private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
107             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
108
109         for (ModifiedNode mod : modifications) {
110             final YangInstanceIdentifier.PathArgument id = mod.getIdentifier();
111             final Optional<TreeNode> cm = meta.getChild(id);
112
113             Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
114             if (result.isPresent()) {
115                 final TreeNode tn = result.get();
116                 meta.addChild(tn);
117                 data.addChild(tn.getData());
118             } else {
119                 meta.removeChild(id);
120                 data.removeChild(id);
121             }
122         }
123
124         meta.setData(data.build());
125         return meta.seal();
126     }
127
128     @Override
129     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta,
130             final Version version) {
131         // For Node Containers - merge is same as subtree change - we only replace children.
132         return applySubtreeChange(modification, currentMeta, version);
133     }
134
135     @Override
136     public TreeNode applySubtreeChange(final ModifiedNode modification,
137             final TreeNode currentMeta, final Version version) {
138         final MutableTreeNode newMeta = currentMeta.mutable();
139         newMeta.setSubtreeVersion(version);
140
141         /*
142          * The user has issued an empty merge operation. In this case we do not perform
143          * a data tree mutation, do not pass GO, and do not collect useless garbage.
144          */
145         final Collection<ModifiedNode> children = modification.getChildren();
146         if (children.isEmpty()) {
147             modification.resolveModificationType(ModificationType.UNMODIFIED);
148             newMeta.setData(currentMeta.getData());
149             return newMeta.seal();
150         }
151
152         @SuppressWarnings("rawtypes")
153         NormalizedNodeContainerBuilder dataBuilder = createBuilder(currentMeta.getData());
154
155         /*
156          * TODO: this is not entirely accurate. If there is only an empty merge operation
157          *       among the children, its effect is ModificationType.UNMODIFIED. That would
158          *       mean this operation can be turned into UNMODIFIED, cascading that further
159          *       up the root -- potentially turning the entire transaction into a no-op
160          *       from the perspective of physical replication.
161          *
162          *       In order to do that, though, we either have to walk the children ourselves
163          *       (looking for a non-UNMODIFIED child), or have mutateChildren() pass that
164          *       information back to us.
165          */
166         modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
167         return mutateChildren(newMeta, dataBuilder, version, children);
168     }
169
170     @Override
171     protected void checkSubtreeModificationApplicable(final YangInstanceIdentifier path, final NodeModification modification,
172             final Optional<TreeNode> current) throws DataValidationFailedException {
173         if (!modification.getOriginal().isPresent() && !current.isPresent()) {
174             throw new ModifiedNodeDoesNotExistException(path, String.format("Node %s does not exist. Cannot apply modification to its children.", path));
175         }
176
177         SchemaAwareApplyOperation.checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
178         checkChildPreconditions(path, modification, current);
179     }
180
181     private void checkChildPreconditions(final YangInstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
182         final TreeNode currentMeta = current.get();
183         for (NodeModification childMod : modification.getChildren()) {
184             final YangInstanceIdentifier.PathArgument childId = childMod.getIdentifier();
185             final Optional<TreeNode> childMeta = currentMeta.getChild(childId);
186
187             YangInstanceIdentifier childPath = path.node(childId);
188             resolveChildOperation(childId).checkApplicable(childPath, childMod, childMeta);
189         }
190     }
191
192     @Override
193     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification,
194             final Optional<TreeNode> current) throws DataValidationFailedException {
195         if(current.isPresent()) {
196             checkChildPreconditions(path, modification,current);
197         }
198     }
199
200     @SuppressWarnings("rawtypes")
201     protected abstract NormalizedNodeContainerBuilder createBuilder(NormalizedNode<?, ?> original);
202 }