BUG-868: do not use InstanceIdentifier.getPath()
[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
13 import java.util.Map.Entry;
14
15 import javax.annotation.concurrent.GuardedBy;
16
17 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
24 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeUtils;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 final class InMemoryDataTreeModification implements DataTreeModification {
29     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
30     private final ModificationApplyOperation strategyTree;
31     private final InMemoryDataTreeSnapshot snapshot;
32     private final ModifiedNode rootNode;
33
34     @GuardedBy("this")
35     private boolean sealed = false;
36
37     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot, final ModificationApplyOperation resolver) {
38         this.snapshot = Preconditions.checkNotNull(snapshot);
39         this.strategyTree = Preconditions.checkNotNull(resolver);
40         this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode());
41     }
42
43     ModifiedNode getRootModification() {
44         return rootNode;
45     }
46
47     ModificationApplyOperation getStrategy() {
48         return strategyTree;
49     }
50
51     @Override
52     public synchronized void write(final InstanceIdentifier path, final NormalizedNode<?, ?> value) {
53         checkSealed();
54         resolveModificationFor(path).write(value);
55     }
56
57     @Override
58     public synchronized void merge(final InstanceIdentifier path, final NormalizedNode<?, ?> data) {
59         checkSealed();
60         mergeImpl(resolveModificationFor(path),data);
61     }
62
63     private void mergeImpl(final OperationWithModification op,final NormalizedNode<?,?> data) {
64
65         if(data instanceof NormalizedNodeContainer<?,?,?>) {
66             @SuppressWarnings({ "rawtypes", "unchecked" })
67             NormalizedNodeContainer<?,?,NormalizedNode<PathArgument, ?>> dataContainer = (NormalizedNodeContainer) data;
68             for(NormalizedNode<PathArgument, ?> child : dataContainer.getValue()) {
69                 PathArgument childId = child.getIdentifier();
70                 mergeImpl(op.forChild(childId), child);
71             }
72         }
73         op.merge(data);
74     }
75
76     @Override
77     public synchronized void delete(final InstanceIdentifier path) {
78         checkSealed();
79         resolveModificationFor(path).delete();
80     }
81
82     @Override
83     public synchronized Optional<NormalizedNode<?, ?>> readNode(final InstanceIdentifier path) {
84         /*
85          * Walk the tree from the top, looking for the first node between root and
86          * the requested path which has been modified. If no such node exists,
87          * we use the node itself.
88          */
89         final Entry<InstanceIdentifier, ModifiedNode> entry = TreeNodeUtils.findClosestsOrFirstMatch(rootNode, path, ModifiedNode.IS_TERMINAL_PREDICATE);
90         final InstanceIdentifier key = entry.getKey();
91         final ModifiedNode mod = entry.getValue();
92
93         final Optional<TreeNode> result = resolveSnapshot(key, mod);
94         if (result.isPresent()) {
95             NormalizedNode<?, ?> data = result.get().getData();
96             return NormalizedNodeUtils.findNode(key, data, path);
97         } else {
98             return Optional.absent();
99         }
100     }
101
102     private Optional<TreeNode> resolveSnapshot(final InstanceIdentifier path,
103             final ModifiedNode modification) {
104         final Optional<Optional<TreeNode>> potentialSnapshot = modification.getSnapshotCache();
105         if(potentialSnapshot.isPresent()) {
106             return potentialSnapshot.get();
107         }
108
109         try {
110             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
111                     snapshot.getRootNode().getSubtreeVersion().next());
112         } catch (Exception e) {
113             LOG.error("Could not create snapshot for {}:{}", path,modification,e);
114             throw e;
115         }
116     }
117
118     private ModificationApplyOperation resolveModificationStrategy(final InstanceIdentifier path) {
119         LOG.trace("Resolving modification apply strategy for {}", path);
120         return TreeNodeUtils.findNodeChecked(strategyTree, path);
121     }
122
123     private OperationWithModification resolveModificationFor(final InstanceIdentifier path) {
124         ModifiedNode modification = rootNode;
125         // We ensure strategy is present.
126         ModificationApplyOperation operation = resolveModificationStrategy(path);
127         for (PathArgument pathArg : path.getPathArguments()) {
128             modification = modification.modifyChild(pathArg);
129         }
130         return OperationWithModification.from(operation, modification);
131     }
132
133     @Override
134     public synchronized void ready() {
135         Preconditions.checkState(!sealed, "Attempted to seal an already-sealed Data Tree.");
136         sealed = true;
137         rootNode.seal();
138     }
139
140     @GuardedBy("this")
141     private void checkSealed() {
142         Preconditions.checkState(!sealed, "Data Tree is sealed. No further modifications allowed.");
143     }
144
145     @Override
146     public String toString() {
147         return "MutableDataTree [modification=" + rootNode + "]";
148     }
149
150     @Override
151     public synchronized DataTreeModification newModification() {
152         Preconditions.checkState(sealed, "Attempted to chain on an unsealed modification");
153
154         if(rootNode.getType() == ModificationType.UNMODIFIED) {
155             return snapshot.newModification();
156         }
157
158         /*
159          *  FIXME: Add advanced transaction chaining for modification of not rebased
160          *  modification.
161          *
162          *  Current computation of tempRoot may yeld incorrect subtree versions
163          *  if there are multiple concurrent transactions, which may break
164          *  versioning preconditions for modification of previously occured write,
165          *  directly nested under parent node, since node version is derived from
166          *  subtree version.
167          *
168          *  For deeper nodes subtree version is derived from their respective metadata
169          *  nodes, so this incorrect root subtree version is not affecting us.
170          */
171         TreeNode originalSnapshotRoot = snapshot.getRootNode();
172         Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), originalSnapshotRoot.getSubtreeVersion().next());
173
174         InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(), tempRoot.get(), strategyTree);
175         return tempTree.newModification();
176     }
177 }