Merge "Added Nonnull annotation for get operation"
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / InMemoryDataTreeModification.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.impl.schema.tree;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import java.util.Map.Entry;
13 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
14 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
16 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
17 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
18 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
22 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeUtils;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 final class InMemoryDataTreeModification implements DataTreeModification {
27     private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> UPDATER =
28             AtomicIntegerFieldUpdater.newUpdater(InMemoryDataTreeModification.class, "sealed");
29     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
30
31     private final RootModificationApplyOperation strategyTree;
32     private final InMemoryDataTreeSnapshot snapshot;
33     private final ModifiedNode rootNode;
34     private final Version version;
35
36     private volatile int sealed = 0;
37
38     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot, final RootModificationApplyOperation resolver) {
39         this.snapshot = Preconditions.checkNotNull(snapshot);
40         this.strategyTree = Preconditions.checkNotNull(resolver).snapshot();
41         this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), false);
42
43         /*
44          * We could allocate version beforehand, since Version contract
45          * states two allocated version must be always different.
46          *
47          * Preallocating version simplifies scenarios such as
48          * chaining of modifications, since version for particular
49          * node in modification and in data tree (if successfully
50          * committed) will be same and will not change.
51          */
52         this.version = snapshot.getRootNode().getSubtreeVersion().next();
53     }
54
55     ModifiedNode getRootModification() {
56         return rootNode;
57     }
58
59     ModificationApplyOperation getStrategy() {
60         return strategyTree;
61     }
62
63     @Override
64     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> value) {
65         checkSealed();
66
67         resolveModificationFor(path).write(value);
68     }
69
70     @Override
71     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
72         checkSealed();
73
74         mergeImpl(resolveModificationFor(path),data);
75     }
76
77     private void mergeImpl(final OperationWithModification op,final NormalizedNode<?,?> data) {
78         if (data instanceof NormalizedNodeContainer<?,?,?>) {
79             @SuppressWarnings({ "rawtypes", "unchecked" })
80             NormalizedNodeContainer<?,?,NormalizedNode<PathArgument, ?>> dataContainer = (NormalizedNodeContainer) data;
81             for(NormalizedNode<PathArgument, ?> child : dataContainer.getValue()) {
82                 PathArgument childId = child.getIdentifier();
83                 mergeImpl(op.forChild(childId), child);
84             }
85         }
86         op.merge(data);
87     }
88
89     @Override
90     public void delete(final YangInstanceIdentifier path) {
91         checkSealed();
92
93         resolveModificationFor(path).delete();
94     }
95
96     @Override
97     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
98         /*
99          * Walk the tree from the top, looking for the first node between root and
100          * the requested path which has been modified. If no such node exists,
101          * we use the node itself.
102          */
103         final Entry<YangInstanceIdentifier, ModifiedNode> entry = TreeNodeUtils.findClosestsOrFirstMatch(rootNode, path, ModifiedNode.IS_TERMINAL_PREDICATE);
104         final YangInstanceIdentifier key = entry.getKey();
105         final ModifiedNode mod = entry.getValue();
106
107         final Optional<TreeNode> result = resolveSnapshot(key, mod);
108         if (result.isPresent()) {
109             NormalizedNode<?, ?> data = result.get().getData();
110             return NormalizedNodeUtils.findNode(key, data, path);
111         } else {
112             return Optional.absent();
113         }
114     }
115
116     private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path,
117             final ModifiedNode modification) {
118         final Optional<Optional<TreeNode>> potentialSnapshot = modification.getSnapshotCache();
119         if (potentialSnapshot.isPresent()) {
120             return potentialSnapshot.get();
121         }
122
123         try {
124             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
125                     version);
126         } catch (Exception e) {
127             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
128             throw e;
129         }
130     }
131
132     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
133         LOG.trace("Resolving modification apply strategy for {}", path);
134         if (rootNode.getType() == ModificationType.UNMODIFIED) {
135             strategyTree.upgradeIfPossible();
136         }
137
138         return TreeNodeUtils.<ModificationApplyOperation>findNodeChecked(strategyTree, path);
139     }
140
141     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
142         // We ensure strategy is present.
143         final ModificationApplyOperation operation = resolveModificationStrategy(path);
144
145         final boolean isOrdered;
146         if (operation instanceof SchemaAwareApplyOperation) {
147             isOrdered = ((SchemaAwareApplyOperation) operation).isOrdered();
148         } else {
149             isOrdered = true;
150         }
151
152         ModifiedNode modification = rootNode;
153         for (PathArgument pathArg : path.getPathArguments()) {
154             modification = modification.modifyChild(pathArg, isOrdered);
155         }
156         return OperationWithModification.from(operation, modification);
157     }
158
159     @Override
160     public void ready() {
161         final boolean wasRunning = UPDATER.compareAndSet(this, 0, 1);
162         Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
163
164         rootNode.seal();
165     }
166
167     private void checkSealed() {
168         Preconditions.checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
169     }
170
171     @Override
172     public String toString() {
173         return "MutableDataTree [modification=" + rootNode + "]";
174     }
175
176     @Override
177     public DataTreeModification newModification() {
178         Preconditions.checkState(sealed == 1, "Attempted to chain on an unsealed modification");
179
180         if (rootNode.getType() == ModificationType.UNMODIFIED) {
181             // Simple fast case: just use the underlying modification
182             return snapshot.newModification();
183         }
184
185         /*
186          * We will use preallocated version, this means returned snapshot will
187          * have same version each time this method is called.
188          */
189         TreeNode originalSnapshotRoot = snapshot.getRootNode();
190         Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), version);
191
192         InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(), tempRoot.get(), strategyTree);
193         return tempTree.newModification();
194     }
195
196     Version getVersion() {
197         return version;
198     }
199 }