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.NormalizedNodes;
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
30 * to the data store tree.
32 * This tree is lazily created and populated via {@link #modifyChild(PathArgument)}
33 * and {@link TreeNode} which represents original state as tracked by {@link #getOriginal()}.
36 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
37 static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = new Predicate<ModifiedNode>() {
39 public boolean apply(@Nonnull final ModifiedNode input) {
40 Preconditions.checkNotNull(input);
41 switch (input.getOperation()) {
51 throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation()));
55 private final Map<PathArgument, ModifiedNode> children;
56 private final Optional<TreeNode> original;
57 private final PathArgument identifier;
58 private LogicalOperation operation = LogicalOperation.NONE;
59 private Optional<TreeNode> snapshotCache;
60 private NormalizedNode<?, ?> value;
61 private ModificationType modType;
63 // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node.
64 private TreeNode writtenOriginal;
66 private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final ChildTrackingPolicy childPolicy) {
67 this.identifier = identifier;
68 this.original = original;
69 this.children = childPolicy.createMap();
73 * Return the value which was written to this node.
75 * @return Currently-written value
77 public NormalizedNode<?, ?> getWrittenValue() {
82 public PathArgument getIdentifier() {
87 Optional<TreeNode> getOriginal() {
92 LogicalOperation getOperation() {
98 * Returns child modification if child was modified
100 * @return Child modification if direct child or it's subtree
105 public Optional<ModifiedNode> getChild(final PathArgument child) {
106 return Optional.<ModifiedNode> fromNullable(children.get(child));
109 private Optional<TreeNode> metadataFromSnapshot(@Nonnull final PathArgument child) {
110 return original.isPresent() ? original.get().getChild(child) : Optional.<TreeNode>absent();
113 private Optional<TreeNode> metadataFromData(@Nonnull final PathArgument child, final Version modVersion) {
114 if (writtenOriginal == null) {
115 // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version
116 // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting
118 writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion);
121 return writtenOriginal.getChild(child);
125 * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because
126 * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need
127 * to take the current node's operation into account.
129 * @param child Child we are looking to modify
130 * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
131 * @return Before-image tree node as observed by that child.
133 private Optional<TreeNode> findOriginalMetadata(@Nonnull final PathArgument child, final Version modVersion) {
136 // DELETE implies non-presence
137 return Optional.absent();
140 return metadataFromSnapshot(child);
142 // MERGE is half-way between TOUCH and WRITE. If the child exists in data, it behaves as a WRITE, otherwise
143 // it behaves as a TOUCH
144 if (NormalizedNodes.findNode(value, child).isPresent()) {
145 return metadataFromData(child, modVersion);
147 return metadataFromSnapshot(child);
150 // WRITE implies presence based on written data
151 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.
162 * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
163 * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}
165 * @param child child identifier, may not be null
166 * @param childPolicy child tracking policy for the node we are looking for
167 * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
168 * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
169 * containing child metadata if child was present in original data.
171 ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ChildTrackingPolicy childPolicy,
172 @Nonnull final Version modVersion) {
174 if (operation == LogicalOperation.NONE) {
175 updateOperationType(LogicalOperation.TOUCH);
177 final ModifiedNode potential = children.get(child);
178 if (potential != null) {
182 final Optional<TreeNode> currentMetadata = findOriginalMetadata(child, modVersion);
185 final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childPolicy);
186 children.put(child, newlyCreated);
191 * Returns all recorded direct child modification
193 * @return all recorded direct child modifications
196 Collection<ModifiedNode> getChildren() {
197 return children.values();
201 * Records a delete for associated node.
204 final LogicalOperation newType;
209 // We need to record this delete.
210 newType = LogicalOperation.DELETE;
216 * We are canceling a previous modification. This is a bit tricky,
217 * as the original write may have just introduced the data, or it
218 * may have modified it.
220 * As documented in BUG-2470, a delete of data introduced in this
221 * transaction needs to be turned into a no-op.
223 newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
226 throw new IllegalStateException("Unhandled deletion of node with " + operation);
232 updateOperationType(newType);
236 * Records a write for associated node.
240 void write(final NormalizedNode<?, ?> value) {
245 // Promote the node to write, but do not lose children
246 void pushWrite(final NormalizedNode<?, ?> value) {
248 updateOperationType(LogicalOperation.WRITE);
252 void merge(final NormalizedNode<?, ?> value) {
254 updateOperationType(LogicalOperation.MERGE);
257 * Blind overwrite of any previous data is okay, no matter whether the node
258 * is simple or complex type.
260 * If this is a simple or complex type with unkeyed children, this merge will
261 * be turned into a write operation, overwriting whatever was there before.
263 * If this is a container with keyed children, there are two possibilities:
264 * - if it existed before, this value will never be consulted and the children
265 * will get explicitly merged onto the original data.
266 * - if it did not exist before, this value will be used as a seed write and
267 * children will be merged into it.
268 * In either case we rely on OperationWithModification to manipulate the children
269 * before calling this method, so unlike a write we do not want to clear them.
275 * Seal the modification node and prune any children which has not been modified.
279 void seal(final ModificationApplyOperation schema, final Version version) {
281 writtenOriginal = null;
285 // A TOUCH node without any children is a no-op
286 if (children.isEmpty()) {
287 updateOperationType(LogicalOperation.NONE);
291 // A WRITE can collapse all of its children
292 if (!children.isEmpty()) {
293 value = schema.apply(this, getOriginal(), version).get().getData();
297 schema.verifyStructure(value, true);
304 private void clearSnapshot() {
305 snapshotCache = null;
308 Optional<TreeNode> getSnapshot() {
309 return snapshotCache;
312 Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
313 snapshotCache = Preconditions.checkNotNull(snapshot);
317 private void updateOperationType(final LogicalOperation type) {
321 // Make sure we do not reuse previously-instantiated data-derived metadata
322 writtenOriginal = null;
327 public String toString() {
328 return "NodeModification [identifier=" + identifier + ", modificationType="
329 + operation + ", childModification=" + children + "]";
332 void resolveModificationType(@Nonnull final ModificationType type) {
337 * Return the physical modification done to data. May return null if the
338 * operation has not been applied to the underlying tree. This is different
339 * from the logical operation in that it can actually be a no-op if the
340 * operation has no side-effects (like an empty merge on a container).
342 * @return Modification type.
344 ModificationType getModificationType() {
349 * Create a node which will reflect the state of this node, except it will behave as newly-written
350 * value. This is useful only for merge validation.
352 * @param value Value associated with the node
353 * @return An isolated node. This node should never reach a datatree.
355 ModifiedNode asNewlyWritten(final NormalizedNode<?, ?> value) {
357 * We are instantiating an "equivalent" of this node. Currently the only callsite does not care
358 * about the actual iteration order, so we do not have to specify the same tracking policy as
359 * we were instantiated with. Since this is the only time we need to know that policy (it affects
360 * only things in constructor), we do not want to retain it (saves some memory on per-instance
363 * We could reconstruct it using two instanceof checks (to undo what the constructor has done),
364 * which would give perfect results. The memory saving would be at most 32 bytes of a short-lived
365 * object, so let's not bother with that.
367 final ModifiedNode ret = new ModifiedNode(getIdentifier(), Optional.<TreeNode>absent(), ChildTrackingPolicy.UNORDERED);
372 public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
373 return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);