Fix lead transaction cancellation
[mdsal.git] / dom / mdsal-dom-spi / src / main / java / org / opendaylight / mdsal / dom / spi / 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.spi;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.MoreObjects;
13 import com.google.common.util.concurrent.FluentFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.SettableFuture;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.eclipse.jdt.annotation.Nullable;
18 import org.opendaylight.mdsal.common.api.CommitInfo;
19 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
20
21 /**
22  * Transaction context. Tracks the relationship with the backend transaction.
23  * We never leak this class to the user and have it implement the {@link FutureCallback}
24  * interface so we have a simple way of propagating the result.
25  */
26 final class PingPongTransaction implements FutureCallback<CommitInfo> {
27     private final @NonNull SettableFuture<CommitInfo> future = SettableFuture.create();
28     private final @NonNull FluentFuture<CommitInfo> fluent = FluentFuture.from(future);
29     private final @NonNull DOMDataTreeReadWriteTransaction delegate;
30
31     private @Nullable DOMDataTreeReadWriteTransaction frontendTransaction;
32
33     PingPongTransaction(final DOMDataTreeReadWriteTransaction delegate) {
34         this.delegate = requireNonNull(delegate);
35     }
36
37     @NonNull DOMDataTreeReadWriteTransaction getTransaction() {
38         return delegate;
39     }
40
41     DOMDataTreeReadWriteTransaction getFrontendTransaction() {
42         return frontendTransaction;
43     }
44
45     @NonNull FluentFuture<CommitInfo> getCommitFuture() {
46         return fluent;
47     }
48
49     @Override
50     public void onSuccess(final CommitInfo result) {
51         future.set(result);
52     }
53
54     @Override
55     public void onFailure(final Throwable throwable) {
56         future.setException(throwable);
57     }
58
59     void recordFrontendTransaction(final DOMDataTreeReadWriteTransaction tx) {
60         if (frontendTransaction == null) {
61             frontendTransaction = requireNonNull(tx);
62         }
63     }
64
65     @Override
66     public String toString() {
67         return MoreObjects.toStringHelper(this).add("delegate", delegate).toString();
68     }
69 }