Expose completion future from WriteOperations
[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 =
29         FluentFuture.from(new UncancellableListenableFuture<>(future));
30     private final @NonNull DOMDataTreeReadWriteTransaction delegate;
31
32     private @Nullable DOMDataTreeReadWriteTransaction frontendTransaction;
33
34     PingPongTransaction(final DOMDataTreeReadWriteTransaction delegate) {
35         this.delegate = requireNonNull(delegate);
36     }
37
38     @NonNull DOMDataTreeReadWriteTransaction getTransaction() {
39         return delegate;
40     }
41
42     DOMDataTreeReadWriteTransaction getFrontendTransaction() {
43         return frontendTransaction;
44     }
45
46     @NonNull FluentFuture<? extends CommitInfo> completionFuture() {
47         return fluent;
48     }
49
50     @Override
51     public void onSuccess(final CommitInfo result) {
52         future.set(result);
53     }
54
55     @Override
56     public void onFailure(final Throwable throwable) {
57         future.setException(throwable);
58     }
59
60     void recordFrontendTransaction(final DOMDataTreeReadWriteTransaction tx) {
61         if (frontendTransaction == null) {
62             frontendTransaction = requireNonNull(tx);
63         }
64     }
65
66     @Override
67     public String toString() {
68         return MoreObjects.toStringHelper(this).add("delegate", delegate).toString();
69     }
70 }