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 javax.annotation.Nullable;
14 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
21 * Add callback for future objects and result set to the data factory.
24 final class FutureCallbackTx {
26 private final static Logger LOG = LoggerFactory.getLogger(FutureCallbackTx.class);
28 private FutureCallbackTx() {
29 throw new UnsupportedOperationException("Util class");
33 * Add callback to the future object
35 * @param listenableFuture
38 * - transaction used for read of future object
40 * - type of operation (READ, POST, PUT, DELETE)
42 * - factory setting result
44 static <T, X extends Exception> void addCallback(final CheckedFuture<T, X> listenableFuture,
45 final AsyncTransaction<YangInstanceIdentifier, NormalizedNode<?, ?>> transaction, final String txType,
46 final FutureDataFactory<T> dataFactory) {
47 Futures.addCallback(listenableFuture, new FutureCallback<T>() {
50 public void onFailure(final Throwable t) {
51 handlingLoggerAndValues(t, txType, transaction, null, null);
55 public void onSuccess(final T result) {
56 handlingLoggerAndValues(null, txType, transaction, result, dataFactory);
63 * Handling logger and result of callback - on success or on failure
65 * <li>on success - set result to the factory
66 * <li>on failure - throw exception
70 * - exception - if callback is onFailure
72 * - type of operation (READ, POST, PUT, DELETE)
74 * - transaction used for read of future object
76 * - result - if callback is on Success
78 * - setter for result - in callback is onSuccess
80 protected static <T> void handlingLoggerAndValues(@Nullable final Throwable t, final String txType,
81 final AsyncTransaction<YangInstanceIdentifier, NormalizedNode<?, ?>> transaction,
82 final T result, final FutureDataFactory<T> dataFactory) {
84 LOG.info("Transaction({}) {} FAILED!", txType, transaction.getIdentifier(), t);
85 throw new IllegalStateException(" Transaction(" + txType + ") not committed correctly", t);
87 LOG.trace("Transaction({}) {} SUCCESSFUL!", txType, transaction.getIdentifier());
88 dataFactory.setResult(result);