b323e6b397fbda9e4b9c5ada6e664de5a5d447eb
[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 applyTouch(modification, currentMeta, version);
133     }
134
135     @Override
136     public TreeNode applyTouch(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. It
144          * also means the ModificationType is UNMODIFIED.
145          */
146         final Collection<ModifiedNode> children = modification.getChildren();
147         if (children.isEmpty()) {
148             modification.resolveModificationType(ModificationType.UNMODIFIED);
149             newMeta.setData(currentMeta.getData());
150             return newMeta.seal();
151         }
152
153         @SuppressWarnings("rawtypes")
154         final NormalizedNodeContainerBuilder dataBuilder = createBuilder(currentMeta.getData());
155         final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
156
157         /*
158          * It is possible that the only modifications under this node were empty merges,
159          * which were turned into UNMODIFIED. If that is the case, we can turn this operation
160          * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
161          * of speeding up any users, who can skip processing child nodes.
162          *
163          * In order to do that, though, we have to check all child operations are UNMODIFIED.
164          * Let's do precisely that, stopping as soon we find a different result.
165          */
166         for (ModifiedNode child : children) {
167             if (child.getModificationType() != ModificationType.UNMODIFIED) {
168                 modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
169                 return ret;
170             }
171         }
172
173         modification.resolveModificationType(ModificationType.UNMODIFIED);
174         return ret;
175     }
176
177     @Override
178     protected void checkTouchApplicable(final YangInstanceIdentifier path, final NodeModification modification,
179             final Optional<TreeNode> current) throws DataValidationFailedException {
180         if (!modification.getOriginal().isPresent() && !current.isPresent()) {
181             throw new ModifiedNodeDoesNotExistException(path, String.format("Node %s does not exist. Cannot apply modification to its children.", path));
182         }
183
184         SchemaAwareApplyOperation.checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
185         checkChildPreconditions(path, modification, current);
186     }
187
188     private void checkChildPreconditions(final YangInstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
189         final TreeNode currentMeta = current.get();
190         for (NodeModification childMod : modification.getChildren()) {
191             final YangInstanceIdentifier.PathArgument childId = childMod.getIdentifier();
192             final Optional<TreeNode> childMeta = currentMeta.getChild(childId);
193
194             YangInstanceIdentifier childPath = path.node(childId);
195             resolveChildOperation(childId).checkApplicable(childPath, childMod, childMeta);
196         }
197     }
198
199     @Override
200     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification,
201             final Optional<TreeNode> current) throws DataValidationFailedException {
202         if(current.isPresent()) {
203             checkChildPreconditions(path, modification,current);
204         }
205     }
206
207     @SuppressWarnings("rawtypes")
208     protected abstract NormalizedNodeContainerBuilder createBuilder(NormalizedNode<?, ?> original);
209 }