2 * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved.
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
8 package org.opendaylight.genius.infra;
10 import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
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.ReadWriteTransaction;
16 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
21 * Implementation of {@link ManagedNewTransactionRunner}.
23 // 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
24 public class ManagedNewTransactionRunnerImpl implements ManagedNewTransactionRunner {
26 private static final Logger LOG = LoggerFactory.getLogger(ManagedNewTransactionRunnerImpl.class);
28 private final DataBroker broker;
31 public ManagedNewTransactionRunnerImpl(DataBroker broker) {
36 @SuppressWarnings("checkstyle:IllegalCatch")
37 public ListenableFuture<Void> callWithNewWriteOnlyTransactionAndSubmit(CheckedConsumer<WriteTransaction> txCnsmr) {
38 WriteTransaction realTx = broker.newWriteOnlyTransaction();
39 WriteTransaction wrappedTx = new NonSubmitCancelableWriteTransaction(realTx);
41 txCnsmr.accept(wrappedTx);
42 return realTx.submit();
43 } catch (Exception e) {
44 if (!realTx.cancel()) {
45 LOG.error("Transaction.cancel() return false - this should never happen (here)");
47 return immediateFailedFuture(e);
52 @SuppressWarnings("checkstyle:IllegalCatch")
53 public ListenableFuture<Void> callWithNewReadWriteTransactionAndSubmit(
54 CheckedConsumer<ReadWriteTransaction> txRunner) {
55 ReadWriteTransaction realTx = broker.newReadWriteTransaction();
56 ReadWriteTransaction wrappedTx = new NonSubmitCancelableReadWriteTransaction(realTx);
58 txRunner.accept(wrappedTx);
59 return realTx.submit();
60 } catch (Exception e) {
61 if (!realTx.cancel()) {
62 LOG.error("Transaction.cancel() returned false, which should never happen here");
64 return immediateFailedFuture(e);