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.historical.HistoricalDocumentRepository.java

public ListenableFuture<HistoricalDocument> upsert(HistoricalDocument entity) {
    ListenableFuture<ResultSet> future = submitUpsert(entity);
    return Futures.transformAsync(future, new AsyncFunction<ResultSet, HistoricalDocument>() {
        @Override//  w w  w  .j  ava 2 s  . c  o m
        public ListenableFuture<HistoricalDocument> 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())));
        }
    }, MoreExecutors.directExecutor());
}

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

public ListenableFuture<Document> update(String database, String table, Document document) {
    ListenableFuture<AbstractDocumentRepository> docs = acquireRepositoryFor(database, table);
    return Futures.transformAsync(docs, new AsyncFunction<AbstractDocumentRepository, Document>() {
        @Override/*w ww .j a va2s.co m*/
        public ListenableFuture<Document> apply(AbstractDocumentRepository input) throws Exception {
            try {
                ValidationEngine.validateAndThrow(document);
                return input.update(document);
            } catch (ValidationException e) {
                return Futures.immediateFailedFuture(e);
            }
        }
    }, MoreExecutors.directExecutor());
}

From source file:com.mypurecloud.sdk.v2.api.LicenseApiAsync.java

/**
 * Get license assignments for the organization.
 * /*from w  w w. j  ava  2  s  . c  o m*/
 * @param request the request object
 * @param callback the action to perform when the request is completed
 * @return the future indication when the request has completed
 */
public Future<LicenseOrganization> getLicenseOrganizationAsync(GetLicenseOrganizationRequest request,
        final AsyncApiCallback<LicenseOrganization> callback) {
    try {
        final SettableFuture<LicenseOrganization> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<LicenseOrganization>() {
        }, new AsyncApiCallback<ApiResponse<LicenseOrganization>>() {
            @Override
            public void onCompleted(ApiResponse<LicenseOrganization> response) {
                notifySuccess(future, callback, response.getBody());
            }

            @Override
            public void onFailed(Throwable exception) {
                if (shouldThrowErrors) {
                    notifyFailure(future, callback, exception);
                } else {
                    notifySuccess(future, callback, null);
                }
            }
        });
        return future;
    } catch (Throwable exception) {
        return Futures.immediateFailedFuture(exception);
    }
}

From source file:io.crate.executor.transport.AlterTableOperation.java

private ListenableFuture<Long> updateMapping(Map<String, Object> newMapping, String... indices) {
    if (newMapping.isEmpty()) {
        return Futures.immediateFuture(null);
    }/*from w  w w.  j  av  a  2  s .  co m*/
    assert areAllMappingsEqual(clusterService.state().metaData(),
            indices) : "Trying to update mapping for indices with different existing mappings";

    Map<String, Object> mapping;
    try {
        MetaData metaData = clusterService.state().metaData();
        String index = indices[0];
        mapping = metaData.index(index).mapping(Constants.DEFAULT_MAPPING_TYPE).getSourceAsMap();
    } catch (IOException e) {
        return Futures.immediateFailedFuture(e);
    }

    XContentHelper.update(mapping, newMapping, false);

    // update mapping of all indices
    PutMappingRequest request = new PutMappingRequest(indices);
    request.indicesOptions(IndicesOptions.lenientExpandOpen());
    request.type(Constants.DEFAULT_MAPPING_TYPE);
    request.source(mapping);

    FutureActionListener<PutMappingResponse, Long> listener = new FutureActionListener<>(LONG_NULL_FUNCTION);
    transportActionProvider.transportPutMappingAction().execute(request, listener);
    return listener;
}

From source file:org.caffinitas.ohc.linked.OHCacheImpl.java

public Future<V> getWithLoaderAsync(final K key, final CacheLoader<K, V> loader) {
    if (key == null)
        throw new NullPointerException();
    if (executorService == null || executorService.isShutdown() || closed)
        throw new IllegalStateException(
                "OHCache has no executor service - configure one via OHCacheBuilder.executorService()");

    final KeyBuffer keySource = keySource(key);

    final OffHeapMap segment = segment(keySource.hash());
    long hashEntryAdr = segment.getEntry(keySource, true);

    if (hashEntryAdr == 0L) {
        // this call is _likely_ the initial requestor for that key since there's no entry for the key

        final long keyLen = keySerializer.serializedSize(key);

        long bytes = Util.allocLen(keyLen, 0L);

        if ((maxEntrySize > 0L && bytes > maxEntrySize)
                || (hashEntryAdr = Uns.allocate(bytes, throwOOME)) == 0L) {
            // entry too large to be inserted or OS is not able to provide enough memory
            putFailCount++;/*from w w  w  .j  a v  a  2s  . com*/

            remove(key);

            return Futures
                    .immediateFailedFuture(new RuntimeException("max entry size exceeded or malloc() failed"));
        }

        try {
            keySerializer.serialize(key, Uns.keyBuffer(hashEntryAdr, keyLen));
        } catch (Throwable e) {
            freeAndThrow(e, hashEntryAdr);
        }

        final long hash = hasher.hash(hashEntryAdr, Util.ENTRY_OFF_DATA, (int) keyLen);

        // initialize hash entry
        HashEntries.init(hash, keyLen, 0L, hashEntryAdr, Util.SENTINEL_LOADING);

        if (segment.putEntry(hashEntryAdr, hash, keyLen, bytes, true, 0L, 0L, 0L)) {
            // this request IS the initial requestor for the key

            final long sentinelHashEntryAdr = hashEntryAdr;
            return executorService.submit(new Callable<V>() {
                public V call() throws Exception {
                    Exception failure = null;
                    V value = null;
                    boolean replaced = false;

                    try {
                        value = loader.load(key);

                        long valueLen = valueSerializer.serializedSize(value);

                        long bytes = Util.allocLen(keyLen, valueLen);

                        long hashEntryAdr;
                        if ((maxEntrySize > 0L && bytes > maxEntrySize)
                                || (hashEntryAdr = Uns.allocate(bytes, throwOOME)) == 0L)
                            throw new RuntimeException("max entry size exceeded or malloc() failed");

                        long hash = serializeForPut(key, value, keyLen, valueLen, hashEntryAdr);

                        // initialize hash entry
                        HashEntries.init(hash, keyLen, valueLen, hashEntryAdr, Util.SENTINEL_NOT_PRESENT);

                        if (!segment.replaceEntry(hash, sentinelHashEntryAdr, hashEntryAdr, bytes))
                            throw new RuntimeException("not enough free capacity");
                        replaced = true;

                        HashEntries.setSentinel(sentinelHashEntryAdr, Util.SENTINEL_SUCCESS);
                        HashEntries.dereference(sentinelHashEntryAdr);
                    } catch (PermanentLoadException e) {
                        HashEntries.setSentinel(sentinelHashEntryAdr, Util.SENTINEL_PERMANENT_FAILURE);
                        throw e;
                    } catch (Throwable e) {
                        failure = e instanceof Exception ? (Exception) e : new RuntimeException(e);
                        HashEntries.setSentinel(sentinelHashEntryAdr, Util.SENTINEL_TEMPORARY_FAILURE);
                        if (replaced)
                            HashEntries.dereference(sentinelHashEntryAdr);
                        else
                            segment.removeEntry(sentinelHashEntryAdr);
                    }

                    if (failure != null)
                        throw failure;

                    return value;
                }
            });
        } else {
            // this request IS NOT the initial requestor for the key, so it must
            // free the unneeded but allocated sentinel

            Uns.free(hashEntryAdr);
        }

        // fall through
    }

    // this request IS NOT the initial requestor for the key
    // this request IS an adjacent requestor for the key

    // check if the value is already there (no sentinel) or has permanent failure status
    int sentinelStatus = HashEntries.getSentinel(hashEntryAdr);
    switch (sentinelStatus) {
    case Util.SENTINEL_NOT_PRESENT:
        try {
            return Futures.immediateFuture(valueSerializer.deserialize(Uns.valueBufferR(hashEntryAdr)));
        } finally {
            HashEntries.dereference(hashEntryAdr);
        }
    case Util.SENTINEL_PERMANENT_FAILURE:
        HashEntries.dereference(hashEntryAdr);
        return Futures.immediateFailedFuture(new PermanentLoadException());
    }

    // handle sentinel

    final SettableFuture<V> future = SettableFuture.create();

    final long sentinelHashEntryAdr = hashEntryAdr;

    // TODO / DOCUMENT: executorService shutdown with ongoing requests with referenced sentinel-entries --> off-heap memory leak
    // Reason:
    // The jobs started for adjacent getWithLoader*() calls are not running (and waiting) continuously.
    // Instead these are scheduled regularly and poll the referenced sentinel hash-entry.
    // The sentinel hash-entry is dereferenced within the following job for adjacent getWithLoader*() calls.
    // So - if the following job is no longer called, the sentinel hash-entry will never be dereferenced and
    // therefore never be deallocated.
    // Workaround is to close the OHCache instance, then wait some time and shutdown the scheduled executor service
    // when there are no more scheduled jobs.

    // The following job basically "spins" on the sentinel field of the sentinel hash-entry without
    // any lock on the segment.
    // It has two "exit" criterias:

    executorService.schedule(new Runnable() {
        public void run() {
            if (future.isCancelled() || closed) {
                HashEntries.dereference(sentinelHashEntryAdr);
                return;
            }

            int sentinelStatus = HashEntries.getSentinel(sentinelHashEntryAdr);
            switch (sentinelStatus) {
            // SENTINEL_NOT_PRESENT is an impossible status on the sentinel hash-entry
            case Util.SENTINEL_SUCCESS:
                break;
            case Util.SENTINEL_LOADING:
                reschedule(0L);
                return;
            case Util.SENTINEL_PERMANENT_FAILURE:
                failure(0L, new PermanentLoadException());
                return;
            case Util.SENTINEL_TEMPORARY_FAILURE:
                failure(0L, new TemporaryLoadException());
                return;
            default:
                failure(0L, new AssertionError("illegal sentinel value " + sentinelStatus));
                return;
            }

            long hashEntryAdr = segment.getEntry(keySource, true);

            if (hashEntryAdr == 0L) {
                // two possibilities that the entry does not exist:
                // - entry has been evicted (very very unlikely, so ignore this option)
                // - loader indicated temporary failure (very very likely)
                future.setException(new TemporaryLoadException());
            }

            if (hashEntryAdr == sentinelHashEntryAdr) {
                // oops, still the sentinel entry
                reschedule(0L);
                return;
            }

            sentinelStatus = HashEntries.getSentinel(hashEntryAdr);
            switch (sentinelStatus) {
            case Util.SENTINEL_NOT_PRESENT:
                try {
                    future.set(valueSerializer.deserialize(Uns.valueBufferR(hashEntryAdr)));
                    HashEntries.dereference(hashEntryAdr);
                    HashEntries.dereference(sentinelHashEntryAdr);
                } catch (Throwable e) {
                    failure(hashEntryAdr, e);
                }
                break;
            case Util.SENTINEL_SUCCESS:
            case Util.SENTINEL_LOADING:
                HashEntries.dereference(hashEntryAdr);
                reschedule(hashEntryAdr);
                break;
            case Util.SENTINEL_PERMANENT_FAILURE:
                failure(hashEntryAdr, new PermanentLoadException());
                break;
            case Util.SENTINEL_TEMPORARY_FAILURE:
                failure(hashEntryAdr, new TemporaryLoadException());
                break;
            default:
                failure(hashEntryAdr, new AssertionError("illegal sentinel value " + sentinelStatus));
                break;
            }
        }

        private void failure(long hashEntryAdr, Throwable e) {
            if (hashEntryAdr != 0L)
                HashEntries.dereference(hashEntryAdr);
            HashEntries.dereference(sentinelHashEntryAdr);
            future.setException(e);
        }

        private void reschedule(long hashEntryAdr) {
            try {
                executorService.schedule(this, 10, TimeUnit.MILLISECONDS);
            } catch (Throwable t) {
                failure(hashEntryAdr, t);
            }
        }
    }, 10, TimeUnit.MILLISECONDS);

    return future;
}

From source file:org.opendaylight.vpnservice.natservice.internal.VpnFloatingIpHandler.java

@Override
public void onRemoveFloatingIp(final BigInteger dpnId, String routerId, Uuid networkId, final String externalIp,
        String internalIp, final long label) {
    final String vpnName = NatUtil.getAssociatedVPN(dataBroker, networkId, LOG);
    if (vpnName == null) {
        LOG.info("No VPN associated with ext nw {} to handle remove floating ip configuration {} in router {}",
                networkId, externalIp, routerId);
        return;//  w  w w  . j a  v  a  2s.  c  om
    }
    //Remove Prefix from BGP
    String rd = NatUtil.getVpnRd(dataBroker, vpnName);
    removePrefixFromBGP(rd, externalIp + "/32");

    //Remove custom FIB routes
    //Future<RpcResult<java.lang.Void>> removeFibEntry(RemoveFibEntryInput input);
    RemoveFibEntryInput input = new RemoveFibEntryInputBuilder().setVpnName(vpnName).setSourceDpid(dpnId)
            .setIpAddress(externalIp + "/32").setServiceId(label).build();
    Future<RpcResult<Void>> future = fibService.removeFibEntry(input);

    ListenableFuture<RpcResult<Void>> labelFuture = Futures.transform(
            JdkFutureAdapters.listenInPoolThread(future),
            new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {

                @Override
                public ListenableFuture<RpcResult<Void>> apply(RpcResult<Void> result) throws Exception {
                    //Release label
                    if (result.isSuccessful()) {
                        removeTunnelTableEntry(dpnId, label);
                        removeLFibTableEntry(dpnId, label);
                        RemoveVpnLabelInput labelInput = new RemoveVpnLabelInputBuilder().setVpnName(vpnName)
                                .setIpPrefix(externalIp).build();
                        Future<RpcResult<Void>> labelFuture = vpnService.removeVpnLabel(labelInput);
                        return JdkFutureAdapters.listenInPoolThread(labelFuture);
                    } else {
                        String errMsg = String.format(
                                "RPC call to remove custom FIB entries on dpn %s for prefix %s Failed - %s",
                                dpnId, externalIp, result.getErrors());
                        LOG.error(errMsg);
                        return Futures.immediateFailedFuture(new RuntimeException(errMsg));
                    }
                }
            });

    Futures.addCallback(labelFuture, new FutureCallback<RpcResult<Void>>() {

        @Override
        public void onFailure(Throwable error) {
            LOG.error("Error in removing the label or custom fib entries", error);
        }

        @Override
        public void onSuccess(RpcResult<Void> result) {
            if (result.isSuccessful()) {
                LOG.debug("Successfully removed the label for the prefix {} from VPN {}", externalIp, vpnName);
            } else {
                LOG.error("Error in removing the label for prefix {} from VPN {}, {}", externalIp, vpnName,
                        result.getErrors());
            }
        }
    });
}

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

@Override
public ListenableFuture<Object[]> invoke(final VContext ctx, final StreamServerCall call, final String method,
        final Object[] args) {
    Executor executor = V.getExecutor(ctx);
    if (executor == null) {
        return Futures.immediateFailedFuture(new VException("NULL executor in context: did "
                + "you derive server context from the context returned by V.init()?"));
    }//from w ww  .j a v a 2 s .  c  o m
    try {
        final ServerMethod m = findMethod(method);
        final SettableFuture<ListenableFuture<Object[]>> ret = SettableFuture.create();
        // Invoke the method.
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    if (ctx.isCanceled()) {
                        ret.setException(new CanceledException(ctx));
                        return;
                    }
                    // Invoke the method and process results.
                    Object[] allArgs = new Object[2 + args.length];
                    allArgs[0] = ctx;
                    allArgs[1] = call;
                    System.arraycopy(args, 0, allArgs, 2, args.length);
                    Object result = m.invoke(allArgs);
                    ret.set(prepareReply(m, result));
                } catch (InvocationTargetException | IllegalAccessException e) {
                    ret.setException(new VException(
                            String.format("Error invoking method %s: %s", method, e.getCause().toString())));
                }
            }
        });
        return Futures.dereference(ret);
    } catch (VException e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:com.metamx.rdiclient.RdiClientImpl.java

private ListenableFuture<HttpResponseStatus> retryingPost(final RequestBuilder request, final int attempt,
        final int maxRetries) {
    final SettableFuture<HttpResponseStatus> retVal = SettableFuture.create();
    final ListenableFuture<HttpResponseStatus> response = Futures.transform(
            request.go(new StatusResponseHandler(Charsets.UTF_8)),
            new AsyncFunction<StatusResponseHolder, HttpResponseStatus>() {
                @Override/*from ww  w  .  j a  v a2s  .c om*/
                public ListenableFuture<HttpResponseStatus> apply(StatusResponseHolder result)
                        throws Exception {
                    // Throw an RdiHttpResponseException in case of unexpected HTTP status codes.
                    if (result.getStatus().getCode() / 100 == 2) {
                        return Futures.immediateFuture(result.getStatus());
                    } else {
                        return Futures.immediateFailedFuture(new RdiHttpResponseException(result));
                    }
                }
            });
    Futures.addCallback(response, new FutureCallback<HttpResponseStatus>() {
        @Override
        public void onSuccess(HttpResponseStatus result) {
            retVal.set(result);
        }

        @Override
        public void onFailure(Throwable e) {
            final boolean shouldRetry;
            if (maxRetries <= 0) {
                shouldRetry = false;
            } else if (e instanceof IOException || e instanceof ChannelException) {
                shouldRetry = true;
            } else if (e instanceof RdiHttpResponseException) {
                final int statusCode = ((RdiHttpResponseException) e).getStatusCode();
                shouldRetry = statusCode / 100 == 5 || (statusCode / 100 == 4 && statusCode != 400);
            } else {
                shouldRetry = false;
            }

            if (shouldRetry) {
                final long sleepMillis = retryDuration(attempt);
                log.warn(e, "Failed try #%d, retrying in %,dms (%,d tries left).", attempt + 1, sleepMillis,
                        maxRetries);
                retryExecutor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        final ListenableFuture<HttpResponseStatus> nextTry = retryingPost(request, attempt + 1,
                                maxRetries - 1);
                        Futures.addCallback(nextTry, new FutureCallback<HttpResponseStatus>() {
                            @Override
                            public void onSuccess(HttpResponseStatus result2) {
                                retVal.set(result2);
                            }

                            @Override
                            public void onFailure(Throwable e2) {
                                retVal.setException(e2);
                            }
                        });
                    }
                }, sleepMillis, TimeUnit.MILLISECONDS);
            } else if (e instanceof RdiException || e instanceof Error) {
                retVal.setException(e);
            } else {
                retVal.setException(new RdiException(String
                        .format("Got exception when posting events to urlString[%s].", config.getRdiUrl()), e));
            }
        }
    });

    return retVal;
}

From source file:co.paralleluniverse.jersey.connector.AsyncHttpConnector.java

/**
 * Asynchronously process client request into a response.
 *
 * The method is used by Jersey client runtime to asynchronously send a request
 * and receive a response.//w  w w  .j  a  va 2s .c o  m
 *
 * @param request Jersey client request to be sent.
 * @param callback Jersey asynchronous connector callback to asynchronously receive
 * the request processing result (either a response or a failure).
 * @return asynchronously executed task handle.
 */
@Override
public Future<?> apply(final ClientRequest request, final AsyncConnectorCallback callback) {
    final ByteBufferInputStream entityStream = new ByteBufferInputStream();
    final AtomicBoolean callbackInvoked = new AtomicBoolean(false);

    Throwable failure;
    try {
        return client.executeRequest(translateRequest(request), new AsyncHandler<Void>() {
            private volatile HttpResponseStatus status = null;

            @Override
            public STATE onStatusReceived(final HttpResponseStatus responseStatus) throws Exception {
                status = responseStatus;
                return STATE.CONTINUE;
            }

            @Override
            public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception {
                if (!callbackInvoked.compareAndSet(false, true))
                    return STATE.ABORT;

                callback.response(translateResponse(request, this.status, headers, entityStream));
                return STATE.CONTINUE;
            }

            @Override
            public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                entityStream.put(bodyPart.getBodyByteBuffer());
                return STATE.CONTINUE;
            }

            @Override
            public Void onCompleted() throws Exception {
                entityStream.closeQueue();
                return null;
            }

            @Override
            public void onThrowable(Throwable t) {
                entityStream.closeQueue(t);

                if (callbackInvoked.compareAndSet(false, true)) {
                    t = t instanceof IOException ? new ProcessingException(t.getMessage(), t) : t;
                    callback.failure(t);
                }
            }
        });
    } catch (IOException ex) {
        failure = new ProcessingException(ex.getMessage(), ex.getCause());
    } catch (Throwable t) {
        failure = t;
    }

    if (callbackInvoked.compareAndSet(false, true))
        callback.failure(failure);

    return Futures.immediateFailedFuture(failure);
}

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

public ListenableFuture<Document> upsert(Document entity) {
    ListenableFuture<ResultSet> future = submitUpsert(entity);
    return Futures.transformAsync(future, new AsyncFunction<ResultSet, Document>() {
        @Override//from   ww w. java  2s.c o  m
        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", tableName, entity.toString())));
        }
    }, MoreExecutors.directExecutor());
}