Merge "Cleanup some major sonar warning in yang/*"
[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 com.google.common.collect.Iterables;
13 import java.util.Collection;
14 import java.util.Map.Entry;
15 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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.DataTreeModification;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModificationCursor;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 final class InMemoryDataTreeModification implements DataTreeModification {
29     private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> UPDATER =
30             AtomicIntegerFieldUpdater.newUpdater(InMemoryDataTreeModification.class, "sealed");
31     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
32
33     private final RootModificationApplyOperation strategyTree;
34     private final InMemoryDataTreeSnapshot snapshot;
35     private final ModifiedNode rootNode;
36     private final Version version;
37
38     private volatile int sealed = 0;
39
40     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot, final RootModificationApplyOperation resolver) {
41         this.snapshot = Preconditions.checkNotNull(snapshot);
42         this.strategyTree = Preconditions.checkNotNull(resolver).snapshot();
43         this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), strategyTree.getChildPolicy());
44
45         /*
46          * We could allocate version beforehand, since Version contract
47          * states two allocated version must be always different.
48          *
49          * Preallocating version simplifies scenarios such as
50          * chaining of modifications, since version for particular
51          * node in modification and in data tree (if successfully
52          * committed) will be same and will not change.
53          */
54         this.version = snapshot.getRootNode().getSubtreeVersion().next();
55     }
56
57     ModifiedNode getRootModification() {
58         return rootNode;
59     }
60
61     ModificationApplyOperation getStrategy() {
62         return strategyTree;
63     }
64
65     @Override
66     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
67         checkSealed();
68
69         resolveModificationFor(path).write(data);
70     }
71
72     @Override
73     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
74         checkSealed();
75
76         resolveModificationFor(path).merge(data);
77     }
78
79     @Override
80     public void delete(final YangInstanceIdentifier path) {
81         checkSealed();
82
83         resolveModificationFor(path).delete();
84     }
85
86     @Override
87     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
88         /*
89          * Walk the tree from the top, looking for the first node between root and
90          * the requested path which has been modified. If no such node exists,
91          * we use the node itself.
92          */
93         final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path, ModifiedNode.IS_TERMINAL_PREDICATE);
94         final YangInstanceIdentifier key = entry.getKey();
95         final ModifiedNode mod = entry.getValue();
96
97         final Optional<TreeNode> result = resolveSnapshot(key, mod);
98         if (result.isPresent()) {
99             NormalizedNode<?, ?> data = result.get().getData();
100             return NormalizedNodes.findNode(key, data, path);
101         } else {
102             return Optional.absent();
103         }
104     }
105
106     private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
107         final Optional<TreeNode> potentialSnapshot = modification.getSnapshot();
108         if (potentialSnapshot != null) {
109             return potentialSnapshot;
110         }
111
112         try {
113             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
114                     version);
115         } catch (Exception e) {
116             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
117             throw e;
118         }
119     }
120
121     private void upgradeIfPossible() {
122         if (rootNode.getOperation() == LogicalOperation.NONE) {
123             strategyTree.upgradeIfPossible();
124         }
125     }
126
127     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
128         LOG.trace("Resolving modification apply strategy for {}", path);
129
130         upgradeIfPossible();
131         return StoreTreeNodes.<ModificationApplyOperation>findNodeChecked(strategyTree, path);
132     }
133
134     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
135         upgradeIfPossible();
136
137         /*
138          * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
139          *
140          * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
141          * ending with an empty one, as we will throw the exception below. This fact could end up
142          * being a problem, as we'd have bunch of phantom operations.
143          *
144          * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
145          * process.
146          */
147         ModificationApplyOperation operation = strategyTree;
148         ModifiedNode modification = rootNode;
149
150         int i = 1;
151         for(PathArgument pathArg : path.getPathArguments()) {
152             Optional<ModificationApplyOperation> potential = operation.getChild(pathArg);
153             if (!potential.isPresent()) {
154                 throw new IllegalArgumentException(String.format("Child %s is not present in schema tree.",
155                         Iterables.toString(Iterables.limit(path.getPathArguments(), i))));
156             }
157             operation = potential.get();
158             ++i;
159
160             modification = modification.modifyChild(pathArg, operation.getChildPolicy());
161         }
162
163         return OperationWithModification.from(operation, modification);
164     }
165
166     @Override
167     public void ready() {
168         final boolean wasRunning = UPDATER.compareAndSet(this, 0, 1);
169         Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
170
171         rootNode.seal();
172     }
173
174     private void checkSealed() {
175         Preconditions.checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
176     }
177
178     @Override
179     public String toString() {
180         return "MutableDataTree [modification=" + rootNode + "]";
181     }
182
183     @Override
184     public DataTreeModification newModification() {
185         Preconditions.checkState(sealed == 1, "Attempted to chain on an unsealed modification");
186
187         if (rootNode.getOperation() == LogicalOperation.NONE) {
188             // Simple fast case: just use the underlying modification
189             return snapshot.newModification();
190         }
191
192         /*
193          * We will use preallocated version, this means returned snapshot will
194          * have same version each time this method is called.
195          */
196         TreeNode originalSnapshotRoot = snapshot.getRootNode();
197         Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), version);
198
199         InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(), tempRoot.get(), strategyTree);
200         return tempTree.newModification();
201     }
202
203     Version getVersion() {
204         return version;
205     }
206
207     private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
208         final Collection<ModifiedNode> children = node.getChildren();
209         if (!children.isEmpty()) {
210             cursor.enter(node.getIdentifier());
211             for (ModifiedNode child : children) {
212                 applyNode(cursor, child);
213             }
214             cursor.exit();
215         }
216     }
217
218     private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
219         switch (node.getOperation()) {
220         case NONE:
221             break;
222         case DELETE:
223             cursor.delete(node.getIdentifier());
224             break;
225         case MERGE:
226             cursor.merge(node.getIdentifier(), node.getWrittenValue());
227             applyChildren(cursor, node);
228             break;
229         case TOUCH:
230             // TODO: we could improve efficiency of cursor use if we could understand
231             //       nested TOUCH operations. One way of achieving that would be a proxy
232             //       cursor, which would keep track of consecutive enter and exit calls
233             //       and coalesce them.
234             applyChildren(cursor, node);
235             break;
236         case WRITE:
237             cursor.write(node.getIdentifier(), node.getWrittenValue());
238             applyChildren(cursor, node);
239             break;
240         default:
241             throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
242         }
243     }
244
245     @Override
246     public void applyToCursor(final DataTreeModificationCursor cursor) {
247         for (ModifiedNode child : rootNode.getChildren()) {
248             applyNode(cursor, child);
249         }
250     }
251 }