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.orangerhymelabs.helenus.cassandra.document.DocumentRepository.java

public ListenableFuture<Document> upsert(Document entity) {
    ListenableFuture<ResultSet> future = submitUpsert(entity);
    return Futures.transformAsync(future, new AsyncFunction<ResultSet, Document>() {
        @Override//from   w  ww. j  a  va  2  s .  c om
        public ListenableFuture<Document> apply(ResultSet result) throws Exception {
            if (result.wasApplied()) {
                return Futures.immediateFuture(entity);
            }

            //TODO: This doesn't provide any informational value... what should it be?
            return Futures.immediateFailedFuture(new StorageException(String
                    .format("Table %s failed to store document: %s", table.toDbTable(), entity.toString())));
        }
    });
}

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

@Override
public ListenableFuture<byte[]> unwrapKeyAsync(final byte[] encryptedKey, final String algorithm)
        throws NoSuchAlgorithmException {

    if (Strings.isNullOrWhiteSpace(algorithm)) {
        throw new IllegalArgumentException("algorithm");
    }/*from  w  ww.  j a  v a  2 s  .  c  o  m*/

    if (encryptedKey == null || encryptedKey.length == 0) {
        throw new IllegalArgumentException("wrappedKey");
    }

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

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

    KeyWrapAlgorithm algo = (KeyWrapAlgorithm) baseAlgorithm;

    ICryptoTransform transform = null;

    try {
        transform = algo.CreateDecryptor(_key, null, _provider);
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }

    byte[] decrypted = null;

    try {
        decrypted = transform.doFinal(encryptedKey);
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }

    return Futures.immediateFuture(decrypted);
}

From source file:com.tinspx.util.concurrent.FutureUtils.java

/**
 * Returns the result of calling/*from ww w. ja v  a2 s  .  c  o  m*/
 * {@link AsyncFunction#apply(java.lang.Object) function.apply(input)}. Any
 * {@code Throwable} thrown from {@code apply} is returned in an failed
 * {@code ListenableFuture} instead of throwing the {@code Exception}.
 */
@SuppressWarnings({ "BroadCatchBlock", "TooBroadCatch", "unchecked" })
public static <I, O> ListenableFuture<O> apply(AsyncFunction<? super I, ? extends O> function, I input) {
    checkNotNull(function);
    try {
        return (ListenableFuture<O>) function.apply(input);
    } catch (Throwable ex) {
        return Futures.immediateFailedFuture(ex);
    }
}

From source file:org.voltdb.DefaultSnapshotDataTarget.java

private ListenableFuture<?> write(final Callable<BBContainer> tupleDataC, final boolean prependLength) {
    /*/*from  ww w  .  j  a  v a  2s.co  m*/
     * Unwrap the data to be written. For the traditional
     * snapshot data target this should be a noop.
     */
    BBContainer tupleDataTemp;
    try {
        tupleDataTemp = tupleDataC.call();
        /*
         * Can be null if the dedupe filter nulled out the buffer
         */
        if (tupleDataTemp == null) {
            return Futures.immediateFuture(null);
        }
    } catch (Throwable t) {
        return Futures.immediateFailedFuture(t);
    }
    final BBContainer tupleData = tupleDataTemp;

    if (m_writeFailed) {
        tupleData.discard();
        return null;
    }

    m_outstandingWriteTasks.incrementAndGet();

    Future<byte[]> compressionTask = null;
    if (prependLength) {
        tupleData.b.position(tupleData.b.position() + 12);
        compressionTask = CompressionService.compressBufferAsync(tupleData.b);
    }
    final Future<byte[]> compressionTaskFinal = compressionTask;

    ListenableFuture<?> writeTask = m_es.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            try {
                if (m_acceptOneWrite) {
                    m_acceptOneWrite = false;
                } else {
                    if (m_simulateBlockedWrite != null) {
                        m_simulateBlockedWrite.await();
                    }
                    if (m_simulateFullDiskWritingChunk) {
                        throw new IOException("Disk full");
                    }
                }

                int totalWritten = 0;
                if (prependLength) {
                    final ByteBuffer payloadBuffer = ByteBuffer.wrap(compressionTaskFinal.get());

                    ByteBuffer lengthPrefix = ByteBuffer.allocate(16);
                    m_bytesAllowedBeforeSync.acquire(payloadBuffer.remaining() + 16);
                    lengthPrefix.putInt(payloadBuffer.remaining());
                    lengthPrefix.putInt(tupleData.b.getInt(0));
                    lengthPrefix.putInt(tupleData.b.getInt(4));
                    lengthPrefix.putInt(tupleData.b.getInt(8));
                    lengthPrefix.flip();
                    while (lengthPrefix.hasRemaining()) {
                        totalWritten += m_channel.write(lengthPrefix);
                    }
                    while (payloadBuffer.hasRemaining()) {
                        totalWritten += m_channel.write(payloadBuffer);
                    }
                } else {
                    while (tupleData.b.hasRemaining()) {
                        totalWritten += m_channel.write(tupleData.b);
                    }
                }
                m_bytesWritten += totalWritten;
                m_bytesWrittenSinceLastSync.addAndGet(totalWritten);
            } catch (IOException e) {
                m_writeException = e;
                hostLog.error("Error while attempting to write snapshot data to file " + m_file, e);
                m_writeFailed = true;
                throw e;
            } finally {
                tupleData.discard();
                m_outstandingWriteTasksLock.lock();
                try {
                    if (m_outstandingWriteTasks.decrementAndGet() == 0) {
                        m_noMoreOutstandingWriteTasksCondition.signalAll();
                    }
                } finally {
                    m_outstandingWriteTasksLock.unlock();
                }
            }
            return null;
        }
    });
    return writeTask;
}

From source file:org.opendaylight.netconf.topology.AbstractNetconfTopology.java

@Override
public ListenableFuture<Void> disconnectNode(NodeId nodeId) {
    LOG.debug("Disconnecting RemoteDevice{{}}", nodeId.getValue());
    if (!activeConnectors.containsKey(nodeId)) {
        return Futures.immediateFailedFuture(
                new IllegalStateException("Unable to disconnect device that is not connected"));
    }//from w ww  .  j a v a 2s.c o  m

    // retrieve connection, and disconnect it
    final NetconfConnectorDTO connectorDTO = activeConnectors.remove(nodeId);
    connectorDTO.getCommunicator().close();
    connectorDTO.getFacade().close();
    return Futures.immediateFuture(null);
}

From source file:com.orangerhymelabs.helenus.cassandra.document.DocumentService.java

public ListenableFuture<Document> upsert(String database, String table, Document document) {
    ListenableFuture<AbstractDocumentRepository> docs = acquireRepositoryFor(database, table);
    return Futures.transformAsync(docs, new AsyncFunction<AbstractDocumentRepository, Document>() {
        @Override/*from ww w  .ja v  a  2s .c  o m*/
        public ListenableFuture<Document> apply(AbstractDocumentRepository input) throws Exception {
            try {
                ValidationEngine.validateAndThrow(document);
                return input.upsert(document);
            } catch (ValidationException e) {
                return Futures.immediateFailedFuture(e);
            }
        }
    }, MoreExecutors.directExecutor());
}

From source file:io.v.android.security.BlessingsManager.java

private static ListenableFuture<Blessings> wrapWithSetAsDefault(final VContext ctx, final Context context,
        ListenableFuture<Blessings> future) {
    return Futures.transform(future, new AsyncFunction<Blessings, Blessings>() {
        @Override/*w  ww  .  ja va 2s  . c  o m*/
        public ListenableFuture<Blessings> apply(Blessings blessings) throws Exception {
            if (ctx.isCanceled()) {
                return Futures.immediateFailedFuture(new VException("Vanadium context canceled"));
            }
            // Update local state with the new blessings.
            try {
                VPrincipal p = V.getPrincipal(ctx);
                p.blessingStore().setDefaultBlessings(blessings);
                p.blessingStore().set(blessings, Constants.ALL_PRINCIPALS);
                VSecurity.addToRoots(p, blessings);
                return Futures.immediateFuture(blessings);
            } catch (VException e) {
                return Futures.immediateFailedFuture(e);
            }
        }
    });
}

From source file:com.google.cloud.bigtable.grpc.async.v2.AsyncExecutor.java

private <ResponseT, RequestT extends GeneratedMessage> ListenableFuture<ResponseT> call(
        AsyncCall<RequestT, ResponseT> rpc, RequestT request, long id) {
    ListenableFuture<ResponseT> future;
    try {/*from   ww w. j  a  va2  s  . co  m*/
        future = rpc.call(client, request);
    } catch (Exception e) {
        future = Futures.immediateFailedFuture(e);
    }
    rpcThrottler.addCallback(future, id);
    return future;
}

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

@Override
public ListenableFuture<Pair<byte[], String>> signAsync(final byte[] digest, final String algorithm) {
    return Futures.immediateFailedFuture(new NotImplementedException("signAsync is not currently supported"));
}

From source file:io.v.v23.rpc.ReflectInvoker.java

private static ListenableFuture<Object[]> prepareReply(final ServerMethod m, Object resultFuture) {
    if (resultFuture == null) {
        return Futures.immediateFailedFuture(new VException(String
                .format("Server method %s returned NULL ListenableFuture.", m.getReflectMethod().getName())));
    }//  ww w. jav  a2s. com
    if (!(resultFuture instanceof ListenableFuture)) {
        return Futures.immediateFailedFuture(new VException(String
                .format("Server method %s didn't return a ListenableFuture.", m.getReflectMethod().getName())));
    }
    return Futures.transform((ListenableFuture<?>) resultFuture, new AsyncFunction<Object, Object[]>() {
        @Override
        public ListenableFuture<Object[]> apply(Object result) throws Exception {
            Type[] resultTypes = m.getResultTypes();
            switch (resultTypes.length) {
            case 0:
                return Futures.immediateFuture(new Object[0]); // Void
            case 1:
                return Futures.immediateFuture(new Object[] { result });
            default: { // Multiple return values.
                Class<?> returnType = (Class<?>) m.getReturnType();
                Field[] fields = returnType.getFields();
                Object[] reply = new Object[fields.length];
                for (int i = 0; i < fields.length; i++) {
                    try {
                        reply[i] = result != null ? fields[i].get(result) : null;
                    } catch (IllegalAccessException e) {
                        throw new VException("Couldn't get field: " + e.getMessage());
                    }
                }
                return Futures.immediateFuture(reply);
            }
            }
        }
    });
}