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.robotninjas.concurrent.FluentFutureTask.java

@Override
public <E extends Exception> FluentCheckedFuture<V, E> makeChecked(Function<Exception, E> func) {
    return new CheckedDecorator<>(Futures.makeChecked(this, func));
}

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

@Nonnull
@Override/*from  ww  w. ja v a  2s  .  co m*/
public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
        @Nullable final NormalizedNode<?, ?> input) {
    final NetconfMessage message = transformer.toRpcRequest(type, input);
    final ListenableFuture<RpcResult<NetconfMessage>> delegateFutureWithPureResult = listener
            .sendRequest(message, type.getLastComponent());

    final ListenableFuture<DOMRpcResult> transformed = Futures.transform(delegateFutureWithPureResult,
            new Function<RpcResult<NetconfMessage>, DOMRpcResult>() {
                @Override
                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", type);
        }
    });
}

From source file:org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceRpc.java

@Nonnull
@Override//  w  w w  .  j  av  a 2  s  .c  o m
public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
        @Nullable final NormalizedNode<?, ?> input) {
    final NetconfMessage message = transformer.toRpcRequest(type, input);
    final ListenableFuture<RpcResult<NetconfMessage>> delegateFutureWithPureResult = listener
            .sendRequest(message, type.getLastComponent());

    final ListenableFuture<DOMRpcResult> transformed = Futures.transform(delegateFutureWithPureResult,
            new Function<RpcResult<NetconfMessage>, DOMRpcResult>() {
                @Override
                public DOMRpcResult apply(final RpcResult<NetconfMessage> input) {
                    if (input.isSuccessful()) {
                        return transformer.toRpcResult(input.getResult(), type);
                    } else {
                        // TODO check whether the listener sets errors properly
                        return new DefaultDOMRpcResult(input.getErrors());
                    }
                }
            });

    return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
        @Nullable
        @Override
        public DOMRpcException apply(@Nullable final Exception e) {
            // FIXME what other possible exceptions are there ?
            return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s", type);
        }
    });
}

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

@Override
public CheckedFuture<Void, TransactionCommitFailedException> submit() {
    checkRunning();//from www. j a v  a2s  .c  om
    LOG.debug("{}: Submitting transaction", txIdentifier);
    if (!initialized) {
        // If underlying producers, transactions and cursors are
        // not even initialized just seal this transaction and
        // return immediate future
        finished = true;
        return Futures.immediateCheckedFuture(null);
    }
    // First we need to close cursors
    cursorMap.values().forEach(DOMDataTreeWriteCursor::close);
    final ListenableFuture<List<Void>> aggregatedSubmit = Futures.allAsList(
            transactionMap.get(LogicalDatastoreType.CONFIGURATION).submit(),
            transactionMap.get(LogicalDatastoreType.OPERATIONAL).submit());

    // Now we can close producers and mark transaction as finished
    closeProducers();
    finished = true;

    return Futures.makeChecked(Futures.transform(aggregatedSubmit, (List<Void> input) -> input.get(0)),
            TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
}

From source file:org.opendaylight.netconf.topology.pipeline.tx.ProxyReadOnlyTransaction.java

@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    final Future<Boolean> existsFuture = delegate.exists(store, path);
    final SettableFuture<Boolean> settableFuture = SettableFuture.create();
    final CheckedFuture<Boolean, ReadFailedException> checkedFuture = Futures.makeChecked(settableFuture,
            new Function<Exception, ReadFailedException>() {
                @Nullable/*from w  w w  . ja  v  a2 s .com*/
                @Override
                public ReadFailedException apply(Exception cause) {
                    return new ReadFailedException("Read from transaction failed", cause);
                }
            });
    existsFuture.onComplete(new OnComplete<Boolean>() {
        @Override
        public void onComplete(Throwable throwable, Boolean result) throws Throwable {
            if (throwable == null) {
                settableFuture.set(result);
            } else {
                settableFuture.setException(throwable);
            }
        }
    }, actorSystem.dispatcher());
    return checkedFuture;
}

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

/**
 * @return ParallelStrategy instance which create single thread for on every
 *         call//from   w w w .  ja v  a 2s .  c  o m
 */
public static <T> ParallelStrategy<T> separateThreadStrategy() {
    return toCheckedStrategy(new ConclusionFunction<Callable<T>, CheckedFuture<T, PhraseExecutionException>>() {
        @Override
        public CheckedFuture<T, PhraseExecutionException> apply(Callable<T> input) {
            final ListenableFutureTask<T> task = ListenableFutureTask.create(input);
            new Thread(task).start();
            Function<Exception, PhraseExecutionException> mapper = ParallelStrategy
                    .createMapper(PhraseErrorCode.ERROR, new String[] { "singleThreadStrategy" });
            return Futures.makeChecked(task, mapper);
        }
    });
}

From source file:org.opendaylight.controller.md.sal.binding.impl.BindingRpcImplementationAdapter.java

private CheckedFuture<DOMRpcResult, DOMRpcException> transformResult(final SchemaPath schemaPath,
        final ListenableFuture<RpcResult<?>> bindingResult) {
    final ListenableFuture<DOMRpcResult> transformed = Futures.transform(bindingResult, lazySerializedMapper);
    return Futures.makeChecked(transformed, EXCEPTION_MAPPER);
}

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

@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    checkRunning();//from w  ww .  j a  v  a2  s. c om
    LOG.debug("{}: Invoking read at {}:{}", txIdentifier, store, path);
    final ListenerRegistration<DOMDataTreeListener> reg;
    final SettableFuture<Optional<NormalizedNode<?, ?>>> initialDataTreeChangeFuture = SettableFuture.create();
    try {
        reg = service.registerListener(new ReadShardedListener(initialDataTreeChangeFuture),
                Collections.singleton(new DOMDataTreeIdentifier(store, path)), false, Collections.emptyList());
        registrations.add(reg);
    } catch (final DOMDataTreeLoopException e) {
        // This should not happen, we are not specifying any
        // producers when registering listener
        throw new IllegalStateException("Loop in listener and producers detected", e);
    }

    // After data tree change future is finished, we can close the listener registration
    Futures.addCallback(initialDataTreeChangeFuture, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
        @Override
        public void onSuccess(@Nullable final Optional<NormalizedNode<?, ?>> result) {
            reg.close();
        }

        @Override
        public void onFailure(final Throwable throwable) {
            reg.close();
        }
    });

    return Futures.makeChecked(initialDataTreeChangeFuture, ReadFailedException.MAPPER);
}

From source file:org.opendaylight.netconf.topology.singleton.impl.tx.NetconfReadOnlyTransaction.java

@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {

    LOG.trace("{}: Exists {} via NETCONF: {}", id, store, path);

    final Future<Boolean> existsFuture = delegate.exists(store, path);
    final SettableFuture<Boolean> settableFuture = SettableFuture.create();
    final CheckedFuture<Boolean, ReadFailedException> checkedFuture;
    checkedFuture = Futures.makeChecked(settableFuture, new Function<Exception, ReadFailedException>() {
        @Nullable/*from  w  ww  . j ava 2s .c om*/
        @Override
        public ReadFailedException apply(Exception cause) {
            return new ReadFailedException("Read from transaction failed", cause);
        }
    });
    existsFuture.onComplete(new OnComplete<Boolean>() {
        @Override
        public void onComplete(final Throwable throwable, final Boolean result) throws Throwable {
            if (throwable == null) {
                settableFuture.set(result);
            } else {
                settableFuture.setException(throwable);
            }
        }
    }, actorSystem.dispatcher());
    return checkedFuture;
}

From source file:org.opendaylight.controller.sal.connect.netconf.sal.tx.WriteRunningTx.java

@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
    final ListenableFuture<Void> commmitFutureAsVoid = Futures.transform(commit(),
            new Function<RpcResult<TransactionStatus>, Void>() {
                @Override//  w  ww. j a  v a  2 s .  com
                public Void apply(final RpcResult<TransactionStatus> input) {
                    return null;
                }
            });

    return Futures.makeChecked(commmitFutureAsVoid,
            new Function<Exception, TransactionCommitFailedException>() {
                @Override
                public TransactionCommitFailedException apply(final Exception input) {
                    return new TransactionCommitFailedException(
                            "Submit of transaction " + getIdentifier() + " failed", input);
                }
            });
}