2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.impl.schema.tree;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Predicate;
13 import com.google.common.base.Verify;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.HashMap;
17 import java.util.Iterator;
18 import java.util.LinkedHashMap;
20 import javax.annotation.Nonnull;
21 import javax.annotation.concurrent.NotThreadSafe;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
23 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
29 * Node Modification Node and Tree
31 * Tree which structurally resembles data tree and captures client modifications
32 * to the data store tree.
34 * This tree is lazily created and populated via {@link #modifyChild(PathArgument)}
35 * and {@link TreeNode} which represents original state as tracked by {@link #getOriginal()}.
38 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
39 static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = new Predicate<ModifiedNode>() {
41 public boolean apply(final @Nonnull ModifiedNode input) {
42 Preconditions.checkNotNull(input);
43 switch (input.getOperation()) {
53 throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation()));
57 private final Map<PathArgument, ModifiedNode> children;
58 private final Optional<TreeNode> original;
59 private final PathArgument identifier;
60 private LogicalOperation operation = LogicalOperation.NONE;
61 private Optional<TreeNode> snapshotCache;
62 private NormalizedNode<?, ?> value;
63 private ModificationType modType;
65 private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final ChildTrackingPolicy childPolicy) {
66 this.identifier = identifier;
67 this.original = original;
69 switch (childPolicy) {
71 children = Collections.emptyMap();
74 children = new LinkedHashMap<>();
77 children = new HashMap<>();
80 throw new IllegalArgumentException("Unsupported child tracking policy " + childPolicy);
85 * Return the value which was written to this node.
87 * @return Currently-written value
89 public NormalizedNode<?, ?> getWrittenValue() {
94 public PathArgument getIdentifier() {
99 Optional<TreeNode> getOriginal() {
104 LogicalOperation getOperation() {
110 * Returns child modification if child was modified
112 * @return Child modification if direct child or it's subtree
117 public Optional<ModifiedNode> getChild(final PathArgument child) {
118 return Optional.<ModifiedNode> fromNullable(children.get(child));
123 * Returns child modification if child was modified, creates {@link ModifiedNode}
124 * for child otherwise.
126 * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
127 * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}
129 * @param child child identifier, may not be null
130 * @param childPolicy child tracking policy for the node we are looking for
131 * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
132 * containing child metadata if child was present in original data.
134 ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ChildTrackingPolicy childPolicy) {
136 if (operation == LogicalOperation.NONE) {
137 updateOperationType(LogicalOperation.TOUCH);
139 final ModifiedNode potential = children.get(child);
140 if (potential != null) {
144 final Optional<TreeNode> currentMetadata;
145 if (original.isPresent()) {
146 final TreeNode orig = original.get();
147 currentMetadata = orig.getChild(child);
149 currentMetadata = Optional.absent();
152 final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childPolicy);
153 children.put(child, newlyCreated);
158 * Returns all recorded direct child modification
160 * @return all recorded direct child modifications
163 Collection<ModifiedNode> getChildren() {
164 return children.values();
168 * Records a delete for associated node.
171 final LogicalOperation newType;
176 // We need to record this delete.
177 newType = LogicalOperation.DELETE;
183 * We are canceling a previous modification. This is a bit tricky,
184 * as the original write may have just introduced the data, or it
185 * may have modified it.
187 * As documented in BUG-2470, a delete of data introduced in this
188 * transaction needs to be turned into a no-op.
190 newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
193 throw new IllegalStateException("Unhandled deletion of node with " + operation);
199 updateOperationType(newType);
203 * Records a write for associated node.
207 void write(final NormalizedNode<?, ?> value) {
209 updateOperationType(LogicalOperation.WRITE);
214 void merge(final NormalizedNode<?, ?> value) {
216 updateOperationType(LogicalOperation.MERGE);
219 * Blind overwrite of any previous data is okay, no matter whether the node
220 * is simple or complex type.
222 * If this is a simple or complex type with unkeyed children, this merge will
223 * be turned into a write operation, overwriting whatever was there before.
225 * If this is a container with keyed children, there are two possibilities:
226 * - if it existed before, this value will never be consulted and the children
227 * will get explicitly merged onto the original data.
228 * - if it did not exist before, this value will be used as a seed write and
229 * children will be merged into it.
230 * In either case we rely on OperationWithModification to manipulate the children
231 * before calling this method, so unlike a write we do not want to clear them.
237 * Seal the modification node and prune any children which has not been
243 // Walk all child nodes and remove any children which have not
245 final Iterator<ModifiedNode> it = children.values().iterator();
246 while (it.hasNext()) {
247 final ModifiedNode child = it.next();
250 if (child.operation == LogicalOperation.NONE) {
255 // A TOUCH node without any children is a no-op
256 if (operation == LogicalOperation.TOUCH && children.isEmpty()) {
257 updateOperationType(LogicalOperation.NONE);
261 private void clearSnapshot() {
262 snapshotCache = null;
265 Optional<TreeNode> getSnapshot() {
266 return snapshotCache;
269 Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
270 snapshotCache = Preconditions.checkNotNull(snapshot);
274 private void updateOperationType(final LogicalOperation type) {
281 public String toString() {
282 return "NodeModification [identifier=" + identifier + ", modificationType="
283 + operation + ", childModification=" + children + "]";
286 void resolveModificationType(@Nonnull final ModificationType type) {
290 @Nonnull ModificationType modificationType() {
291 return Verify.verifyNotNull(modType, "Node %s does not have resolved modification type", this);
295 * Create a node which will reflect the state of this node, except it will behave as newly-written
296 * value. This is useful only for merge validation.
298 * @param value Value associated with the node
299 * @return An isolated node. This node should never reach a datatree.
301 ModifiedNode asNewlyWritten(final NormalizedNode<?, ?> value) {
303 * We are instantiating an "equivalent" of this node. Currently the only callsite does not care
304 * about the actual iteration order, so we do not have to specify the same tracking policy as
305 * we were instantiated with. Since this is the only time we need to know that policy (it affects
306 * only things in constructor), we do not want to retain it (saves some memory on per-instance
309 * We could reconstruct it using two instanceof checks (to undo what the constructor has done),
310 * which would give perfect results. The memory saving would be at most 32 bytes of a short-lived
311 * object, so let's not bother with that.
313 final ModifiedNode ret = new ModifiedNode(getIdentifier(), Optional.<TreeNode>absent(), ChildTrackingPolicy.UNORDERED);
318 public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
319 return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);