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

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

Introduction

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

Prototype

@CheckReturnValue
public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable) 

Source Link

Document

Returns a ListenableFuture which has an exception set immediately upon construction.

Usage

From source file:com.microsoft.azure.keyvault.cryptography.RsaKey.java

@Override
public ListenableFuture<byte[]> decryptAsync(final byte[] ciphertext, final byte[] iv,
        final byte[] authenticationData, final byte[] authenticationTag, final String algorithm)
        throws NoSuchAlgorithmException {

    if (ciphertext == null) {
        throw new IllegalArgumentException("ciphertext");
    }//from w w w  .  java2  s.  c o m

    // Interpret the requested algorithm
    if (Strings.isNullOrWhiteSpace(algorithm)) {
        throw new IllegalArgumentException("algorithm");
    }

    Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm);

    if (baseAlgorithm == null || !(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) {
        throw new NoSuchAlgorithmException(algorithm);
    }

    AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm) baseAlgorithm;

    ICryptoTransform transform;
    ListenableFuture<byte[]> result;

    try {
        transform = algo.CreateDecryptor(_keyPair, _provider);
        result = Futures.immediateFuture(transform.doFinal(ciphertext));
    } catch (Exception e) {
        result = Futures.immediateFailedFuture(e);
    }

    return result;
}

From source file:com.vmware.photon.controller.common.zookeeper.AbstractServiceNode.java

/**
 * Joins a cluster defined by child nodes of a Zookeeper znode. Returns a promise that gets fulfilled
 * when this node has finished joining the cluster. The promise returns a Lease object that client code
 * can use to get expiration promise (the one that gets fulfilled when this particular membership gets
 * recalled b/c of ZK connection loss).//from w w w.  j  a  va  2s. c om
 */
@Override
public synchronized ListenableFuture<Lease> join() {
    logger.debug("Attempting to join cluster: {}", this);

    if (state == State.JOINED) {
        return Futures.immediateFailedFuture(new IllegalStateException("Node has already joined"));
    }

    final SettableFuture<Lease> leasePromise = SettableFuture.create();

    try {
        Futures.addCallback(joinCondition(), new FutureCallback<Void>() {
            @Override
            public void onSuccess(Void result) {
                state = State.JOINED;
                handleSuccessfulJoinCondition(leasePromise);
            }

            @Override
            public void onFailure(Throwable t) {
                leasePromise.setException(t);
            }
        });
    } catch (Exception e) {
        leasePromise.setException(e);
    }

    return leasePromise;
}

From source file:io.crate.operation.collect.HandlerSideDataCollectOperation.java

@Override
public ListenableFuture<Object[][]> collect(CollectNode collectNode,
        RamAccountingContext ramAccountingContext) {
    if (collectNode.isPartitioned()) {
        // edge case: partitioned table without actual indices
        // no results
        return Futures.immediateFuture(TaskResult.EMPTY_RESULT.rows());
    }//from   w w  w .j  av a  2  s. c om
    if (collectNode.maxRowGranularity() == RowGranularity.DOC) {
        // we assume information schema here
        return handleWithService(informationSchemaCollectService, collectNode, ramAccountingContext);
    } else if (collectNode.maxRowGranularity() == RowGranularity.CLUSTER) {
        return handleCluster(collectNode, ramAccountingContext);
    } else if (collectNode.maxRowGranularity() == RowGranularity.SHARD) {
        return handleWithService(unassignedShardsCollectService, collectNode, ramAccountingContext);
    } else {
        return Futures.immediateFailedFuture(new IllegalStateException("unsupported routing"));
    }
}

From source file:co.cask.cdap.internal.app.deploy.SandboxConfigurator.java

/**
 * Runs the <code>Application.configure()</code> in a sandbox JVM
 * with high level of security.// w  w  w.  j  av  a  2s  . c o  m
 *
 * @return An instance of {@link ListenableFuture}
 */
@Override
public ListenableFuture<ConfigResponse> config() {
    final SettableFuture<ConfigResponse> result = SettableFuture.create();
    final File outputFile;

    try {
        outputFile = File.createTempFile(PREFIX, EXT);

        // Run the command in seperate JVM.
        process = Runtime.getRuntime().exec(getCommand(outputFile));

        // Add future to handle the case when the future is cancelled.
        // OnSuccess, we don't do anything other than cleaning the output.
        // onFailure, we make sure that process is destroyed.
        Futures.addCallback(result, new FutureCallback<ConfigResponse>() {

            private void deleteOutput() {
                if (outputFile.exists()) {
                    outputFile.delete();
                }
            }

            @Override
            public void onSuccess(final ConfigResponse result) {
                // Delete the output file on delete.
                deleteOutput();
            }

            @Override
            public void onFailure(final Throwable t) {
                // In case the future was cancelled, we have to
                // destroy the process.
                if (result.isCancelled()) {
                    process.destroy();
                }
                deleteOutput();
            }
        });
    } catch (Exception e) {
        // Returns a {@code ListenableFuture} which has an exception set immediately
        // upon construction.
        return Futures.immediateFailedFuture(e);
    }

    // Start a thread that waits for command execution to complete or till it's cancelled.
    new Thread() {
        @Override
        public void run() {
            try {
                // Wait for process to exit and extract the return. If cancelled the process will
                // be shutdown.
                process.waitFor();
                int exit = process.exitValue();
                if (exit == 0) {
                    result.set(
                            new DefaultConfigResponse(0, Files.newReaderSupplier(outputFile, Charsets.UTF_8)));
                } else {
                    result.set(new DefaultConfigResponse(exit, null));
                }
            } catch (Exception e) {
                result.setException(e);
            }
        }
    }.start();

    return result;
}

From source file:io.v.x.jni.test.fortune.FortuneServerImpl.java

@Override
public ListenableFuture<Integer> streamingGet(final VContext context, ServerCall call,
        final ServerStream<String, Boolean> stream) {
    final SettableFuture<Integer> future = SettableFuture.create();
    final AtomicInteger numSent = new AtomicInteger(0);
    Futures.addCallback(InputChannels.withCallback(stream, new InputChannelCallback<Boolean>() {
        @Override//www  .  ja v  a  2  s  . c om
        public ListenableFuture<Void> onNext(Boolean result) {
            if (lastAddedFortune == null) {
                return Futures.immediateFailedFuture(new NoFortunesException(context));
            }
            return Futures.transform(stream.send(lastAddedFortune), new Function<Void, Void>() {
                @Override
                public Void apply(Void input) {
                    numSent.incrementAndGet();
                    return null;
                }
            });
        }
    }), new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            future.set(numSent.get());
        }

        @Override
        public void onFailure(Throwable t) {
            future.setException(t);
        }
    });
    return future;
}

From source file:org.opendaylight.protocol.bgp.openconfig.impl.moduleconfig.TableTypesFunction.java

@Override
public ListenableFuture<List<T>> apply(final List<AfiSafi> afiSafis) {
    final ListenableFuture<Optional<Service>> readFuture = configModuleWriter
            .readConfigService(new ServiceKey(BgpTableType.class), rTx);
    return Futures.transform(readFuture, new AsyncFunction<Optional<Service>, List<T>>() {

        @Override/* ww w .  j a v  a  2s.c  om*/
        public ListenableFuture<List<T>> apply(final Optional<Service> maybeService) {
            if (maybeService.isPresent()) {
                final Service service = maybeService.get();
                final List<ListenableFuture<Optional<Module>>> modulesFuture = new ArrayList<>();
                final Map<String, String> moduleNameToService = new HashMap<>();
                for (final Instance instance : service.getInstance()) {
                    final String moduleName = OpenConfigUtil.getModuleName(instance.getProvider());
                    modulesFuture.add(configModuleWriter
                            .readModuleConfiguration(new ModuleKey(moduleName, BgpTableTypeImpl.class), rTx));
                    moduleNameToService.put(moduleName, instance.getName());
                }
                return Futures.transform(Futures.successfulAsList(modulesFuture),
                        new ModulesToLocalTablesFunction(afiSafis, moduleNameToService));
            }
            return Futures.immediateFailedFuture(
                    new IllegalStateException("No BgpTableType service present in configuration."));
        }

    });
}

From source file:co.cask.tigon.internal.app.runtime.AbstractProgramController.java

@Override
public final ListenableFuture<ProgramController> stop() {
    if (!state.compareAndSet(State.STARTING, State.STOPPING)
            && !state.compareAndSet(State.ALIVE, State.STOPPING)
            && !state.compareAndSet(State.SUSPENDED, State.STOPPING)) {
        return Futures
                .immediateFailedFuture(new IllegalStateException("Resumption not allowed").fillInStackTrace());
    }/*from   ww w.ja  v a  2  s .  co  m*/
    final SettableFuture<ProgramController> result = SettableFuture.create();
    executor(State.STOPPING).execute(new Runnable() {
        @Override
        public void run() {
            try {
                caller.stopping();
                doStop();
                state.set(State.STOPPED);
                result.set(AbstractProgramController.this);
                caller.stopped();
            } catch (Throwable t) {
                error(t, result);
            }
        }
    });
    return result;
}

From source file:dagger.producers.internal.Producers.java

/** Returns a producer that fails with the given exception. */
public static <T> Producer<T> immediateFailedProducer(final Throwable throwable) {
    return new Producer<T>() {
        @Override/*from   w w w. ja v  a2  s .co  m*/
        public ListenableFuture<T> get() {
            return Futures.immediateFailedFuture(throwable);
        }
    };
}

From source file:org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMStoreThreePhaseCommitCohort.java

@Override
public final ListenableFuture<Void> preCommit() {
    try {//from   w  w w  . ja  va 2  s.c  o m
        candidate = store.prepare(modification);
        return SUCCESSFUL_FUTURE;
    } catch (Exception e) {
        LOG.warn("Unexpected failure in pre-commit phase", e);
        return Futures.immediateFailedFuture(e);
    }
}

From source file:com.orangerhymelabs.helenus.cassandra.AbstractCassandraRepository.java

public ListenableFuture<T> update(T entity) {
    ListenableFuture<ResultSet> future = submitUpdate(entity);
    return Futures.transformAsync(future, new AsyncFunction<ResultSet, T>() {
        @Override/*  ww  w . j  ava 2  s .c o m*/
        public ListenableFuture<T> apply(ResultSet result) {
            if (result.wasApplied()) {
                return Futures.immediateFuture(entity);
            }

            return Futures.immediateFailedFuture(new ItemNotFoundException(entity.toString()));
        }
    }, MoreExecutors.directExecutor());
}