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.
30 * Tree which structurally resembles data tree and captures client modifications to the data store tree. This tree is
31 * lazily created and populated via {@link #modifyChild(PathArgument, ModificationApplyOperation, Version)} and
32 * {@link TreeNode} which represents original state as tracked by {@link #getOriginal()}.
35 * The contract is that the state information exposed here preserves the temporal ordering of whatever modifications
36 * were executed. A child's effects pertain to data node as modified by its ancestors. This means that in order to
37 * reconstruct the effective data node presentation, it is sufficient to perform a depth-first pre-order traversal of
41 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
42 static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = input -> {
43 Preconditions.checkNotNull(input);
44 switch (input.getOperation()) {
53 throw new IllegalArgumentException("Unhandled modification type " + 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 // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node.
66 private TreeNode writtenOriginal;
68 // Internal cache for TreeNodes created as part of validation
69 private SchemaAwareApplyOperation validatedOp;
70 private Optional<TreeNode> validatedCurrent;
71 private TreeNode validatedNode;
73 private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original,
74 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() {
108 * Returns child modification if child was modified.
110 * @return Child modification if direct child or it's subtree was modified.
113 public Optional<ModifiedNode> getChild(final PathArgument child) {
114 return Optional.fromNullable(children.get(child));
117 private Optional<TreeNode> metadataFromSnapshot(@Nonnull final PathArgument child) {
118 return original.isPresent() ? original.get().getChild(child) : Optional.absent();
121 private Optional<TreeNode> metadataFromData(@Nonnull final PathArgument child, final Version modVersion) {
122 if (writtenOriginal == null) {
123 // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version
124 // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting
126 writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion);
129 return writtenOriginal.getChild(child);
133 * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because
134 * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need
135 * to take the current node's operation into account.
137 * @param child Child we are looking to modify
138 * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
139 * @return Before-image tree node as observed by that child.
141 private Optional<TreeNode> findOriginalMetadata(@Nonnull final PathArgument child, final Version modVersion) {
144 // DELETE implies non-presence
145 return Optional.absent();
149 return metadataFromSnapshot(child);
151 // WRITE implies presence based on written data
152 return metadataFromData(child, modVersion);
154 throw new IllegalStateException("Unhandled node operation " + operation);
159 * Returns child modification if child was modified, creates {@link ModifiedNode}
160 * for child otherwise. If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
161 * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}.
163 * @param child child identifier, may not be null
164 * @param childOper Child operation
165 * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
166 * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
167 * containing child metadata if child was present in original data.
169 ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ModificationApplyOperation childOper,
170 @Nonnull final Version modVersion) {
172 if (operation == LogicalOperation.NONE) {
173 updateOperationType(LogicalOperation.TOUCH);
175 final ModifiedNode potential = children.get(child);
176 if (potential != null) {
180 final Optional<TreeNode> currentMetadata = findOriginalMetadata(child, modVersion);
183 final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childOper.getChildPolicy());
184 if (operation == LogicalOperation.MERGE && value != null) {
186 * We are attempting to modify a previously-unmodified part of a MERGE node. If the
187 * value contains this component, we need to materialize it as a MERGE modification.
189 @SuppressWarnings({ "rawtypes", "unchecked" })
190 final Optional<NormalizedNode<?, ?>> childData = ((NormalizedNodeContainer)value).getChild(child);
191 if (childData.isPresent()) {
192 childOper.mergeIntoModifiedNode(newlyCreated, childData.get(), modVersion);
196 children.put(child, newlyCreated);
201 * Returns all recorded direct child modifications.
203 * @return all recorded direct child modifications
206 Collection<ModifiedNode> getChildren() {
207 return children.values();
211 * Records a delete for associated node.
214 final LogicalOperation newType;
219 // We need to record this delete.
220 newType = LogicalOperation.DELETE;
223 // In case of merge - delete needs to be recored and must not to be changed into NONE, because lazy
224 // expansion of parent MERGE node would reintroduce it again.
225 newType = LogicalOperation.DELETE;
230 * We are canceling a previous modification. This is a bit tricky, as the original write may have just
231 * introduced the data, or it may have modified it.
233 * As documented in BUG-2470, a delete of data introduced in this transaction needs to be turned into
236 newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
239 throw new IllegalStateException("Unhandled deletion of node with " + operation);
245 updateOperationType(newType);
249 * Records a write for associated node.
251 * @param value new value
253 void write(final NormalizedNode<?, ?> value) {
254 updateValue(LogicalOperation.WRITE, value);
259 * Seal the modification node and prune any children which has not been modified.
261 * @param schema associated apply operation
262 * @param version target version
264 void seal(final ModificationApplyOperation schema, final Version version) {
266 writtenOriginal = null;
270 // A TOUCH node without any children is a no-op
271 if (children.isEmpty()) {
272 updateOperationType(LogicalOperation.NONE);
276 // A WRITE can collapse all of its children
277 if (!children.isEmpty()) {
278 value = schema.apply(this, getOriginal(), version).get().getData();
282 schema.verifyStructure(value, true);
289 private void clearSnapshot() {
290 snapshotCache = null;
293 Optional<TreeNode> getSnapshot() {
294 return snapshotCache;
297 Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
298 snapshotCache = Preconditions.checkNotNull(snapshot);
302 void updateOperationType(final LogicalOperation type) {
306 // Make sure we do not reuse previously-instantiated data-derived metadata
307 writtenOriginal = null;
312 public String toString() {
313 return "NodeModification [identifier=" + identifier + ", modificationType="
314 + operation + ", childModification=" + children + "]";
317 void resolveModificationType(@Nonnull final ModificationType type) {
322 * Update this node's value and operation type without disturbing any of its child modifications.
324 * @param type New operation type
325 * @param value New node value
327 void updateValue(final LogicalOperation type, final NormalizedNode<?, ?> value) {
328 this.value = Preconditions.checkNotNull(value);
329 updateOperationType(type);
333 * Return the physical modification done to data. May return null if the
334 * operation has not been applied to the underlying tree. This is different
335 * from the logical operation in that it can actually be a no-op if the
336 * operation has no side-effects (like an empty merge on a container).
338 * @return Modification type.
340 ModificationType getModificationType() {
344 public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
345 return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);
348 void setValidatedNode(final SchemaAwareApplyOperation op, final Optional<TreeNode> current, final TreeNode node) {
349 this.validatedOp = Preconditions.checkNotNull(op);
350 this.validatedCurrent = Preconditions.checkNotNull(current);
351 this.validatedNode = Preconditions.checkNotNull(node);
354 TreeNode getValidatedNode(final SchemaAwareApplyOperation op, final Optional<TreeNode> current) {
355 return op.equals(validatedOp) && current.equals(validatedCurrent) ? validatedNode : null;