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 java.util.Collection;
17 import java.util.Optional;
18 import java.util.function.Predicate;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
21 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
30 * Node Modification Node and Tree.
33 * Tree which structurally resembles data tree and captures client modifications to the data store tree. This tree is
34 * lazily created and populated via {@link #modifyChild(PathArgument, ModificationApplyOperation, Version)} and
35 * {@link TreeNode} which represents original state as tracked by {@link #getOriginal()}.
38 * The contract is that the state information exposed here preserves the temporal ordering of whatever modifications
39 * were executed. A child's effects pertain to data node as modified by its ancestors. This means that in order to
40 * reconstruct the effective data node presentation, it is sufficient to perform a depth-first pre-order traversal of
43 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
44 static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = input -> {
45 requireNonNull(input);
46 switch (input.getOperation()) {
55 throw new IllegalArgumentException("Unhandled modification type " + input.getOperation());
59 private final Map<PathArgument, ModifiedNode> children;
60 private final Optional<TreeNode> original;
61 private final PathArgument identifier;
62 private LogicalOperation operation = LogicalOperation.NONE;
63 private Optional<TreeNode> snapshotCache;
64 private NormalizedNode<?, ?> value;
65 private ModificationType modType;
67 // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node.
68 private TreeNode writtenOriginal;
70 // Internal cache for TreeNodes created as part of validation
71 private ModificationApplyOperation validatedOp;
72 private Optional<TreeNode> validatedCurrent;
73 private Optional<TreeNode> validatedNode;
75 private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original,
76 final ChildTrackingPolicy childPolicy) {
77 this.identifier = identifier;
78 this.original = original;
79 this.children = childPolicy.createMap();
83 public PathArgument getIdentifier() {
88 LogicalOperation getOperation() {
93 Optional<TreeNode> getOriginal() {
98 * Return the value which was written to this node. The returned object is only valid for
99 * {@link LogicalOperation#MERGE} and {@link LogicalOperation#WRITE}.
100 * operations. It should only be consulted when this modification is going to end up being
101 * {@link ModificationType#WRITE}.
103 * @return Currently-written value
105 @NonNull NormalizedNode<?, ?> getWrittenValue() {
106 return verifyNotNull(value);
110 * Returns child modification if child was modified.
112 * @return Child modification if direct child or it's subtree was modified.
115 public Optional<ModifiedNode> getChild(final PathArgument child) {
116 return Optional.ofNullable(children.get(child));
119 private Optional<TreeNode> metadataFromSnapshot(final @NonNull PathArgument child) {
120 return original.isPresent() ? original.get().getChild(child) : Optional.empty();
123 private Optional<TreeNode> metadataFromData(final @NonNull PathArgument child, final Version modVersion) {
124 if (writtenOriginal == null) {
125 // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version
126 // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting
128 writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion);
131 return writtenOriginal.getChild(child);
135 * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because
136 * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need
137 * to take the current node's operation into account.
139 * @param child Child we are looking to modify
140 * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
141 * @return Before-image tree node as observed by that child.
143 private Optional<TreeNode> findOriginalMetadata(final @NonNull PathArgument child, final Version modVersion) {
146 // DELETE implies non-presence
147 return Optional.empty();
151 return metadataFromSnapshot(child);
153 // WRITE implies presence based on written data
154 return metadataFromData(child, modVersion);
156 throw new IllegalStateException("Unhandled node operation " + operation);
161 * Returns child modification if child was modified, creates {@link ModifiedNode}
162 * for child otherwise. 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 childOper Child operation
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(final @NonNull PathArgument child, final @NonNull ModificationApplyOperation childOper,
172 final @NonNull 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, childOper.getChildPolicy());
186 if (operation == LogicalOperation.MERGE && value != null) {
188 * We are attempting to modify a previously-unmodified part of a MERGE node. If the
189 * value contains this component, we need to materialize it as a MERGE modification.
191 @SuppressWarnings({ "rawtypes", "unchecked" })
192 final Optional<NormalizedNode<?, ?>> childData = ((NormalizedNodeContainer)value).getChild(child);
193 if (childData.isPresent()) {
194 childOper.mergeIntoModifiedNode(newlyCreated, childData.get(), modVersion);
198 children.put(child, newlyCreated);
203 * Returns all recorded direct child modifications.
205 * @return all recorded direct child modifications
208 Collection<ModifiedNode> getChildren() {
209 return children.values();
213 * Records a delete for associated node.
216 final LogicalOperation newType;
221 // We need to record this delete.
222 newType = LogicalOperation.DELETE;
225 // In case of merge - delete needs to be recored and must not to be changed into NONE, because lazy
226 // expansion of parent MERGE node would reintroduce it again.
227 newType = LogicalOperation.DELETE;
232 * We are canceling a previous modification. This is a bit tricky, as the original write may have just
233 * introduced the data, or it may have modified it.
235 * As documented in BUG-2470, a delete of data introduced in this transaction needs to be turned into
238 newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
241 throw new IllegalStateException("Unhandled deletion of node with " + operation);
247 updateOperationType(newType);
251 * Records a write for associated node.
253 * @param newValue new value
255 void write(final NormalizedNode<?, ?> newValue) {
256 updateValue(LogicalOperation.WRITE, newValue);
261 * Seal the modification node and prune any children which has not been modified.
263 * @param schema associated apply operation
264 * @param version target version
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).map(TreeNode::getData).orElse(null);
285 // The write has ended up being empty, such as a write of an empty list.
286 updateOperationType(LogicalOperation.DELETE);
288 schema.fullVerifyStructure(value);
296 private void clearSnapshot() {
297 snapshotCache = null;
300 Optional<TreeNode> getSnapshot() {
301 return snapshotCache;
304 Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
305 snapshotCache = requireNonNull(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 final ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues()
321 .add("identifier", identifier).add("operation", operation).add("modificationType", modType);
322 if (!children.isEmpty()) {
323 helper.add("childModification", children);
325 return helper.toString();
328 void resolveModificationType(final @NonNull ModificationType type) {
333 * Update this node's value and operation type without disturbing any of its child modifications.
335 * @param type New operation type
336 * @param newValue New node value
338 void updateValue(final LogicalOperation type, final NormalizedNode<?, ?> newValue) {
339 this.value = requireNonNull(newValue);
340 updateOperationType(type);
344 * Return the physical modification done to data. May return null if the
345 * operation has not been applied to the underlying tree. This is different
346 * from the logical operation in that it can actually be a no-op if the
347 * operation has no side-effects (like an empty merge on a container).
349 * @return Modification type.
351 ModificationType getModificationType() {
355 public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
356 return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);
359 void setValidatedNode(final ModificationApplyOperation op, final Optional<TreeNode> current,
360 final Optional<TreeNode> node) {
361 this.validatedOp = requireNonNull(op);
362 this.validatedCurrent = requireNonNull(current);
363 this.validatedNode = requireNonNull(node);
366 Optional<TreeNode> getValidatedNode(final ModificationApplyOperation op, final Optional<TreeNode> current) {
367 return op.equals(validatedOp) && current.equals(validatedCurrent) ? validatedNode : null;