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