Cleanup use of Guava library
[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.Preconditions;
13 import com.google.common.base.Verify;
14 import java.util.Collection;
15 import java.util.Optional;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
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.tree.ConflictingModificationAppliedException;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
30 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
31
32 abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareApplyOperation {
33
34     private final Class<? extends NormalizedNode<?, ?>> nodeClass;
35     private final boolean verifyChildrenStructure;
36
37     protected AbstractNodeContainerModificationStrategy(final Class<? extends NormalizedNode<?, ?>> nodeClass,
38             final DataTreeConfiguration treeConfig) {
39         this.nodeClass = Preconditions.checkNotNull(nodeClass , "nodeClass");
40         this.verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
41     }
42
43     @SuppressWarnings("rawtypes")
44     @Override
45     void verifyStructure(final NormalizedNode<?, ?> writtenValue, final boolean verifyChildren) {
46         checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
47         checkArgument(writtenValue instanceof NormalizedNodeContainer);
48         if (verifyChildrenStructure && verifyChildren) {
49             final NormalizedNodeContainer container = (NormalizedNodeContainer) writtenValue;
50             for (final Object child : container.getValue()) {
51                 checkArgument(child instanceof NormalizedNode);
52                 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
53                 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
54                 if (childOp.isPresent()) {
55                     childOp.get().verifyStructure(castedChild, verifyChildren);
56                 } else {
57                     throw new SchemaValidationFailedException(String.format(
58                             "Node %s is not a valid child of %s according to the schema.",
59                             castedChild.getIdentifier(), container.getIdentifier()));
60                 }
61             }
62         }
63     }
64
65     @Override
66     protected void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
67         final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
68         for (final Object child : container.getValue()) {
69             checkArgument(child instanceof NormalizedNode);
70             final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
71             final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
72             if (childOp.isPresent()) {
73                 childOp.get().recursivelyVerifyStructure(castedChild);
74             } else {
75                 throw new SchemaValidationFailedException(
76                     String.format("Node %s is not a valid child of %s according to the schema.",
77                         castedChild.getIdentifier(), container.getIdentifier()));
78             }
79         }
80     }
81
82     @Override
83     protected TreeNode applyWrite(final ModifiedNode modification,
84             final Optional<TreeNode> currentMeta, final Version version) {
85         final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
86         final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
87
88         if (modification.getChildren().isEmpty()) {
89             return newValueMeta;
90         }
91
92         /*
93          * This is where things get interesting. The user has performed a write and
94          * then she applied some more modifications to it. So we need to make sense
95          * of that an apply the operations on top of the written value. We could have
96          * done it during the write, but this operation is potentially expensive, so
97          * we have left it out of the fast path.
98          *
99          * As it turns out, once we materialize the written data, we can share the
100          * code path with the subtree change. So let's create an unsealed TreeNode
101          * and run the common parts on it -- which end with the node being sealed.
102          *
103          * FIXME: this code needs to be moved out from the prepare() path and into
104          *        the read() and seal() paths. Merging of writes needs to be charged
105          *        to the code which originated this, not to the code which is
106          *        attempting to make it visible.
107          */
108         final MutableTreeNode mutable = newValueMeta.mutable();
109         mutable.setSubtreeVersion(version);
110
111         @SuppressWarnings("rawtypes")
112         final NormalizedNodeContainerBuilder dataBuilder = createBuilder(newValue);
113         final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
114
115         // We are good to go except one detail: this is a single logical write, but
116         // we have a result TreeNode which has been forced to materialized, e.g. it
117         // is larger than it needs to be. Create a new TreeNode to host the data.
118         return TreeNodeFactory.createTreeNode(result.getData(), version);
119     }
120
121     /**
122      * Applies write/remove diff operation for each modification child in modification subtree.
123      * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
124      *
125      * @param meta MutableTreeNode (IndexTreeNode)
126      * @param data DataBuilder
127      * @param nodeVersion Version of TreeNode
128      * @param modifications modification operations to apply
129      * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
130      */
131     @SuppressWarnings({ "rawtypes", "unchecked" })
132     private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
133             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
134
135         for (final ModifiedNode mod : modifications) {
136             final YangInstanceIdentifier.PathArgument id = mod.getIdentifier();
137             final Optional<TreeNode> cm = meta.getChild(id);
138
139             final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
140             if (result.isPresent()) {
141                 final TreeNode tn = result.get();
142                 meta.addChild(tn);
143                 data.addChild(tn.getData());
144             } else {
145                 meta.removeChild(id);
146                 data.removeChild(id);
147             }
148         }
149
150         meta.setData(data.build());
151         return meta.seal();
152     }
153
154     @Override
155     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
156         /*
157          * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
158          * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
159          * heavy lifting of applying the children recursively (either through here or through applyWrite().
160          */
161         final NormalizedNode<?, ?> value = modification.getWrittenValue();
162
163         Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
164         @SuppressWarnings({"unchecked", "rawtypes"})
165         final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
166         for (final NormalizedNode<?, ?> c : children) {
167             final PathArgument id = c.getIdentifier();
168             modification.modifyChild(id, resolveChildOperation(id), version);
169         }
170         return applyTouch(modification, currentMeta, version);
171     }
172
173     private void mergeChildrenIntoModification(final ModifiedNode modification,
174             final Collection<NormalizedNode<?, ?>> children, final Version version) {
175         for (final NormalizedNode<?, ?> c : children) {
176             final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
177             final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
178             childOp.mergeIntoModifiedNode(childNode, c, version);
179         }
180     }
181
182     @Override
183     final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
184             final Version version) {
185         @SuppressWarnings({ "unchecked", "rawtypes" })
186         final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
187
188         switch (modification.getOperation()) {
189             case NONE:
190                 // Fresh node, just record a MERGE with a value
191                 recursivelyVerifyStructure(value);
192                 modification.updateValue(LogicalOperation.MERGE, value);
193                 return;
194             case TOUCH:
195
196                 mergeChildrenIntoModification(modification, children, version);
197                 // We record empty merge value, since real children merges
198                 // are already expanded. This is needed to satisfy non-null for merge
199                 // original merge value can not be used since it mean different
200                 // order of operation - parent changes are always resolved before
201                 // children ones, and having node in TOUCH means children was modified
202                 // before.
203                 modification.updateValue(LogicalOperation.MERGE, createEmptyValue(value));
204                 return;
205             case MERGE:
206                 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
207                 // as MERGE, invalidating cached snapshot
208                 mergeChildrenIntoModification(modification, children, version);
209                 modification.updateOperationType(LogicalOperation.MERGE);
210                 return;
211             case DELETE:
212                 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
213                 // we are really performing a write. One thing that ruins that are any child modifications. If there
214                 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
215                 // and then append any child entries.
216                 if (!modification.getChildren().isEmpty()) {
217                     // Version does not matter here as we'll throw it out
218                     final Optional<TreeNode> current = apply(modification, modification.getOriginal(),
219                         Version.initial());
220                     if (current.isPresent()) {
221                         modification.updateValue(LogicalOperation.WRITE, current.get().getData());
222                         mergeChildrenIntoModification(modification, children, version);
223                         return;
224                     }
225                 }
226
227                 modification.updateValue(LogicalOperation.WRITE, value);
228                 return;
229             case WRITE:
230                 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
231                 // ModifiedNode and run recursively on it
232                 mergeChildrenIntoModification(modification, children, version);
233                 modification.updateOperationType(LogicalOperation.WRITE);
234                 return;
235             default:
236                 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
237         }
238     }
239
240     @Override
241     protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
242         /*
243          * The user may have issued an empty merge operation. In this case we do not perform
244          * a data tree mutation, do not pass GO, and do not collect useless garbage. It
245          * also means the ModificationType is UNMODIFIED.
246          */
247         final Collection<ModifiedNode> children = modification.getChildren();
248         if (!children.isEmpty()) {
249             @SuppressWarnings("rawtypes")
250             final NormalizedNodeContainerBuilder dataBuilder = createBuilder(currentMeta.getData());
251             final MutableTreeNode newMeta = currentMeta.mutable();
252             newMeta.setSubtreeVersion(version);
253             final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
254
255             /*
256              * It is possible that the only modifications under this node were empty merges,
257              * which were turned into UNMODIFIED. If that is the case, we can turn this operation
258              * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
259              * of speeding up any users, who can skip processing child nodes.
260              *
261              * In order to do that, though, we have to check all child operations are UNMODIFIED.
262              * Let's do precisely that, stopping as soon we find a different result.
263              */
264             for (final ModifiedNode child : children) {
265                 if (child.getModificationType() != ModificationType.UNMODIFIED) {
266                     modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
267                     return ret;
268                 }
269             }
270         }
271
272         // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
273         // replace the metadata node.
274         modification.resolveModificationType(ModificationType.UNMODIFIED);
275         return currentMeta;
276     }
277
278     @Override
279     protected void checkTouchApplicable(final YangInstanceIdentifier path, final NodeModification modification,
280             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
281         if (!modification.getOriginal().isPresent() && !current.isPresent()) {
282             throw new ModifiedNodeDoesNotExistException(path,
283                 String.format("Node %s does not exist. Cannot apply modification to its children.", path));
284         }
285
286         if (!current.isPresent()) {
287             throw new ConflictingModificationAppliedException(path, "Node was deleted by other transaction.");
288         }
289
290         checkChildPreconditions(path, modification, current.get(), version);
291     }
292
293     /**
294      * Recursively check child preconditions.
295      *
296      * @param path current node path
297      * @param modification current modification
298      * @param current Current data tree node.
299      */
300     private void checkChildPreconditions(final YangInstanceIdentifier path, final NodeModification modification,
301             final TreeNode current, final Version version) throws DataValidationFailedException {
302         for (final NodeModification childMod : modification.getChildren()) {
303             final YangInstanceIdentifier.PathArgument childId = childMod.getIdentifier();
304             final Optional<TreeNode> childMeta = current.getChild(childId);
305
306             final YangInstanceIdentifier childPath = path.node(childId);
307             resolveChildOperation(childId).checkApplicable(childPath, childMod, childMeta, version);
308         }
309     }
310
311     @Override
312     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification,
313             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
314         if (current.isPresent()) {
315             checkChildPreconditions(path, modification, current.get(), version);
316         }
317     }
318
319     protected boolean verifyChildrenStructure() {
320         return verifyChildrenStructure;
321     }
322
323     @SuppressWarnings("rawtypes")
324     protected abstract NormalizedNodeContainerBuilder createBuilder(NormalizedNode<?, ?> original);
325
326     protected abstract NormalizedNode<?, ?> createEmptyValue(NormalizedNode<?, ?> original);
327 }