Prune empty nodes from transaction when it is sealed
[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.HashMap;
14 import java.util.Iterator;
15 import java.util.LinkedHashMap;
16 import java.util.Map;
17 import javax.annotation.Nonnull;
18 import javax.annotation.concurrent.NotThreadSafe;
19 import org.opendaylight.yangtools.concepts.Identifiable;
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 StoreMetadataNode} which represents original state {@link #getOriginal()}.
34  */
35 @NotThreadSafe
36 final class ModifiedNode implements StoreTreeNode<ModifiedNode>, Identifiable<PathArgument>, NodeModification {
37
38     public 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.getType()) {
43             case DELETE:
44             case MERGE:
45             case WRITE:
46                 return true;
47             case SUBTREE_MODIFIED:
48             case UNMODIFIED:
49                 return false;
50             }
51
52             throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getType()));
53         }
54     };
55
56     private final Map<PathArgument, ModifiedNode> children;
57     private final Optional<TreeNode> original;
58     private final PathArgument identifier;
59     private ModificationType modificationType = ModificationType.UNMODIFIED;
60     private Optional<TreeNode> snapshotCache;
61     private NormalizedNode<?, ?> value;
62
63     private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final boolean isOrdered) {
64         this.identifier = identifier;
65         this.original = original;
66
67         if (isOrdered) {
68             children = new LinkedHashMap<>();
69         } else {
70             children = new HashMap<>();
71         }
72     }
73
74     /**
75      *
76      *
77      * @return
78      */
79     public NormalizedNode<?, ?> getWrittenValue() {
80         return value;
81     }
82
83     @Override
84     public PathArgument getIdentifier() {
85         return identifier;
86     }
87
88     /**
89      *
90      * Returns original store metadata
91      * @return original store metadata
92      */
93     @Override
94     public Optional<TreeNode> getOriginal() {
95         return original;
96     }
97
98     /**
99      * Returns modification type
100      *
101      * @return modification type
102      */
103     @Override
104     public ModificationType getType() {
105         return modificationType;
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.<ModifiedNode> fromNullable(children.get(child));
119     }
120
121     /**
122      *
123      * Returns child modification if child was modified, creates {@link org.opendaylight.controller.md.sal.dom.store.impl.tree.data.ModifiedNode}
124      * for child otherwise.
125      *
126      * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
127      * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}
128      *
129      * @param child
130      * @return {@link org.opendaylight.controller.md.sal.dom.store.impl.tree.data.ModifiedNode} for specified child, with {@link #getOriginal()}
131      *         containing child metadata if child was present in original data.
132      */
133     public ModifiedNode modifyChild(final PathArgument child, final boolean isOrdered) {
134         clearSnapshot();
135         if (modificationType == ModificationType.UNMODIFIED) {
136             updateModificationType(ModificationType.SUBTREE_MODIFIED);
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         ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, isOrdered);
152         children.put(child, newlyCreated);
153         return newlyCreated;
154     }
155
156     /**
157      *
158      * Returns all recorded direct child modification
159      *
160      * @return all recorded direct child modifications
161      */
162     @Override
163     public Iterable<ModifiedNode> getChildren() {
164         return children.values();
165     }
166
167     /**
168      *
169      * Records a delete for associated node.
170      *
171      */
172     public void delete() {
173         final ModificationType newType;
174
175         switch (modificationType) {
176         case DELETE:
177         case UNMODIFIED:
178             // We need to record this delete.
179             newType = ModificationType.DELETE;
180             break;
181         case MERGE:
182         case SUBTREE_MODIFIED:
183         case WRITE:
184             /*
185              * We are canceling a previous modification. This is a bit tricky,
186              * as the original write may have just introduced the data, or it
187              * may have modified it.
188              *
189              * As documented in BUG-2470, a delete of data introduced in this
190              * transaction needs to be turned into a no-op.
191              */
192             newType = original.isPresent() ? ModificationType.DELETE : ModificationType.UNMODIFIED;
193             break;
194         default:
195             throw new IllegalStateException("Unhandled deletion of node with " + modificationType);
196         }
197
198         clearSnapshot();
199         children.clear();
200         this.value = null;
201         updateModificationType(newType);
202     }
203
204     /**
205      *
206      * Records a write for associated node.
207      *
208      * @param value
209      */
210     public void write(final NormalizedNode<?, ?> value) {
211         clearSnapshot();
212         updateModificationType(ModificationType.WRITE);
213         children.clear();
214         this.value = value;
215     }
216
217     public void merge(final NormalizedNode<?, ?> data) {
218         clearSnapshot();
219         updateModificationType(ModificationType.MERGE);
220         // FIXME: Probably merge with previous value.
221         this.value = data;
222     }
223
224     /**
225      * Seal the modification node and prune any children which has not been
226      * modified.
227      */
228     void seal() {
229         clearSnapshot();
230
231         // Walk all child nodes and remove any children which have not
232         // been modified.
233         final Iterator<ModifiedNode> it = children.values().iterator();
234         while (it.hasNext()) {
235             final ModifiedNode child = it.next();
236             child.seal();
237
238             if (child.modificationType == ModificationType.UNMODIFIED) {
239                 it.remove();
240             }
241         }
242
243         // A SUBTREE_MODIFIED node without any children is a no-op
244         if (modificationType == ModificationType.SUBTREE_MODIFIED && children.isEmpty()) {
245             updateModificationType(ModificationType.UNMODIFIED);
246         }
247     }
248
249     private void clearSnapshot() {
250         snapshotCache = null;
251     }
252
253     public Optional<TreeNode> storeSnapshot(final Optional<TreeNode> snapshot) {
254         snapshotCache = snapshot;
255         return snapshot;
256     }
257
258     public Optional<Optional<TreeNode>> getSnapshotCache() {
259         return Optional.fromNullable(snapshotCache);
260     }
261
262     private void updateModificationType(final ModificationType type) {
263         modificationType = type;
264         clearSnapshot();
265     }
266
267     @Override
268     public String toString() {
269         return "NodeModification [identifier=" + identifier + ", modificationType="
270                 + modificationType + ", childModification=" + children + "]";
271     }
272
273     public static ModifiedNode createUnmodified(final TreeNode metadataTree, final boolean isOrdered) {
274         return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), isOrdered);
275     }
276 }