Merge "Bug 1475: Correctly handle case of typedef that extends boolean"
[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 java.util.Map.Entry;
11
12 import javax.annotation.concurrent.GuardedBy;
13
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.impl.schema.NormalizedNodeUtils;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 import com.google.common.base.Optional;
26 import com.google.common.base.Preconditions;
27
28 final class InMemoryDataTreeModification implements DataTreeModification {
29     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
30     private final RootModificationApplyOperation 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 RootModificationApplyOperation resolver) {
38         this.snapshot = Preconditions.checkNotNull(snapshot);
39         this.strategyTree = Preconditions.checkNotNull(resolver).snapshot();
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 YangInstanceIdentifier path, final NormalizedNode<?, ?> value) {
53         checkSealed();
54         resolveModificationFor(path).write(value);
55     }
56
57     @Override
58     public synchronized void merge(final YangInstanceIdentifier 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 YangInstanceIdentifier path) {
78         checkSealed();
79         resolveModificationFor(path).delete();
80     }
81
82     @Override
83     public synchronized Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier 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<YangInstanceIdentifier, ModifiedNode> entry = TreeNodeUtils.findClosestsOrFirstMatch(rootNode, path, ModifiedNode.IS_TERMINAL_PREDICATE);
90         final YangInstanceIdentifier 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 YangInstanceIdentifier 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 YangInstanceIdentifier path) {
119         LOG.trace("Resolving modification apply strategy for {}", path);
120         if(rootNode.getType() == ModificationType.UNMODIFIED) {
121             strategyTree.upgradeIfPossible();
122         }
123
124         return TreeNodeUtils.<ModificationApplyOperation>findNodeChecked(strategyTree, path);
125     }
126
127     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
128         ModifiedNode modification = rootNode;
129         // We ensure strategy is present.
130         ModificationApplyOperation operation = resolveModificationStrategy(path);
131         for (PathArgument pathArg : path.getPathArguments()) {
132             modification = modification.modifyChild(pathArg);
133         }
134         return OperationWithModification.from(operation, modification);
135     }
136
137     @Override
138     public synchronized void ready() {
139         Preconditions.checkState(!sealed, "Attempted to seal an already-sealed Data Tree.");
140         sealed = true;
141         rootNode.seal();
142     }
143
144     @GuardedBy("this")
145     private void checkSealed() {
146         Preconditions.checkState(!sealed, "Data Tree is sealed. No further modifications allowed.");
147     }
148
149     @Override
150     public String toString() {
151         return "MutableDataTree [modification=" + rootNode + "]";
152     }
153
154     @Override
155     public synchronized DataTreeModification newModification() {
156         Preconditions.checkState(sealed, "Attempted to chain on an unsealed modification");
157
158         if(rootNode.getType() == ModificationType.UNMODIFIED) {
159             return snapshot.newModification();
160         }
161
162         /*
163          *  FIXME: Add advanced transaction chaining for modification of not rebased
164          *  modification.
165          *
166          *  Current computation of tempRoot may yeld incorrect subtree versions
167          *  if there are multiple concurrent transactions, which may break
168          *  versioning preconditions for modification of previously occured write,
169          *  directly nested under parent node, since node version is derived from
170          *  subtree version.
171          *
172          *  For deeper nodes subtree version is derived from their respective metadata
173          *  nodes, so this incorrect root subtree version is not affecting us.
174          */
175         TreeNode originalSnapshotRoot = snapshot.getRootNode();
176         Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), originalSnapshotRoot.getSubtreeVersion().next());
177
178         InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(), tempRoot.get(), strategyTree);
179         return tempTree.newModification();
180     }
181 }