Merge "Bug 868: Removed Binding to Composite Node codecs."
[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.HashMap;
15 import java.util.Iterator;
16 import java.util.LinkedHashMap;
17 import java.util.Map;
18 import javax.annotation.Nonnull;
19 import javax.annotation.concurrent.NotThreadSafe;
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.tree.ModificationType;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
25
26 /**
27  * Node Modification Node and Tree
28  *
29  * Tree which structurally resembles data tree and captures client modifications
30  * to the data store tree.
31  *
32  * This tree is lazily created and populated via {@link #modifyChild(PathArgument)}
33  * and {@link TreeNode} which represents original state as tracked by {@link #getOriginal()}.
34  */
35 @NotThreadSafe
36 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
37     static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = new Predicate<ModifiedNode>() {
38         @Override
39         public boolean apply(final @Nonnull ModifiedNode input) {
40             Preconditions.checkNotNull(input);
41             switch (input.getOperation()) {
42             case DELETE:
43             case MERGE:
44             case WRITE:
45                 return true;
46             case TOUCH:
47             case NONE:
48                 return false;
49             }
50
51             throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation()));
52         }
53     };
54
55     private final Map<PathArgument, ModifiedNode> children;
56     private final Optional<TreeNode> original;
57     private final PathArgument identifier;
58     private LogicalOperation operation = LogicalOperation.NONE;
59     private Optional<TreeNode> snapshotCache;
60     private NormalizedNode<?, ?> value;
61
62     private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final boolean isOrdered) {
63         this.identifier = identifier;
64         this.original = original;
65
66         if (isOrdered) {
67             children = new LinkedHashMap<>();
68         } else {
69             children = new HashMap<>();
70         }
71     }
72
73     /**
74      * Return the value which was written to this node.
75      *
76      * @return Currently-written value
77      */
78     public NormalizedNode<?, ?> getWrittenValue() {
79         return value;
80     }
81
82     @Override
83     public PathArgument getIdentifier() {
84         return identifier;
85     }
86
87     @Override
88     Optional<TreeNode> getOriginal() {
89         return original;
90     }
91
92
93     @Override
94     LogicalOperation getOperation() {
95         return operation;
96     }
97
98     /**
99      *
100      * Returns child modification if child was modified
101      *
102      * @return Child modification if direct child or it's subtree
103      *  was modified.
104      *
105      */
106     @Override
107     public Optional<ModifiedNode> getChild(final PathArgument child) {
108         return Optional.<ModifiedNode> fromNullable(children.get(child));
109     }
110
111     /**
112      *
113      * Returns child modification if child was modified, creates {@link ModifiedNode}
114      * for child otherwise.
115      *
116      * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
117      * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}
118      *
119      * @param child
120      * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
121      *         containing child metadata if child was present in original data.
122      */
123     ModifiedNode modifyChild(final PathArgument child, final boolean isOrdered) {
124         clearSnapshot();
125         if (operation == LogicalOperation.NONE) {
126             updateModificationType(LogicalOperation.TOUCH);
127         }
128         final ModifiedNode potential = children.get(child);
129         if (potential != null) {
130             return potential;
131         }
132
133         final Optional<TreeNode> currentMetadata;
134         if (original.isPresent()) {
135             final TreeNode orig = original.get();
136             currentMetadata = orig.getChild(child);
137         } else {
138             currentMetadata = Optional.absent();
139         }
140
141         final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, isOrdered);
142         children.put(child, newlyCreated);
143         return newlyCreated;
144     }
145
146     /**
147      * Returns all recorded direct child modification
148      *
149      * @return all recorded direct child modifications
150      */
151     @Override
152     Collection<ModifiedNode> getChildren() {
153         return children.values();
154     }
155
156     /**
157      * Records a delete for associated node.
158      */
159     void delete() {
160         final LogicalOperation newType;
161
162         switch (operation) {
163         case DELETE:
164         case NONE:
165             // We need to record this delete.
166             newType = LogicalOperation.DELETE;
167             break;
168         case MERGE:
169         case TOUCH:
170         case WRITE:
171             /*
172              * We are canceling a previous modification. This is a bit tricky,
173              * as the original write may have just introduced the data, or it
174              * may have modified it.
175              *
176              * As documented in BUG-2470, a delete of data introduced in this
177              * transaction needs to be turned into a no-op.
178              */
179             newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
180             break;
181         default:
182             throw new IllegalStateException("Unhandled deletion of node with " + operation);
183         }
184
185         clearSnapshot();
186         children.clear();
187         this.value = null;
188         updateModificationType(newType);
189     }
190
191     /**
192      * Records a write for associated node.
193      *
194      * @param value
195      */
196     void write(final NormalizedNode<?, ?> value) {
197         clearSnapshot();
198         updateModificationType(LogicalOperation.WRITE);
199         children.clear();
200         this.value = value;
201     }
202
203     void merge(final NormalizedNode<?, ?> value) {
204         clearSnapshot();
205         updateModificationType(LogicalOperation.MERGE);
206
207         /*
208          * Blind overwrite of any previous data is okay, no matter whether the node
209          * is simple or complex type.
210          *
211          * If this is a simple or complex type with unkeyed children, this merge will
212          * be turned into a write operation, overwriting whatever was there before.
213          *
214          * If this is a container with keyed children, there are two possibilities:
215          * - if it existed before, this value will never be consulted and the children
216          *   will get explicitly merged onto the original data.
217          * - if it did not exist before, this value will be used as a seed write and
218          *   children will be merged into it.
219          * In either case we rely on OperationWithModification to manipulate the children
220          * before calling this method, so unlike a write we do not want to clear them.
221          */
222         this.value = value;
223     }
224
225     /**
226      * Seal the modification node and prune any children which has not been
227      * modified.
228      */
229     void seal() {
230         clearSnapshot();
231
232         // Walk all child nodes and remove any children which have not
233         // been modified.
234         final Iterator<ModifiedNode> it = children.values().iterator();
235         while (it.hasNext()) {
236             final ModifiedNode child = it.next();
237             child.seal();
238
239             if (child.operation == LogicalOperation.NONE) {
240                 it.remove();
241             }
242         }
243
244         // A TOUCH node without any children is a no-op
245         if (operation == LogicalOperation.TOUCH && children.isEmpty()) {
246             updateModificationType(LogicalOperation.NONE);
247         }
248     }
249
250     private void clearSnapshot() {
251         snapshotCache = null;
252     }
253
254     Optional<TreeNode> getSnapshot() {
255         return snapshotCache;
256     }
257
258     Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
259         snapshotCache = Preconditions.checkNotNull(snapshot);
260         return snapshot;
261     }
262
263     private void updateModificationType(final LogicalOperation type) {
264         operation = type;
265         clearSnapshot();
266     }
267
268     @Override
269     public String toString() {
270         return "NodeModification [identifier=" + identifier + ", modificationType="
271                 + operation + ", childModification=" + children + "]";
272     }
273
274     /**
275      * Create a node which will reflect the state of this node, except it will behave as newly-written
276      * value. This is useful only for merge validation.
277      *
278      * @param value Value associated with the node
279      * @return An isolated node. This node should never reach a datatree.
280      */
281     ModifiedNode asNewlyWritten(final NormalizedNode<?, ?> value) {
282         final ModifiedNode ret = new ModifiedNode(getIdentifier(), Optional.<TreeNode>absent(), false);
283         ret.write(value);
284         return ret;
285     }
286
287     public static ModifiedNode createUnmodified(final TreeNode metadataTree, final boolean isOrdered) {
288         return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), isOrdered);
289     }
290 }