Merge "BUG-2876: prune empty subtree modifications"
[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.Collections;
15 import java.util.HashMap;
16 import java.util.Iterator;
17 import java.util.LinkedHashMap;
18 import java.util.Map;
19 import javax.annotation.Nonnull;
20 import javax.annotation.concurrent.NotThreadSafe;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
26
27 /**
28  * Node Modification Node and Tree
29  *
30  * Tree which structurally resembles data tree and captures client modifications
31  * to the data store tree.
32  *
33  * This tree is lazily created and populated via {@link #modifyChild(PathArgument)}
34  * and {@link TreeNode} which represents original state as tracked by {@link #getOriginal()}.
35  */
36 @NotThreadSafe
37 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
38     static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = new Predicate<ModifiedNode>() {
39         @Override
40         public boolean apply(final @Nonnull ModifiedNode input) {
41             Preconditions.checkNotNull(input);
42             switch (input.getOperation()) {
43             case DELETE:
44             case MERGE:
45             case WRITE:
46                 return true;
47             case TOUCH:
48             case NONE:
49                 return false;
50             }
51
52             throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation()));
53         }
54     };
55
56     private final Map<PathArgument, ModifiedNode> children;
57     private final Optional<TreeNode> original;
58     private final PathArgument identifier;
59     private LogicalOperation operation = LogicalOperation.NONE;
60     private Optional<TreeNode> snapshotCache;
61     private NormalizedNode<?, ?> value;
62     private ModificationType modType;
63
64     private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final ChildTrackingPolicy childPolicy) {
65         this.identifier = identifier;
66         this.original = original;
67
68         switch (childPolicy) {
69         case NONE:
70             children = Collections.emptyMap();
71             break;
72         case ORDERED:
73             children = new LinkedHashMap<>();
74             break;
75         case UNORDERED:
76             children = new HashMap<>();
77             break;
78         default:
79             throw new IllegalArgumentException("Unsupported child tracking policy " + childPolicy);
80         }
81     }
82
83     /**
84      * Return the value which was written to this node.
85      *
86      * @return Currently-written value
87      */
88     public NormalizedNode<?, ?> getWrittenValue() {
89         return value;
90     }
91
92     @Override
93     public PathArgument getIdentifier() {
94         return identifier;
95     }
96
97     @Override
98     Optional<TreeNode> getOriginal() {
99         return original;
100     }
101
102     @Override
103     LogicalOperation getOperation() {
104         return operation;
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     /**
121      *
122      * Returns child modification if child was modified, creates {@link ModifiedNode}
123      * for child otherwise.
124      *
125      * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
126      * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}
127      *
128      * @param child child identifier, may not be null
129      * @param childPolicy child tracking policy for the node we are looking for
130      * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
131      *         containing child metadata if child was present in original data.
132      */
133     ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ChildTrackingPolicy childPolicy) {
134         clearSnapshot();
135         if (operation == LogicalOperation.NONE) {
136             updateOperationType(LogicalOperation.TOUCH);
137         }
138         final ModifiedNode potential = children.get(child);
139         if (potential != null) {
140             return potential;
141         }
142
143         final Optional<TreeNode> currentMetadata;
144         if (original.isPresent()) {
145             final TreeNode orig = original.get();
146             currentMetadata = orig.getChild(child);
147         } else {
148             currentMetadata = Optional.absent();
149         }
150
151         final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childPolicy);
152         children.put(child, newlyCreated);
153         return newlyCreated;
154     }
155
156     /**
157      * Returns all recorded direct child modification
158      *
159      * @return all recorded direct child modifications
160      */
161     @Override
162     Collection<ModifiedNode> getChildren() {
163         return children.values();
164     }
165
166     /**
167      * Records a delete for associated node.
168      */
169     void delete() {
170         final LogicalOperation newType;
171
172         switch (operation) {
173         case DELETE:
174         case NONE:
175             // We need to record this delete.
176             newType = LogicalOperation.DELETE;
177             break;
178         case MERGE:
179         case TOUCH:
180         case WRITE:
181             /*
182              * We are canceling a previous modification. This is a bit tricky,
183              * as the original write may have just introduced the data, or it
184              * may have modified it.
185              *
186              * As documented in BUG-2470, a delete of data introduced in this
187              * transaction needs to be turned into a no-op.
188              */
189             newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
190             break;
191         default:
192             throw new IllegalStateException("Unhandled deletion of node with " + operation);
193         }
194
195         clearSnapshot();
196         children.clear();
197         this.value = null;
198         updateOperationType(newType);
199     }
200
201     /**
202      * Records a write for associated node.
203      *
204      * @param value
205      */
206     void write(final NormalizedNode<?, ?> value) {
207         clearSnapshot();
208         updateOperationType(LogicalOperation.WRITE);
209         children.clear();
210         this.value = value;
211     }
212
213     void merge(final NormalizedNode<?, ?> value) {
214         clearSnapshot();
215         updateOperationType(LogicalOperation.MERGE);
216
217         /*
218          * Blind overwrite of any previous data is okay, no matter whether the node
219          * is simple or complex type.
220          *
221          * If this is a simple or complex type with unkeyed children, this merge will
222          * be turned into a write operation, overwriting whatever was there before.
223          *
224          * If this is a container with keyed children, there are two possibilities:
225          * - if it existed before, this value will never be consulted and the children
226          *   will get explicitly merged onto the original data.
227          * - if it did not exist before, this value will be used as a seed write and
228          *   children will be merged into it.
229          * In either case we rely on OperationWithModification to manipulate the children
230          * before calling this method, so unlike a write we do not want to clear them.
231          */
232         this.value = value;
233     }
234
235     /**
236      * Seal the modification node and prune any children which has not been
237      * modified.
238      */
239     void seal() {
240         clearSnapshot();
241
242         // Walk all child nodes and remove any children which have not
243         // been modified.
244         final Iterator<ModifiedNode> it = children.values().iterator();
245         while (it.hasNext()) {
246             final ModifiedNode child = it.next();
247             child.seal();
248
249             if (child.operation == LogicalOperation.NONE) {
250                 it.remove();
251             }
252         }
253
254         // A TOUCH node without any children is a no-op
255         if (operation == LogicalOperation.TOUCH && children.isEmpty()) {
256             updateOperationType(LogicalOperation.NONE);
257         }
258     }
259
260     private void clearSnapshot() {
261         snapshotCache = null;
262     }
263
264     Optional<TreeNode> getSnapshot() {
265         return snapshotCache;
266     }
267
268     Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
269         snapshotCache = Preconditions.checkNotNull(snapshot);
270         return snapshot;
271     }
272
273     private void updateOperationType(final LogicalOperation type) {
274         operation = type;
275         modType = null;
276         clearSnapshot();
277     }
278
279     @Override
280     public String toString() {
281         return "NodeModification [identifier=" + identifier + ", modificationType="
282                 + operation + ", childModification=" + children + "]";
283     }
284
285     void resolveModificationType(@Nonnull final ModificationType type) {
286         modType = type;
287     }
288
289     /**
290      * Return the physical modification done to data. May return null if the
291      * operation has not been applied to the underlying tree. This is different
292      * from the logical operation in that it can actually be a no-op if the
293      * operation has no side-effects (like an empty merge on a container).
294      *
295      * @return Modification type.
296      */
297     ModificationType getModificationType() {
298         return modType;
299     }
300
301     /**
302      * Create a node which will reflect the state of this node, except it will behave as newly-written
303      * value. This is useful only for merge validation.
304      *
305      * @param value Value associated with the node
306      * @return An isolated node. This node should never reach a datatree.
307      */
308     ModifiedNode asNewlyWritten(final NormalizedNode<?, ?> value) {
309         /*
310          * We are instantiating an "equivalent" of this node. Currently the only callsite does not care
311          * about the actual iteration order, so we do not have to specify the same tracking policy as
312          * we were instantiated with. Since this is the only time we need to know that policy (it affects
313          * only things in constructor), we do not want to retain it (saves some memory on per-instance
314          * basis).
315          *
316          * We could reconstruct it using two instanceof checks (to undo what the constructor has done),
317          * which would give perfect results. The memory saving would be at most 32 bytes of a short-lived
318          * object, so let's not bother with that.
319          */
320         final ModifiedNode ret = new ModifiedNode(getIdentifier(), Optional.<TreeNode>absent(), ChildTrackingPolicy.UNORDERED);
321         ret.write(value);
322         return ret;
323     }
324
325     public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
326         return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);
327     }
328 }