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 // Internal cache for TreeNodes created as part of validation
70 private SchemaAwareApplyOperation validatedOp;
71 private Optional<TreeNode> validatedCurrent;
72 private TreeNode validatedNode;
74 private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final ChildTrackingPolicy childPolicy) {
75 this.identifier = identifier;
76 this.original = original;
77 this.children = childPolicy.createMap();
81 public PathArgument getIdentifier() {
86 LogicalOperation getOperation() {
91 Optional<TreeNode> getOriginal() {
96 * Return the value which was written to this node. The returned object is only valid for
97 * {@link LogicalOperation#MERGE} and {@link LogicalOperation#WRITE}.
98 * operations. It should only be consulted when this modification is going to end up being
99 * {@link ModificationType#WRITE}.
101 * @return Currently-written value
103 NormalizedNode<?, ?> getWrittenValue() {
109 * Returns child modification if child was modified
111 * @return Child modification if direct child or it's subtree
116 public Optional<ModifiedNode> getChild(final PathArgument child) {
117 return Optional.<ModifiedNode> fromNullable(children.get(child));
120 private Optional<TreeNode> metadataFromSnapshot(@Nonnull final PathArgument child) {
121 return original.isPresent() ? original.get().getChild(child) : Optional.<TreeNode>absent();
124 private Optional<TreeNode> metadataFromData(@Nonnull final PathArgument child, final Version modVersion) {
125 if (writtenOriginal == null) {
126 // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version
127 // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting
129 writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion);
132 return writtenOriginal.getChild(child);
136 * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because
137 * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need
138 * to take the current node's operation into account.
140 * @param child Child we are looking to modify
141 * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
142 * @return Before-image tree node as observed by that child.
144 private Optional<TreeNode> findOriginalMetadata(@Nonnull final PathArgument child, final Version modVersion) {
147 // DELETE implies non-presence
148 return Optional.absent();
152 return metadataFromSnapshot(child);
154 // WRITE implies presence based on written data
155 return metadataFromData(child, modVersion);
158 throw new IllegalStateException("Unhandled node operation " + operation);
163 * Returns child modification if child was modified, creates {@link ModifiedNode}
164 * for child otherwise.
166 * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
167 * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}
169 * @param child child identifier, may not be null
170 * @param childPolicy child tracking policy for the node we are looking for
171 * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
172 * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
173 * containing child metadata if child was present in original data.
175 ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ChildTrackingPolicy childPolicy,
176 @Nonnull final Version modVersion) {
178 if (operation == LogicalOperation.NONE) {
179 updateOperationType(LogicalOperation.TOUCH);
181 final ModifiedNode potential = children.get(child);
182 if (potential != null) {
186 final Optional<TreeNode> currentMetadata = findOriginalMetadata(child, modVersion);
189 final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childPolicy);
190 if (operation == LogicalOperation.MERGE && value != null) {
192 * We are attempting to modify a previously-unmodified part of a MERGE node. If the
193 * value contains this component, we need to materialize it as a MERGE modification.
195 @SuppressWarnings({ "rawtypes", "unchecked" })
196 final Optional<NormalizedNode<?, ?>> childData = ((NormalizedNodeContainer)value).getChild(child);
197 if (childData.isPresent()) {
198 newlyCreated.updateValue(LogicalOperation.MERGE, childData.get());
202 children.put(child, newlyCreated);
207 * Returns all recorded direct child modification
209 * @return all recorded direct child modifications
212 Collection<ModifiedNode> getChildren() {
213 return children.values();
217 * Records a delete for associated node.
220 final LogicalOperation newType;
225 // We need to record this delete.
226 newType = LogicalOperation.DELETE;
229 // In case of merge - delete needs to be recored and must not to be changed into
230 // NONE, because lazy expansion of parent MERGE node would reintroduce it
232 newType = LogicalOperation.DELETE;
237 * We are canceling a previous modification. This is a bit tricky,
238 * as the original write may have just introduced the data, or it
239 * may have modified it.
241 * As documented in BUG-2470, a delete of data introduced in this
242 * transaction needs to be turned into a no-op.
244 newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
247 throw new IllegalStateException("Unhandled deletion of node with " + operation);
253 updateOperationType(newType);
257 * Records a write for associated node.
261 void write(final NormalizedNode<?, ?> value) {
262 updateValue(LogicalOperation.WRITE, value);
267 * Seal the modification node and prune any children which has not been modified.
271 void seal(final ModificationApplyOperation schema, final Version version) {
273 writtenOriginal = null;
277 // A TOUCH node without any children is a no-op
278 if (children.isEmpty()) {
279 updateOperationType(LogicalOperation.NONE);
283 // A WRITE can collapse all of its children
284 if (!children.isEmpty()) {
285 value = schema.apply(this, getOriginal(), version).get().getData();
289 schema.verifyStructure(value, true);
296 private void clearSnapshot() {
297 snapshotCache = null;
300 Optional<TreeNode> getSnapshot() {
301 return snapshotCache;
304 Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
305 snapshotCache = Preconditions.checkNotNull(snapshot);
309 void updateOperationType(final LogicalOperation type) {
313 // Make sure we do not reuse previously-instantiated data-derived metadata
314 writtenOriginal = null;
319 public String toString() {
320 return "NodeModification [identifier=" + identifier + ", modificationType="
321 + operation + ", childModification=" + children + "]";
324 void resolveModificationType(@Nonnull final ModificationType type) {
329 * Update this node's value and operation type without disturbing any of its child modifications.
331 * @param type New operation type
332 * @param value New node value
334 void updateValue(final LogicalOperation type, final NormalizedNode<?, ?> value) {
335 this.value = Preconditions.checkNotNull(value);
336 updateOperationType(type);
340 * Return the physical modification done to data. May return null if the
341 * operation has not been applied to the underlying tree. This is different
342 * from the logical operation in that it can actually be a no-op if the
343 * operation has no side-effects (like an empty merge on a container).
345 * @return Modification type.
347 ModificationType getModificationType() {
351 public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
352 return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);
355 void setValidatedNode(final SchemaAwareApplyOperation op, final Optional<TreeNode> current, final TreeNode node) {
356 this.validatedOp = Preconditions.checkNotNull(op);
357 this.validatedCurrent = Preconditions.checkNotNull(current);
358 this.validatedNode = Preconditions.checkNotNull(node);
361 TreeNode getValidatedNode(final SchemaAwareApplyOperation op, final Optional<TreeNode> current) {
362 return op.equals(validatedOp) && current.equals(validatedCurrent) ? validatedNode : null;