e378795cb38f40c859c9fa0ff5c944c3bafa1cae
[mdsal.git] / dom / mdsal-dom-broker / src / main / java / org / opendaylight / mdsal / dom / broker / PingPongTransaction.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.broker;
9
10 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
11
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.Preconditions;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.SettableFuture;
18 import org.opendaylight.mdsal.dom.api.DOMDataReadWriteTransaction;
19
20 /**
21  * Transaction context. Tracks the relationship with the backend transaction.
22  * We never leak this class to the user and have it implement the {@link FutureCallback}
23  * interface so we have a simple way of propagating the result.
24  */
25 final class PingPongTransaction implements FutureCallback<Void> {
26     private final CheckedFuture<Void, TransactionCommitFailedException> submitFuture;
27     private final DOMDataReadWriteTransaction delegate;
28     private final SettableFuture<Void> future;
29     private DOMDataReadWriteTransaction frontendTransaction;
30
31     PingPongTransaction(final DOMDataReadWriteTransaction delegate) {
32         this.delegate = Preconditions.checkNotNull(delegate);
33         future = SettableFuture.create();
34         submitFuture = new PingPongFuture(future);
35     }
36
37     DOMDataReadWriteTransaction getTransaction() {
38         return delegate;
39     }
40
41     DOMDataReadWriteTransaction getFrontendTransaction() {
42         return frontendTransaction;
43     }
44
45     CheckedFuture<Void, TransactionCommitFailedException> getSubmitFuture() {
46         return submitFuture;
47     }
48
49     @Override
50     public void onSuccess(final Void result) {
51         future.set(result);
52     }
53
54     @Override
55     public void onFailure(final Throwable t) {
56         future.setException(t);
57     }
58
59     void recordFrontendTransaction(final DOMDataReadWriteTransaction tx) {
60         if (frontendTransaction != null) {
61             frontendTransaction = tx;
62         }
63     }
64
65     @Override
66     public String toString() {
67         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
68     }
69
70     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
71         return toStringHelper.add("delegate", delegate);
72     }
73 }