BUG-4295: fix merge callsite
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / ModifiedNode.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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Predicate;
13 import java.util.Collection;
14 import java.util.Map;
15 import javax.annotation.Nonnull;
16 import javax.annotation.concurrent.NotThreadSafe;
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.ModificationType;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
25
26 /**
27  * Node Modification Node and Tree
28  *
29  * Tree which structurally resembles data tree and captures client modifications to the data store tree. This tree is
30  * lazily created and populated via {@link #modifyChild(PathArgument)} and {@link TreeNode} which represents original
31  * state as tracked by {@link #getOriginal()}.
32  *
33  * The contract is that the state information exposed here preserves the temporal ordering of whatever modifications
34  * were executed. A child's effects pertain to data node as modified by its ancestors. This means that in order to
35  * reconstruct the effective data node presentation, it is sufficient to perform a depth-first pre-order traversal of
36  * the tree.
37  */
38 @NotThreadSafe
39 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
40     static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = new Predicate<ModifiedNode>() {
41         @Override
42         public boolean apply(@Nonnull final ModifiedNode input) {
43             Preconditions.checkNotNull(input);
44             switch (input.getOperation()) {
45             case DELETE:
46             case MERGE:
47             case WRITE:
48                 return true;
49             case TOUCH:
50             case NONE:
51                 return false;
52             }
53
54             throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation()));
55         }
56     };
57
58     private final Map<PathArgument, ModifiedNode> children;
59     private final Optional<TreeNode> original;
60     private final PathArgument identifier;
61     private LogicalOperation operation = LogicalOperation.NONE;
62     private Optional<TreeNode> snapshotCache;
63     private NormalizedNode<?, ?> value;
64     private ModificationType modType;
65
66     // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node.
67     private TreeNode writtenOriginal;
68
69     // Internal cache for TreeNodes created as part of validation
70     private SchemaAwareApplyOperation validatedOp;
71     private Optional<TreeNode> validatedCurrent;
72     private TreeNode validatedNode;
73
74     private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final ChildTrackingPolicy childPolicy) {
75         this.identifier = identifier;
76         this.original = original;
77         this.children = childPolicy.createMap();
78     }
79
80     @Override
81     public PathArgument getIdentifier() {
82         return identifier;
83     }
84
85     @Override
86     LogicalOperation getOperation() {
87         return operation;
88     }
89
90     @Override
91     Optional<TreeNode> getOriginal() {
92         return original;
93     }
94
95     /**
96      * Return the value which was written to this node. The returned object is only valid for
97      * {@link LogicalOperation#MERGE} and {@link LogicalOperation#WRITE}.
98      * operations. It should only be consulted when this modification is going to end up being
99      * {@link ModificationType#WRITE}.
100      *
101      * @return Currently-written value
102      */
103     NormalizedNode<?, ?> getWrittenValue() {
104         return value;
105     }
106
107     /**
108      *
109      * Returns child modification if child was modified
110      *
111      * @return Child modification if direct child or it's subtree
112      *  was modified.
113      *
114      */
115     @Override
116     public Optional<ModifiedNode> getChild(final PathArgument child) {
117         return Optional.<ModifiedNode> fromNullable(children.get(child));
118     }
119
120     private Optional<TreeNode> metadataFromSnapshot(@Nonnull final PathArgument child) {
121         return original.isPresent() ? original.get().getChild(child) : Optional.<TreeNode>absent();
122     }
123
124     private Optional<TreeNode> metadataFromData(@Nonnull final PathArgument child, final Version modVersion) {
125         if (writtenOriginal == null) {
126             // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version
127             // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting
128             // modifications.
129             writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion);
130         }
131
132         return writtenOriginal.getChild(child);
133     }
134
135     /**
136      * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because
137      * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need
138      * to take the current node's operation into account.
139      *
140      * @param child Child we are looking to modify
141      * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
142      * @return Before-image tree node as observed by that child.
143      */
144     private Optional<TreeNode> findOriginalMetadata(@Nonnull final PathArgument child, final Version modVersion) {
145         switch (operation) {
146         case DELETE:
147             // DELETE implies non-presence
148             return Optional.absent();
149         case NONE:
150         case TOUCH:
151         case MERGE:
152             return metadataFromSnapshot(child);
153         case WRITE:
154             // WRITE implies presence based on written data
155             return metadataFromData(child, modVersion);
156         }
157
158         throw new IllegalStateException("Unhandled node operation " + operation);
159     }
160
161     /**
162      *
163      * Returns child modification if child was modified, creates {@link ModifiedNode}
164      * for child otherwise.
165      *
166      * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
167      * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}
168      *
169      * @param child child identifier, may not be null
170      * @param childOper Child operation
171      * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
172      * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
173      *         containing child metadata if child was present in original data.
174      */
175     ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ModificationApplyOperation childOper,
176             @Nonnull final Version modVersion) {
177         clearSnapshot();
178         if (operation == LogicalOperation.NONE) {
179             updateOperationType(LogicalOperation.TOUCH);
180         }
181         final ModifiedNode potential = children.get(child);
182         if (potential != null) {
183             return potential;
184         }
185
186         final Optional<TreeNode> currentMetadata = findOriginalMetadata(child, modVersion);
187
188
189         final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childOper.getChildPolicy());
190         if (operation == LogicalOperation.MERGE && value != null) {
191             /*
192              * We are attempting to modify a previously-unmodified part of a MERGE node. If the
193              * value contains this component, we need to materialize it as a MERGE modification.
194              */
195             @SuppressWarnings({ "rawtypes", "unchecked" })
196             final Optional<NormalizedNode<?, ?>> childData = ((NormalizedNodeContainer)value).getChild(child);
197             if (childData.isPresent()) {
198                 childOper.mergeIntoModifiedNode(newlyCreated, childData.get(), modVersion);
199             }
200         }
201
202         children.put(child, newlyCreated);
203         return newlyCreated;
204     }
205
206     /**
207      * Returns all recorded direct child modification
208      *
209      * @return all recorded direct child modifications
210      */
211     @Override
212     Collection<ModifiedNode> getChildren() {
213         return children.values();
214     }
215
216     /**
217      * Records a delete for associated node.
218      */
219     void delete() {
220         final LogicalOperation newType;
221
222         switch (operation) {
223         case DELETE:
224         case NONE:
225             // We need to record this delete.
226             newType = LogicalOperation.DELETE;
227             break;
228         case MERGE:
229                 // In case of merge - delete needs to be recored and must not to be changed into
230                 // NONE, because lazy expansion of parent MERGE node would reintroduce it
231                 // again.
232                 newType = LogicalOperation.DELETE;
233                 break;
234         case TOUCH:
235         case WRITE:
236             /*
237              * We are canceling a previous modification. This is a bit tricky,
238              * as the original write may have just introduced the data, or it
239              * may have modified it.
240              *
241              * As documented in BUG-2470, a delete of data introduced in this
242              * transaction needs to be turned into a no-op.
243              */
244             newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
245             break;
246         default:
247             throw new IllegalStateException("Unhandled deletion of node with " + operation);
248         }
249
250         clearSnapshot();
251         children.clear();
252         this.value = null;
253         updateOperationType(newType);
254     }
255
256     /**
257      * Records a write for associated node.
258      *
259      * @param value
260      */
261     void write(final NormalizedNode<?, ?> value) {
262         updateValue(LogicalOperation.WRITE, value);
263         children.clear();
264     }
265
266     /**
267      * Seal the modification node and prune any children which has not been modified.
268      *
269      * @param schema
270      */
271     void seal(final ModificationApplyOperation schema, final Version version) {
272         clearSnapshot();
273         writtenOriginal = null;
274
275         switch (operation) {
276             case TOUCH:
277                 // A TOUCH node without any children is a no-op
278                 if (children.isEmpty()) {
279                     updateOperationType(LogicalOperation.NONE);
280                 }
281                 break;
282             case WRITE:
283                 // A WRITE can collapse all of its children
284                 if (!children.isEmpty()) {
285                     value = schema.apply(this, getOriginal(), version).get().getData();
286                     children.clear();
287                 }
288
289                 schema.verifyStructure(value, true);
290                 break;
291             default:
292                 break;
293         }
294     }
295
296     private void clearSnapshot() {
297         snapshotCache = null;
298     }
299
300     Optional<TreeNode> getSnapshot() {
301         return snapshotCache;
302     }
303
304     Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
305         snapshotCache = Preconditions.checkNotNull(snapshot);
306         return snapshot;
307     }
308
309     void updateOperationType(final LogicalOperation type) {
310         operation = type;
311         modType = null;
312
313         // Make sure we do not reuse previously-instantiated data-derived metadata
314         writtenOriginal = null;
315         clearSnapshot();
316     }
317
318     @Override
319     public String toString() {
320         return "NodeModification [identifier=" + identifier + ", modificationType="
321                 + operation + ", childModification=" + children + "]";
322     }
323
324     void resolveModificationType(@Nonnull final ModificationType type) {
325         modType = type;
326     }
327
328     /**
329      * Update this node's value and operation type without disturbing any of its child modifications.
330      *
331      * @param type New operation type
332      * @param value New node value
333      */
334     void updateValue(final LogicalOperation type, final NormalizedNode<?, ?> value) {
335         this.value = Preconditions.checkNotNull(value);
336         updateOperationType(type);
337     }
338
339     /**
340      * Return the physical modification done to data. May return null if the
341      * operation has not been applied to the underlying tree. This is different
342      * from the logical operation in that it can actually be a no-op if the
343      * operation has no side-effects (like an empty merge on a container).
344      *
345      * @return Modification type.
346      */
347     ModificationType getModificationType() {
348         return modType;
349     }
350
351     public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
352         return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);
353     }
354
355     void setValidatedNode(final SchemaAwareApplyOperation op, final Optional<TreeNode> current, final TreeNode node) {
356         this.validatedOp = Preconditions.checkNotNull(op);
357         this.validatedCurrent = Preconditions.checkNotNull(current);
358         this.validatedNode = Preconditions.checkNotNull(node);
359     }
360
361     TreeNode getValidatedNode(final SchemaAwareApplyOperation op, final Optional<TreeNode> current) {
362         return op.equals(validatedOp) && current.equals(validatedCurrent) ? validatedNode : null;
363     }
364 }