b7f2f6003c385d69429c83d69c8e07e28ec60667
[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
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import java.util.Collection;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
17 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
18 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
27 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
28
29 abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareApplyOperation {
30
31     private final Class<? extends NormalizedNode<?, ?>> nodeClass;
32     private final boolean verifyChildrenStructure;
33
34     protected AbstractNodeContainerModificationStrategy(final Class<? extends NormalizedNode<?, ?>> nodeClass,
35             final TreeType treeType) {
36         this.nodeClass = Preconditions.checkNotNull(nodeClass , "nodeClass");
37         this.verifyChildrenStructure = (treeType == TreeType.CONFIGURATION);
38     }
39
40     @SuppressWarnings("rawtypes")
41     @Override
42     void verifyStructure(final NormalizedNode<?, ?> writtenValue, final boolean verifyChildren) {
43         checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
44         checkArgument(writtenValue instanceof NormalizedNodeContainer);
45         if (verifyChildrenStructure && verifyChildren) {
46             final NormalizedNodeContainer container = (NormalizedNodeContainer) writtenValue;
47             for (final Object child : container.getValue()) {
48                 checkArgument(child instanceof NormalizedNode);
49                 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
50                 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
51                 if (childOp.isPresent()) {
52                     childOp.get().verifyStructure(castedChild, verifyChildren);
53                 } else {
54                     throw new SchemaValidationFailedException(String.format(
55                             "Child %s is not valid child according to schema.", castedChild.getIdentifier()));
56                 }
57             }
58         }
59     }
60
61     @Override
62     protected TreeNode applyWrite(final ModifiedNode modification,
63             final Optional<TreeNode> currentMeta, final Version version) {
64         final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
65         final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
66
67         if (modification.getChildren().isEmpty()) {
68             return newValueMeta;
69         }
70
71         /*
72          * This is where things get interesting. The user has performed a write and
73          * then she applied some more modifications to it. So we need to make sense
74          * of that an apply the operations on top of the written value. We could have
75          * done it during the write, but this operation is potentially expensive, so
76          * we have left it out of the fast path.
77          *
78          * As it turns out, once we materialize the written data, we can share the
79          * code path with the subtree change. So let's create an unsealed TreeNode
80          * and run the common parts on it -- which end with the node being sealed.
81          *
82          * FIXME: this code needs to be moved out from the prepare() path and into
83          *        the read() and seal() paths. Merging of writes needs to be charged
84          *        to the code which originated this, not to the code which is
85          *        attempting to make it visible.
86          */
87         final MutableTreeNode mutable = newValueMeta.mutable();
88         mutable.setSubtreeVersion(version);
89
90         @SuppressWarnings("rawtypes")
91         final NormalizedNodeContainerBuilder dataBuilder = createBuilder(newValue);
92         final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
93
94         // We are good to go except one detail: this is a single logical write, but
95         // we have a result TreeNode which has been forced to materialized, e.g. it
96         // is larger than it needs to be. Create a new TreeNode to host the data.
97         return TreeNodeFactory.createTreeNode(result.getData(), version);
98     }
99
100     /**
101      * Applies write/remove diff operation for each modification child in modification subtree.
102      * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
103      *
104      * @param meta MutableTreeNode (IndexTreeNode)
105      * @param data DataBuilder
106      * @param nodeVersion Version of TreeNode
107      * @param modifications modification operations to apply
108      * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
109      */
110     @SuppressWarnings({ "rawtypes", "unchecked" })
111     private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
112             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
113
114         for (final ModifiedNode mod : modifications) {
115             final YangInstanceIdentifier.PathArgument id = mod.getIdentifier();
116             final Optional<TreeNode> cm = meta.getChild(id);
117
118             final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
119             if (result.isPresent()) {
120                 final TreeNode tn = result.get();
121                 meta.addChild(tn);
122                 data.addChild(tn.getData());
123             } else {
124                 meta.removeChild(id);
125                 data.removeChild(id);
126             }
127         }
128
129         meta.setData(data.build());
130         return meta.seal();
131     }
132
133     @Override
134     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta,
135             final Version version) {
136         // For Node Containers - merge is same as subtree change - we only replace children.
137         return applyTouch(modification, currentMeta, version);
138     }
139
140     @Override
141     protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
142         /*
143          * The user may have issued an empty merge operation. In this case we do not perform
144          * a data tree mutation, do not pass GO, and do not collect useless garbage. It
145          * also means the ModificationType is UNMODIFIED.
146          */
147         final Collection<ModifiedNode> children = modification.getChildren();
148         if (!children.isEmpty()) {
149             @SuppressWarnings("rawtypes")
150             final NormalizedNodeContainerBuilder dataBuilder = createBuilder(currentMeta.getData());
151             final MutableTreeNode newMeta = currentMeta.mutable();
152             newMeta.setSubtreeVersion(version);
153             final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
154
155             /*
156              * It is possible that the only modifications under this node were empty merges,
157              * which were turned into UNMODIFIED. If that is the case, we can turn this operation
158              * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
159              * of speeding up any users, who can skip processing child nodes.
160              *
161              * In order to do that, though, we have to check all child operations are UNMODIFIED.
162              * Let's do precisely that, stopping as soon we find a different result.
163              */
164             for (final ModifiedNode child : children) {
165                 if (child.getModificationType() != ModificationType.UNMODIFIED) {
166                     modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
167                     return ret;
168                 }
169             }
170         }
171
172         // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
173         // replace the metadata node.
174         modification.resolveModificationType(ModificationType.UNMODIFIED);
175         return currentMeta;
176     }
177
178     @Override
179     protected void checkTouchApplicable(final YangInstanceIdentifier path, final NodeModification modification,
180             final Optional<TreeNode> current) throws DataValidationFailedException {
181         if (!modification.getOriginal().isPresent() && !current.isPresent()) {
182             throw new ModifiedNodeDoesNotExistException(path, String.format("Node %s does not exist. Cannot apply modification to its children.", path));
183         }
184
185         if (!current.isPresent()) {
186             throw new ConflictingModificationAppliedException(path, "Node was deleted by other transaction.");
187         }
188
189         checkChildPreconditions(path, modification, current.get());
190     }
191
192     /**
193      * Recursively check child preconditions.
194      *
195      * @param path current node path
196      * @param modification current modification
197      * @param current Current data tree node.
198      */
199     private void checkChildPreconditions(final YangInstanceIdentifier path, final NodeModification modification, final TreeNode current) throws DataValidationFailedException {
200         for (final NodeModification childMod : modification.getChildren()) {
201             final YangInstanceIdentifier.PathArgument childId = childMod.getIdentifier();
202             final Optional<TreeNode> childMeta = current.getChild(childId);
203
204             final YangInstanceIdentifier childPath = path.node(childId);
205             resolveChildOperation(childId).checkApplicable(childPath, childMod, childMeta);
206         }
207     }
208
209     @Override
210     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification,
211             final Optional<TreeNode> current) throws DataValidationFailedException {
212         if (current.isPresent()) {
213             checkChildPreconditions(path, modification, current.get());
214         }
215     }
216
217     protected boolean verifyChildrenStructure() {
218         return verifyChildrenStructure;
219     }
220
221     @SuppressWarnings("rawtypes")
222     protected abstract NormalizedNodeContainerBuilder createBuilder(NormalizedNode<?, ?> original);
223 }