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 static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.util.Collection;
18 import java.util.Optional;
19 import java.util.function.Predicate;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.eclipse.jdt.annotation.Nullable;
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.NormalizedNodeContainer;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
32 * Node Modification Node and Tree.
35 * Tree which structurally resembles data tree and captures client modifications to the data store tree. This tree is
36 * lazily created and populated via {@link #modifyChild(PathArgument, ModificationApplyOperation, Version)} and
37 * {@link TreeNode} which represents original state as tracked by {@link #getOriginal()}.
40 * The contract is that the state information exposed here preserves the temporal ordering of whatever modifications
41 * were executed. A child's effects pertain to data node as modified by its ancestors. This means that in order to
42 * reconstruct the effective data node presentation, it is sufficient to perform a depth-first pre-order traversal of
45 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
46 static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = input -> {
47 requireNonNull(input);
48 switch (input.getOperation()) {
57 throw new IllegalArgumentException("Unhandled modification type " + input.getOperation());
61 private final Map<PathArgument, ModifiedNode> children;
62 private final Optional<? extends TreeNode> original;
63 private final PathArgument identifier;
64 private LogicalOperation operation = LogicalOperation.NONE;
65 private Optional<TreeNode> snapshotCache;
66 private NormalizedNode<?, ?> value;
67 private ModificationType modType;
69 // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node.
70 private TreeNode writtenOriginal;
72 // Internal cache for TreeNodes created as part of validation
73 private ModificationApplyOperation validatedOp;
74 private Optional<? extends TreeNode> validatedCurrent;
75 private Optional<? extends TreeNode> validatedNode;
77 private ModifiedNode(final PathArgument identifier, final Optional<? extends TreeNode> original,
78 final ChildTrackingPolicy childPolicy) {
79 this.identifier = identifier;
80 this.original = original;
81 this.children = childPolicy.createMap();
85 public PathArgument getIdentifier() {
90 LogicalOperation getOperation() {
95 Optional<? extends TreeNode> getOriginal() {
100 * Return the value which was written to this node. The returned object is only valid for
101 * {@link LogicalOperation#MERGE} and {@link LogicalOperation#WRITE}.
102 * operations. It should only be consulted when this modification is going to end up being
103 * {@link ModificationType#WRITE}.
105 * @return Currently-written value
107 @NonNull NormalizedNode<?, ?> getWrittenValue() {
108 return verifyNotNull(value);
112 * Returns child modification if child was modified.
114 * @return Child modification if direct child or it's subtree was modified.
117 public ModifiedNode childByArg(final PathArgument arg) {
118 return children.get(arg);
121 private Optional<? extends TreeNode> metadataFromSnapshot(final @NonNull PathArgument child) {
122 return original.isPresent() ? original.get().findChildByArg(child) : Optional.empty();
125 private Optional<? extends TreeNode> metadataFromData(final @NonNull PathArgument child, final Version modVersion) {
126 if (writtenOriginal == null) {
127 // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version
128 // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting
130 writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion);
133 return writtenOriginal.findChildByArg(child);
137 * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because
138 * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need
139 * to take the current node's operation into account.
141 * @param child Child we are looking to modify
142 * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
143 * @return Before-image tree node as observed by that child.
145 private Optional<? extends TreeNode> findOriginalMetadata(final @NonNull PathArgument child,
146 final Version modVersion) {
149 // DELETE implies non-presence
150 return Optional.empty();
154 return metadataFromSnapshot(child);
156 // WRITE implies presence based on written data
157 return metadataFromData(child, modVersion);
159 throw new IllegalStateException("Unhandled node operation " + operation);
164 * Returns child modification if child was modified, creates {@link ModifiedNode}
165 * for child otherwise. If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
166 * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}.
168 * @param child child identifier, may not be null
169 * @param childOper Child operation
170 * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
171 * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
172 * containing child metadata if child was present in original data.
174 ModifiedNode modifyChild(final @NonNull PathArgument child, final @NonNull ModificationApplyOperation childOper,
175 final @NonNull Version modVersion) {
177 if (operation == LogicalOperation.NONE) {
178 updateOperationType(LogicalOperation.TOUCH);
180 final ModifiedNode potential = children.get(child);
181 if (potential != null) {
185 final Optional<? extends TreeNode> currentMetadata = findOriginalMetadata(child, modVersion);
186 final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childOper.getChildPolicy());
187 if (operation == LogicalOperation.MERGE && value != null) {
189 * We are attempting to modify a previously-unmodified part of a MERGE node. If the
190 * value contains this component, we need to materialize it as a MERGE modification.
192 @SuppressWarnings({ "rawtypes", "unchecked" })
193 final Optional<NormalizedNode<?, ?>> childData = ((NormalizedNodeContainer)value).getChild(child);
194 if (childData.isPresent()) {
195 childOper.mergeIntoModifiedNode(newlyCreated, childData.get(), modVersion);
199 children.put(child, newlyCreated);
204 * Returns all recorded direct child modifications.
206 * @return all recorded direct child modifications
209 Collection<ModifiedNode> getChildren() {
210 return children.values();
214 * Records a delete for associated node.
217 final LogicalOperation newType;
222 // We need to record this delete.
223 newType = LogicalOperation.DELETE;
226 // In case of merge - delete needs to be recored and must not to be changed into NONE, because lazy
227 // expansion of parent MERGE node would reintroduce it again.
228 newType = LogicalOperation.DELETE;
233 * We are canceling a previous modification. This is a bit tricky, as the original write may have just
234 * introduced the data, or it may have modified it.
236 * As documented in BUG-2470, a delete of data introduced in this transaction needs to be turned into
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.
254 * @param newValue new value
256 void write(final NormalizedNode<?, ?> newValue) {
257 updateValue(LogicalOperation.WRITE, newValue);
262 * Seal the modification node and prune any children which has not been modified.
264 * @param schema associated apply operation
265 * @param version target version
267 void seal(final ModificationApplyOperation schema, final Version version) {
269 writtenOriginal = null;
273 // A TOUCH node without any children is a no-op
274 if (children.isEmpty()) {
275 updateOperationType(LogicalOperation.NONE);
279 // A WRITE can collapse all of its children
280 if (!children.isEmpty()) {
281 value = schema.apply(this, getOriginal(), version).map(TreeNode::getData).orElse(null);
286 // The write has ended up being empty, such as a write of an empty list.
287 updateOperationType(LogicalOperation.DELETE);
289 schema.fullVerifyStructure(value);
297 private void clearSnapshot() {
298 snapshotCache = null;
301 Optional<TreeNode> getSnapshot() {
302 return snapshotCache;
305 Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
306 snapshotCache = requireNonNull(snapshot);
310 void updateOperationType(final LogicalOperation type) {
314 // Make sure we do not reuse previously-instantiated data-derived metadata
315 writtenOriginal = null;
320 public String toString() {
321 final ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues()
322 .add("identifier", identifier).add("operation", operation).add("modificationType", modType);
323 if (!children.isEmpty()) {
324 helper.add("childModification", children);
326 return helper.toString();
329 void resolveModificationType(final @NonNull ModificationType type) {
334 * Update this node's value and operation type without disturbing any of its child modifications.
336 * @param type New operation type
337 * @param newValue New node value
339 void updateValue(final LogicalOperation type, final NormalizedNode<?, ?> newValue) {
340 this.value = requireNonNull(newValue);
341 updateOperationType(type);
345 * Return the physical modification done to data. May return null if the
346 * operation has not been applied to the underlying tree. This is different
347 * from the logical operation in that it can actually be a no-op if the
348 * operation has no side-effects (like an empty merge on a container).
350 * @return Modification type.
352 ModificationType getModificationType() {
356 public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
357 return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);
360 void setValidatedNode(final ModificationApplyOperation op, final Optional<? extends TreeNode> current,
361 final Optional<? extends TreeNode> node) {
362 this.validatedOp = requireNonNull(op);
363 this.validatedCurrent = requireNonNull(current);
364 this.validatedNode = requireNonNull(node);
368 * Acquire pre-validated node assuming a previous operation and node. This is a counterpart to
369 * {@link #setValidatedNode(ModificationApplyOperation, Optional, Optional)}.
371 * @param op Currently-executing operation
372 * @param current Currently-used tree node
373 * @return {@code null} if there is a mismatch with previously-validated node (if present) or the result of previous
376 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
377 justification = "The contract is package-internal and well documented, we do not need a separate wrapper")
378 @Nullable Optional<? extends TreeNode> getValidatedNode(final ModificationApplyOperation op,
379 final Optional<? extends TreeNode> current) {
380 return op.equals(validatedOp) && current.equals(validatedCurrent) ? validatedNode : null;