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