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