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