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