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.annotations.Beta;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import javax.inject.Inject;
15 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
16 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
17 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
18 import org.opendaylight.infrautils.utils.function.CheckedConsumer;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
23 * Implementation of {@link ManagedNewTransactionRunner}.
26 // Do *NOT* mark this as @Singleton, because users choose Impl; and as long as this in API, because of https://wiki.opendaylight.org/view/BestPractices/DI_Guidelines#Nota_Bene
27 public class ManagedNewTransactionRunnerImpl implements ManagedNewTransactionRunner {
29 private static final Logger LOG = LoggerFactory.getLogger(ManagedNewTransactionRunnerImpl.class);
31 private final DataBroker broker;
34 public ManagedNewTransactionRunnerImpl(DataBroker broker) {
39 @SuppressWarnings("checkstyle:IllegalCatch")
40 public <E extends Exception> ListenableFuture<Void>
41 callWithNewWriteOnlyTransactionAndSubmit(CheckedConsumer<WriteTransaction, E> txCnsmr) {
42 WriteTransaction realTx = broker.newWriteOnlyTransaction();
43 WriteTransaction wrappedTx = new NonSubmitCancelableWriteTransaction(realTx);
45 txCnsmr.accept(wrappedTx);
46 return realTx.submit();
47 // catch Exception for both the <E extends Exception> thrown by accept() as well as any RuntimeException
48 } catch (Exception e) {
49 if (!realTx.cancel()) {
50 LOG.error("Transaction.cancel() return false - this should never happen (here)");
52 return immediateFailedFuture(e);
57 @SuppressWarnings("checkstyle:IllegalCatch")
58 public <E extends Exception> ListenableFuture<Void>
59 callWithNewReadWriteTransactionAndSubmit(CheckedConsumer<ReadWriteTransaction, E> txRunner) {
60 ReadWriteTransaction realTx = broker.newReadWriteTransaction();
61 ReadWriteTransaction wrappedTx = new NonSubmitCancelableReadWriteTransaction(realTx);
63 txRunner.accept(wrappedTx);
64 return realTx.submit();
65 // catch Exception for both the <E extends Exception> thrown by accept() as well as any RuntimeException
66 } catch (Exception e) {
67 if (!realTx.cancel()) {
68 LOG.error("Transaction.cancel() returned false, which should never happen here");
70 return immediateFailedFuture(e);