checkStyleViolationSeverity=error implemented for mdsal-dom-spi module
[mdsal.git] / dom / mdsal-dom-spi / src / main / java / org / opendaylight / mdsal / dom / spi / store / SnapshotBackedWriteTransaction.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.mdsal.dom.spi.store;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Throwables;
17 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 /**
26  * Implementation of Write transaction which is backed by
27  * {@link DataTreeSnapshot} and executed according to
28  * {@link org.opendaylight.mdsal.dom.spi.store.SnapshotBackedWriteTransaction.TransactionReadyPrototype}.
29  *
30  * @param <T> Identifier type
31  */
32 @Beta
33 public class SnapshotBackedWriteTransaction<T> extends AbstractDOMStoreTransaction<T>
34         implements DOMStoreWriteTransaction {
35
36     private static final Logger LOG = LoggerFactory.getLogger(SnapshotBackedWriteTransaction.class);
37
38     @SuppressWarnings("rawtypes")
39     private static final AtomicReferenceFieldUpdater<SnapshotBackedWriteTransaction,
40         TransactionReadyPrototype> READY_UPDATER =
41             AtomicReferenceFieldUpdater.newUpdater(SnapshotBackedWriteTransaction.class,
42                     TransactionReadyPrototype.class, "readyImpl");
43
44     @SuppressWarnings("rawtypes")
45     private static final AtomicReferenceFieldUpdater<SnapshotBackedWriteTransaction,
46         DataTreeModification> TREE_UPDATER =
47             AtomicReferenceFieldUpdater.newUpdater(SnapshotBackedWriteTransaction.class,
48                     DataTreeModification.class, "mutableTree");
49
50     // non-null when not ready
51     private volatile TransactionReadyPrototype<T> readyImpl;
52     // non-null when not committed/closed
53     private volatile DataTreeModification mutableTree;
54
55     SnapshotBackedWriteTransaction(final T identifier, final boolean debug,
56             final DataTreeSnapshot snapshot, final TransactionReadyPrototype<T> readyImpl) {
57         super(identifier, debug);
58         this.readyImpl = Preconditions.checkNotNull(readyImpl, "readyImpl must not be null.");
59         mutableTree = snapshot.newModification();
60         LOG.debug("Write Tx: {} allocated with snapshot {}", identifier, snapshot);
61     }
62
63     @SuppressWarnings("checkstyle:IllegalCatch")
64     @Override
65     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
66         checkNotReady();
67
68         final DataTreeModification tree = mutableTree;
69         LOG.debug("Tx: {} Write: {}:{}", getIdentifier(), path, data);
70
71         try {
72             tree.write(path, data);
73             // FIXME: Add checked exception
74         } catch (Exception e) {
75             LOG.error("Tx: {}, failed to write {}:{} in {}", getIdentifier(), path, data, tree, e);
76             // Rethrow original ones if they are subclasses of RuntimeException
77             // or Error
78             Throwables.propagateIfPossible(e);
79             // FIXME: Introduce proper checked exception
80             throw new IllegalArgumentException("Illegal input data.", e);
81         }
82     }
83
84     @SuppressWarnings("checkstyle:IllegalCatch")
85     @Override
86     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
87         checkNotReady();
88
89         final DataTreeModification tree = mutableTree;
90         LOG.debug("Tx: {} Merge: {}:{}", getIdentifier(), path, data);
91
92         try {
93             tree.merge(path, data);
94             // FIXME: Add checked exception
95         } catch (Exception e) {
96             LOG.error("Tx: {}, failed to write {}:{} in {}", getIdentifier(), path, data, tree, e);
97             // Rethrow original ones if they are subclasses of RuntimeException
98             // or Error
99             Throwables.propagateIfPossible(e);
100             // FIXME: Introduce proper checked exception
101             throw new IllegalArgumentException("Illegal input data.", e);
102         }
103     }
104
105     @SuppressWarnings("checkstyle:IllegalCatch")
106     @Override
107     public void delete(final YangInstanceIdentifier path) {
108         checkNotReady();
109
110         final DataTreeModification tree = mutableTree;
111         LOG.debug("Tx: {} Delete: {}", getIdentifier(), path);
112
113         try {
114             tree.delete(path);
115             // FIXME: Add checked exception
116         } catch (Exception e) {
117             LOG.error("Tx: {}, failed to delete {} in {}", getIdentifier(), path, tree, e);
118             // Rethrow original ones if they are subclasses of RuntimeException
119             // or Error
120             Throwables.propagateIfPossible(e);
121             // FIXME: Introduce proper checked exception
122             throw new IllegalArgumentException("Illegal path to delete.", e);
123         }
124     }
125
126     /**
127      * Exposed for {@link SnapshotBackedReadWriteTransaction}'s sake only. The contract does
128      * not allow data access after the transaction has been closed or readied.
129      *
130      * @param path Path to read
131      * @return null if the the transaction has been closed;
132      */
133     final Optional<NormalizedNode<?, ?>> readSnapshotNode(final YangInstanceIdentifier path) {
134         return readyImpl == null ? null : mutableTree.readNode(path);
135     }
136
137     private void checkNotReady() {
138         checkState(readyImpl != null,
139                 "Transaction %s is no longer open. No further modifications allowed.", getIdentifier());
140     }
141
142     @Override
143     public DOMStoreThreePhaseCommitCohort ready() {
144         @SuppressWarnings("unchecked")
145         final TransactionReadyPrototype<T> wasReady = READY_UPDATER.getAndSet(this, null);
146         checkState(wasReady != null, "Transaction %s is no longer open", getIdentifier());
147
148         LOG.debug("Store transaction: {} : Ready", getIdentifier());
149
150         final DataTreeModification tree = mutableTree;
151         TREE_UPDATER.lazySet(this, null);
152         tree.ready();
153         return wasReady.transactionReady(this, tree);
154     }
155
156     @Override
157     public void close() {
158         @SuppressWarnings("unchecked")
159         final TransactionReadyPrototype<T> wasReady = READY_UPDATER.getAndSet(this, null);
160         if (wasReady != null) {
161             LOG.debug("Store transaction: {} : Closed", getIdentifier());
162             TREE_UPDATER.lazySet(this, null);
163             wasReady.transactionAborted(this);
164         } else {
165             LOG.debug("Store transaction: {} : Closed after submit", getIdentifier());
166         }
167     }
168
169     @Override
170     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
171         return toStringHelper.add("ready", readyImpl == null);
172     }
173
174     /**
175      * Prototype implementation of {@link SnapshotBackedWriteTransaction#ready()}.
176      *
177      * <p>
178      * This class is intended to be implemented by Transaction factories responsible for allocation
179      * of {@link org.opendaylight.mdsal.dom.spi.store.SnapshotBackedWriteTransaction} and
180      * providing underlying logic for applying implementation.
181      *
182      * @param <T> identifier type
183      */
184     public abstract static class TransactionReadyPrototype<T> {
185         /**
186          * Called when a transaction is closed without being readied. This is not invoked for
187          * transactions which are ready.
188          *
189          * @param tx Transaction which got aborted.
190          */
191         protected abstract void transactionAborted(final SnapshotBackedWriteTransaction<T> tx);
192
193         /**
194          * Returns a commit coordinator associated with supplied transactions.
195          * This call must not fail.
196          *
197          * @param tx
198          *            Transaction on which ready was invoked.
199          * @param tree
200          *            Modified data tree which has been constructed.
201          * @return DOMStoreThreePhaseCommitCohort associated with transaction
202          */
203         protected abstract DOMStoreThreePhaseCommitCohort transactionReady(
204             SnapshotBackedWriteTransaction<T> tx, DataTreeModification tree);
205     }
206 }