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