2 * Copyright (c) 2016 Cisco Systems, 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.restconf.restful.utils;
10 import com.google.common.util.concurrent.CheckedFuture;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import java.util.concurrent.CountDownLatch;
14 import javax.annotation.Nullable;
15 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
20 * Add callback for future objects and result set to the data factory.
23 final class FutureCallbackTx {
25 private final static Logger LOG = LoggerFactory.getLogger(FutureCallbackTx.class);
27 private FutureCallbackTx() {
28 throw new UnsupportedOperationException("Util class");
32 * Add callback to the future object
34 * @param listenableFuture
37 * - type of operation (READ, POST, PUT, DELETE)
39 * - factory setting result
41 static <T, X extends Exception> void addCallback(final CheckedFuture<T, X> listenableFuture, final String txType,
42 final FutureDataFactory<T> dataFactory) {
43 final CountDownLatch responseWaiter = new CountDownLatch(1);
44 Futures.addCallback(listenableFuture, new FutureCallback<T>() {
47 public void onFailure(final Throwable t) {
48 responseWaiter.countDown();
49 handlingLoggerAndValues(t, txType, null, null);
53 public void onSuccess(final T result) {
54 handlingLoggerAndValues(null, txType, result, dataFactory);
55 responseWaiter.countDown();
60 responseWaiter.await();
61 } catch (final Exception e) {
62 final String msg = "Problem while waiting for response";
64 throw new RestconfDocumentedException(msg, e);
69 * Handling logger and result of callback - on success or on failure
71 * <li>on success - set result to the factory
72 * <li>on failure - throw exception
76 * - exception - if callback is onFailure
78 * - type of operation (READ, POST, PUT, DELETE)
80 * - result of future - if callback is on Success
82 * - setter for result - in callback is onSuccess
84 protected static <T> void handlingLoggerAndValues(@Nullable final Throwable t, final String txType,
85 final T result, final FutureDataFactory<T> dataFactory) {
87 LOG.warn("Transaction({}) FAILED!", txType, t);
88 throw new RestconfDocumentedException(" Transaction(" + txType + ") not committed correctly", t);
90 LOG.trace("Transaction({}) SUCCESSFUL!", txType);
91 dataFactory.setResult(result);