Example usage for com.google.common.util.concurrent Futures makeChecked

List of usage examples for com.google.common.util.concurrent Futures makeChecked

Introduction

In this page you can find the example usage for com.google.common.util.concurrent Futures makeChecked.

Prototype

@GwtIncompatible("TODO")
@CheckReturnValue
public static <V, X extends Exception> CheckedFuture<V, X> makeChecked(ListenableFuture<V> future,
        Function<? super Exception, X> mapper) 

Source Link

Document

Creates a CheckedFuture out of a normal ListenableFuture and a Function that maps from Exception instances into the appropriate checked type.

Usage

From source file:org.opendaylight.netconf.sal.connect.netconf.sal.SchemalessNetconfDeviceRpc.java

private CheckedFuture<DOMRpcResult, DOMRpcException> handleRpc(@Nonnull final SchemaPath type,
        @Nullable final NormalizedNode<?, ?> input, final MessageTransformer<NetconfMessage> transformer) {
    final NetconfMessage netconfMessage = transformer.toRpcRequest(type, input);
    final ListenableFuture<RpcResult<NetconfMessage>> rpcResultListenableFuture = listener
            .sendRequest(netconfMessage, type.getLastComponent());

    final ListenableFuture<DOMRpcResult> transformed = Futures.transform(rpcResultListenableFuture,
            new Function<RpcResult<NetconfMessage>, DOMRpcResult>() {
                @Override/* w w w.  j a v a2  s.  c  o m*/
                public DOMRpcResult apply(final RpcResult<NetconfMessage> input) {
                    if (input.isSuccessful()) {
                        return transformer.toRpcResult(input.getResult(), type);
                    } else {
                        return new DefaultDOMRpcResult(input.getErrors());
                    }
                }
            });

    return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
        @Nullable
        @Override
        public DOMRpcException apply(@Nullable final Exception e) {
            return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s on device %s",
                    type, deviceId);
        }
    });
}

From source file:ru.rulex.conclusion.execution.ParallelStrategy.java

/**
 * //from   w w w . ja va 2  s.c  o m
 * @return ParallelStrategy<T, E> pStrategy
 */
public static <T> ParallelStrategy<T> serial() {
    return toCheckedStrategy(new ConclusionFunction<Callable<T>, CheckedFuture<T, PhraseExecutionException>>() {
        @Override
        public CheckedFuture<T, PhraseExecutionException> apply(Callable<T> input) {
            return Futures.makeChecked(SAME_THREAD_EXECUTOR.submit(input),
                    createMapper(PhraseErrorCode.ERROR, new String[] { "sameThreadStrategy" }));
        }
    });
}

From source file:org.opendaylight.distributed.tx.impl.RollbackImpl.java

private static CheckedFuture<Void, DTxException.RollbackFailedException> aggregateRollbackFutures(
        final List<ListenableFuture<Void>> perNodeRollbackSubmitFutures) {
    final ListenableFuture<Void> aggregatedRollbackSubmitFuture = Futures
            .transform(Futures.allAsList(perNodeRollbackSubmitFutures), new Function<List<Void>, Void>() {
                @Nullable//from   w ww  .  j  a v  a2  s .c  om
                @Override
                public Void apply(@Nullable final List<Void> input) {
                    return null;
                }
            });

    return Futures.makeChecked(aggregatedRollbackSubmitFuture,
            new Function<Exception, DTxException.RollbackFailedException>() {
                @Nullable
                @Override
                public DTxException.RollbackFailedException apply(final Exception input) {
                    return new DTxException.RollbackFailedException("Rollback submit failed", input);
                }
            });
}

From source file:org.opendaylight.mdsal.dom.broker.ShardedDOMReadTransactionAdapter.java

@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    checkRunning();/*from   ww w  .  j  a  v  a 2  s.c  o  m*/
    LOG.debug("{}: Invoking exists at {}:{}", txIdentifier, store, path);
    final Function<Optional<NormalizedNode<?, ?>>, Boolean> transform = optionalNode -> optionalNode.isPresent()
            ? Boolean.TRUE
            : Boolean.FALSE;
    final ListenableFuture<Boolean> existsResult = Futures.transform(read(store, path), transform);
    return Futures.makeChecked(existsResult, ReadFailedException.MAPPER);
}

From source file:ru.rulex.conclusion.execution.ParallelStrategy.java

/**
 * @return ParallelStrategy<T, E> pStrategy
 *//*from w  w  w .  j  a  v  a2  s .co m*/
public static <T> ParallelStrategy<T> listenableFutureStrategy(final ListeningExecutorService es) {
    return toCheckedStrategy(new ConclusionFunction<Callable<T>, CheckedFuture<T, PhraseExecutionException>>() {
        @Override
        public CheckedFuture<T, PhraseExecutionException> apply(Callable<T> task) {
            return Futures.makeChecked(es.submit(task), ParallelStrategy.createMapper(PhraseErrorCode.ERROR,
                    new String[] { "listenableFutureStrategy" }));
        }
    });
}

From source file:org.opendaylight.distributed.tx.impl.DTXTestTransaction.java

@Override
public <T extends DataObject> CheckedFuture<Optional<T>, ReadFailedException> read(
        LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<T> instanceIdentifier) {
    T obj = null;// w ww.  j  a  va2 s  .  co  m

    if (txDataMap.get(instanceIdentifier).size() > 0)
        obj = (T) txDataMap.get(instanceIdentifier).getFirst();

    final Optional<T> retOpt = Optional.fromNullable(obj);

    final SettableFuture<Optional<T>> retFuture = SettableFuture.create();
    Runnable readResult = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(delayTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            boolean readException = getAndResetExceptionWithInstanceIdentifier(readExceptionMap,
                    instanceIdentifier);
            if (readException == false) {
                retFuture.set(retOpt);
            } else {
                retFuture.setException(new Throwable("Read error"));
            }
            retFuture.notifyAll();
        }
    };

    new Thread(readResult).start();

    Function<Exception, ReadFailedException> f = new Function<Exception, ReadFailedException>() {
        @Nullable
        @Override
        public ReadFailedException apply(@Nullable Exception e) {
            return new ReadFailedException("Read failed", e);
        }
    };

    return Futures.makeChecked(retFuture, f);
}

From source file:org.opendaylight.openflowplugin.openflow.md.util.RoleUtil.java

/**
 * @param rolePushResult result of role push request
 * @return future which throws {@link RolePushException}
 *///from   w  w w. j a v a  2  s .  c o m
public static CheckedFuture<Boolean, RolePushException> makeCheckedRuleRequestFxResult(
        ListenableFuture<Boolean> rolePushResult) {
    return Futures.makeChecked(rolePushResult, exceptionFunction);
}

From source file:org.opendaylight.sxp.controller.core.DatastoreAccess.java

/**
 * @param path                 InstanceIdentifier path specifying data
 * @param data                 Data that will be used in operation
 * @param logicalDatastoreType Type of datastore where operation will be held
 * @param <T>                  Any type extending DataObject
 * @return CheckedFuture callback of operation
 */// w ww  .ja v  a  2 s.com
public synchronized <T extends DataObject> CheckedFuture<Void, TransactionCommitFailedException> merge(
        InstanceIdentifier<T> path, T data, LogicalDatastoreType logicalDatastoreType) {
    if (!checkParams(path, logicalDatastoreType)) {
        return Futures.makeChecked(Futures.immediateCancelledFuture(), input -> ACCESS_CLOSED_ON_RW);
    }
    Preconditions.checkNotNull(data);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Merge {} {}", logicalDatastoreType, path.getTargetType());
    }
    WriteTransaction transaction = bindingTransactionChain.newWriteOnlyTransaction();
    transaction.merge(logicalDatastoreType, path, data);
    return transaction.submit();

}

From source file:ru.rulex.conclusion.execution.ParallelStrategy.java

/**
 * //from  w  w w . j a v  a 2  s .c  o m
 * @return
 */
public static <T> ParallelStrategy<T> defaultListenableFutureStrategy() {
    return toCheckedStrategy(new ConclusionFunction<Callable<T>, CheckedFuture<T, PhraseExecutionException>>() {
        @Override
        public CheckedFuture<T, PhraseExecutionException> apply(Callable<T> task) {
            return Futures.makeChecked(COMPUTATION_EXECUTOR.submit(task), ParallelStrategy
                    .createMapper(PhraseErrorCode.ERROR, new String[] { "listenableFutureStrategy" }));
        }
    });
}

From source file:org.opendaylight.distributed.tx.impl.CachingReadWriteTx.java

public CheckedFuture<Void, DTxException> asyncDelete(final LogicalDatastoreType logicalDatastoreType,
        final InstanceIdentifier<?> instanceIdentifier) {
    increaseOperation();/*from   w  w  w  . ja  v  a2  s .c o m*/
    CheckedFuture<Optional<DataObject>, ReadFailedException> readFuture = null;
    try {
        readFuture = delegate.read(logicalDatastoreType, (InstanceIdentifier<DataObject>) instanceIdentifier);
    } catch (Exception e) {
        readFuture = Futures
                .immediateFailedCheckedFuture(new ReadFailedException("Read exception in delete action"));
    }

    final SettableFuture<Void> retFuture = SettableFuture.create();

    Futures.addCallback(readFuture, new FutureCallback<Optional<DataObject>>() {
        @Override
        public void onSuccess(final Optional<DataObject> result) {
            synchronized (this) {
                cache.add(new CachedData(logicalDatastoreType, instanceIdentifier, result.orNull(),
                        ModifyAction.DELETE));
            }

            final ListeningExecutorService executorService = MoreExecutors
                    .listeningDecorator(executorPoolPerCache);
            final ListenableFuture asyncDeleteFuture = executorService.submit(new Callable() {
                @Override
                public Object call() throws Exception {
                    delegate.delete(logicalDatastoreType, instanceIdentifier);
                    return null;
                }
            });

            Futures.addCallback(asyncDeleteFuture, new FutureCallback() {
                @Override
                public void onSuccess(@Nullable Object result) {
                    decreaseOperation();
                    retFuture.set(null);
                }

                @Override
                public void onFailure(Throwable t) {
                    decreaseOperation();
                    LOG.trace("async delete failure");
                    retFuture.setException(new DTxException.EditFailedException("async delete failure", t));
                }
            });
        }

        @Override
        public void onFailure(final Throwable t) {
            decreaseOperation();
            retFuture.setException(
                    new DTxException.ReadFailedException("failed to read from node in delete action", t));
        }
    });

    return Futures.makeChecked(retFuture, new Function<Exception, DTxException>() {
        @Nullable
        @Override
        public DTxException apply(@Nullable Exception e) {
            e = (Exception) e.getCause();
            return e instanceof DTxException ? (DTxException) e
                    : new DTxException("delete operation failed ", e);
        }
    });
}