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 java.util.Collection;
15 import javax.annotation.Nonnull;
16 import javax.annotation.concurrent.NotThreadSafe;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
27 * Node Modification Node and Tree
29 * Tree which structurally resembles data tree and captures client modifications to the data store tree. This tree is
30 * lazily created and populated via {@link #modifyChild(PathArgument)} and {@link TreeNode} which represents original
31 * state as tracked by {@link #getOriginal()}.
33 * The contract is that the state information exposed here preserves the temporal ordering of whatever modifications
34 * were executed. A child's effects pertain to data node as modified by its ancestors. This means that in order to
35 * reconstruct the effective data node presentation, it is sufficient to perform a depth-first pre-order traversal of
39 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
40 static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = new Predicate<ModifiedNode>() {
42 public boolean apply(@Nonnull final ModifiedNode input) {
43 Preconditions.checkNotNull(input);
44 switch (input.getOperation()) {
54 throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation()));
58 private final Map<PathArgument, ModifiedNode> children;
59 private final Optional<TreeNode> original;
60 private final PathArgument identifier;
61 private LogicalOperation operation = LogicalOperation.NONE;
62 private Optional<TreeNode> snapshotCache;
63 private NormalizedNode<?, ?> value;
64 private ModificationType modType;
66 // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node.
67 private TreeNode writtenOriginal;
69 private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final ChildTrackingPolicy childPolicy) {
70 this.identifier = identifier;
71 this.original = original;
72 this.children = childPolicy.createMap();
76 public PathArgument getIdentifier() {
81 LogicalOperation getOperation() {
86 Optional<TreeNode> getOriginal() {
91 * Return the value which was written to this node. The returned object is only valid for
92 * {@link LogicalOperation#MERGE} and {@link LogicalOperation#WRITE}.
93 * operations. It should only be consulted when this modification is going to end up being
94 * {@link ModificationType#WRITE}.
96 * @return Currently-written value
98 NormalizedNode<?, ?> getWrittenValue() {
104 * Returns child modification if child was modified
106 * @return Child modification if direct child or it's subtree
111 public Optional<ModifiedNode> getChild(final PathArgument child) {
112 return Optional.<ModifiedNode> fromNullable(children.get(child));
115 private Optional<TreeNode> metadataFromSnapshot(@Nonnull final PathArgument child) {
116 return original.isPresent() ? original.get().getChild(child) : Optional.<TreeNode>absent();
119 private Optional<TreeNode> metadataFromData(@Nonnull final PathArgument child, final Version modVersion) {
120 if (writtenOriginal == null) {
121 // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version
122 // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting
124 writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion);
127 return writtenOriginal.getChild(child);
131 * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because
132 * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need
133 * to take the current node's operation into account.
135 * @param child Child we are looking to modify
136 * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
137 * @return Before-image tree node as observed by that child.
139 private Optional<TreeNode> findOriginalMetadata(@Nonnull final PathArgument child, final Version modVersion) {
142 // DELETE implies non-presence
143 return Optional.absent();
147 return metadataFromSnapshot(child);
149 // WRITE implies presence based on written data
150 return metadataFromData(child, modVersion);
153 throw new IllegalStateException("Unhandled node operation " + operation);
158 * Returns child modification if child was modified, creates {@link ModifiedNode}
159 * for child otherwise.
161 * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
162 * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}
164 * @param child child identifier, may not be null
165 * @param childPolicy child tracking policy for the node we are looking for
166 * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
167 * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
168 * containing child metadata if child was present in original data.
170 ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ChildTrackingPolicy childPolicy,
171 @Nonnull final Version modVersion) {
173 if (operation == LogicalOperation.NONE) {
174 updateOperationType(LogicalOperation.TOUCH);
176 final ModifiedNode potential = children.get(child);
177 if (potential != null) {
181 final Optional<TreeNode> currentMetadata = findOriginalMetadata(child, modVersion);
184 final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childPolicy);
185 if (operation == LogicalOperation.MERGE && value != null) {
187 * We are attempting to modify a previously-unmodified part of a MERGE node. If the
188 * value contains this component, we need to materialize it as a MERGE modification.
190 @SuppressWarnings({ "rawtypes", "unchecked" })
191 final Optional<NormalizedNode<?, ?>> childData = ((NormalizedNodeContainer)value).getChild(child);
192 if (childData.isPresent()) {
193 newlyCreated.updateValue(LogicalOperation.MERGE, childData.get());
197 children.put(child, newlyCreated);
202 * Returns all recorded direct child modification
204 * @return all recorded direct child modifications
207 Collection<ModifiedNode> getChildren() {
208 return children.values();
212 * Records a delete for associated node.
215 final LogicalOperation newType;
220 // We need to record this delete.
221 newType = LogicalOperation.DELETE;
224 // In case of merge - delete needs to be recored and must not to be changed into
225 // NONE, because lazy expansion of parent MERGE node would reintroduce it
227 newType = LogicalOperation.DELETE;
232 * We are canceling a previous modification. This is a bit tricky,
233 * as the original write may have just introduced the data, or it
234 * may have modified it.
236 * As documented in BUG-2470, a delete of data introduced in this
237 * transaction needs to be turned into a no-op.
239 newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
242 throw new IllegalStateException("Unhandled deletion of node with " + operation);
248 updateOperationType(newType);
252 * Records a write for associated node.
256 void write(final NormalizedNode<?, ?> value) {
257 updateValue(LogicalOperation.WRITE, value);
262 * Seal the modification node and prune any children which has not been modified.
266 void seal(final ModificationApplyOperation schema, final Version version) {
268 writtenOriginal = null;
272 // A TOUCH node without any children is a no-op
273 if (children.isEmpty()) {
274 updateOperationType(LogicalOperation.NONE);
278 // A WRITE can collapse all of its children
279 if (!children.isEmpty()) {
280 value = schema.apply(this, getOriginal(), version).get().getData();
284 schema.verifyStructure(value, true);
291 private void clearSnapshot() {
292 snapshotCache = null;
295 Optional<TreeNode> getSnapshot() {
296 return snapshotCache;
299 Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
300 snapshotCache = Preconditions.checkNotNull(snapshot);
304 void updateOperationType(final LogicalOperation type) {
308 // Make sure we do not reuse previously-instantiated data-derived metadata
309 writtenOriginal = null;
314 public String toString() {
315 return "NodeModification [identifier=" + identifier + ", modificationType="
316 + operation + ", childModification=" + children + "]";
319 void resolveModificationType(@Nonnull final ModificationType type) {
324 * Update this node's value and operation type without disturbing any of its child modifications.
326 * @param type New operation type
327 * @param value New node value
329 void updateValue(final LogicalOperation type, final NormalizedNode<?, ?> value) {
330 this.value = Preconditions.checkNotNull(value);
331 updateOperationType(type);
335 * Return the physical modification done to data. May return null if the
336 * operation has not been applied to the underlying tree. This is different
337 * from the logical operation in that it can actually be a no-op if the
338 * operation has no side-effects (like an empty merge on a container).
340 * @return Modification type.
342 ModificationType getModificationType() {
346 public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
347 return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);