ManagedTransactionRunner utility to help close transactions
[genius.git] / mdsalutil / mdsalutil-api / src / main / java / org / opendaylight / genius / infra / ManagedNewTransactionRunnerImpl.java
1 /*
2  * Copyright (c) 2017 Red Hat, 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.genius.infra;
9
10 import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
11
12 import com.google.common.util.concurrent.ListenableFuture;
13 import javax.inject.Inject;
14 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
15 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 /**
20  * Implementation of {@link ManagedNewTransactionRunner}.
21  */
22 // Do *NOT* mark this as @Singleton, even though it technically is, as long as this in API, because of https://wiki.opendaylight.org/view/BestPractices/DI_Guidelines#Nota_Bene
23 public class ManagedNewTransactionRunnerImpl implements ManagedNewTransactionRunner {
24
25     private static final Logger LOG = LoggerFactory.getLogger(ManagedNewTransactionRunnerImpl.class);
26
27     private final DataBroker broker;
28
29     @Inject
30     public ManagedNewTransactionRunnerImpl(DataBroker broker) {
31         this.broker = broker;
32     }
33
34     @Override
35     @SuppressWarnings("checkstyle:IllegalCatch")
36     public ListenableFuture<Void> callWithNewWriteOnlyTransactionAndSubmit(CheckedConsumer<WriteTransaction> txCnsmr) {
37         WriteTransaction realTx = broker.newWriteOnlyTransaction();
38         WriteTransaction wrappedTx = new NonSubmitCancelableWriteTransaction(realTx);
39         try {
40             txCnsmr.accept(wrappedTx);
41             return realTx.submit();
42         } catch (Exception e) {
43             if (!realTx.cancel()) {
44                 LOG.error("Transaction.cancel() return false - this should never happen (here)");
45             }
46             return immediateFailedFuture(e);
47         }
48     }
49
50 }