Merge "BUG-997: Fix URLSchemaContextResolver"
[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.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 import com.google.common.base.Optional;
27 import com.google.common.base.Preconditions;
28
29 final class InMemoryDataTreeModification implements DataTreeModification {
30     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
31     private final RootModificationApplyOperation strategyTree;
32     private final InMemoryDataTreeSnapshot snapshot;
33     private final ModifiedNode rootNode;
34     private final Version version;
35
36     @GuardedBy("this")
37     private boolean sealed = false;
38
39     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot, final RootModificationApplyOperation resolver) {
40         this.snapshot = Preconditions.checkNotNull(snapshot);
41         this.strategyTree = Preconditions.checkNotNull(resolver).snapshot();
42         this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode());
43         /*
44          * We could allocate version beforehand, since Version contract
45          * states two allocated version must be allways 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          * commited) will be same and will not change.
51          * 
52          */
53         this.version = snapshot.getRootNode().getSubtreeVersion().next();
54     }
55
56     ModifiedNode getRootModification() {
57         return rootNode;
58     }
59
60     ModificationApplyOperation getStrategy() {
61         return strategyTree;
62     }
63
64     @Override
65     public synchronized void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> value) {
66         checkSealed();
67         resolveModificationFor(path).write(value);
68     }
69
70     @Override
71     public synchronized void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
72         checkSealed();
73         mergeImpl(resolveModificationFor(path),data);
74     }
75
76     private void mergeImpl(final OperationWithModification op,final NormalizedNode<?,?> data) {
77
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 synchronized void delete(final YangInstanceIdentifier path) {
91         checkSealed();
92         resolveModificationFor(path).delete();
93     }
94
95     @Override
96     public synchronized Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
97         /*
98          * Walk the tree from the top, looking for the first node between root and
99          * the requested path which has been modified. If no such node exists,
100          * we use the node itself.
101          */
102         final Entry<YangInstanceIdentifier, ModifiedNode> entry = TreeNodeUtils.findClosestsOrFirstMatch(rootNode, path, ModifiedNode.IS_TERMINAL_PREDICATE);
103         final YangInstanceIdentifier key = entry.getKey();
104         final ModifiedNode mod = entry.getValue();
105
106         final Optional<TreeNode> result = resolveSnapshot(key, mod);
107         if (result.isPresent()) {
108             NormalizedNode<?, ?> data = result.get().getData();
109             return NormalizedNodeUtils.findNode(key, data, path);
110         } else {
111             return Optional.absent();
112         }
113     }
114
115     private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path,
116             final ModifiedNode modification) {
117         final Optional<Optional<TreeNode>> potentialSnapshot = modification.getSnapshotCache();
118         if(potentialSnapshot.isPresent()) {
119             return potentialSnapshot.get();
120         }
121
122         try {
123             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
124                     version);
125         } catch (Exception e) {
126             LOG.error("Could not create snapshot for {}:{}", path,modification,e);
127             throw e;
128         }
129     }
130
131     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
132         LOG.trace("Resolving modification apply strategy for {}", path);
133         if(rootNode.getType() == ModificationType.UNMODIFIED) {
134             strategyTree.upgradeIfPossible();
135         }
136
137         return TreeNodeUtils.<ModificationApplyOperation>findNodeChecked(strategyTree, path);
138     }
139
140     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
141         ModifiedNode modification = rootNode;
142         // We ensure strategy is present.
143         ModificationApplyOperation operation = resolveModificationStrategy(path);
144         for (PathArgument pathArg : path.getPathArguments()) {
145             modification = modification.modifyChild(pathArg);
146         }
147         return OperationWithModification.from(operation, modification);
148     }
149
150     @Override
151     public synchronized void ready() {
152         Preconditions.checkState(!sealed, "Attempted to seal an already-sealed Data Tree.");
153         sealed = true;
154         rootNode.seal();
155     }
156
157     @GuardedBy("this")
158     private void checkSealed() {
159         Preconditions.checkState(!sealed, "Data Tree is sealed. No further modifications allowed.");
160     }
161
162     @Override
163     public String toString() {
164         return "MutableDataTree [modification=" + rootNode + "]";
165     }
166
167     @Override
168     public synchronized DataTreeModification newModification() {
169         Preconditions.checkState(sealed, "Attempted to chain on an unsealed modification");
170
171         if(rootNode.getType() == ModificationType.UNMODIFIED) {
172             return snapshot.newModification();
173         }
174
175         /*
176          *  We will use preallocated version, this means returned snapshot will 
177          *  have same version each time this method is called.
178          */
179         TreeNode originalSnapshotRoot = snapshot.getRootNode();
180         Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), version);
181
182         InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(), tempRoot.get(), strategyTree);
183         return tempTree.newModification();
184     }
185
186     Version getVersion() {
187         return version;
188     }
189 }