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.view.ViewService.java

public ListenableFuture<View> update(View view) {
    ListenableFuture<Boolean> tableFuture = tables.exists(view.databaseName(), view.tableName());
    return Futures.transformAsync(tableFuture, new AsyncFunction<Boolean, View>() {
        @Override//w ww .  j av  a  2s. co m
        public ListenableFuture<View> apply(Boolean exists) throws Exception {
            if (exists) {
                try {
                    ValidationEngine.validateAndThrow(view);
                    return views.update(view);
                } catch (ValidationException e) {
                    return Futures.immediateFailedFuture(e);
                }
            } else {
                return Futures.immediateFailedFuture(
                        new ItemNotFoundException("Database not found: " + view.databaseName()));
            }
        }
    }, MoreExecutors.directExecutor());
}

From source file:com.vmware.photon.controller.common.thrift.BasicClientPool.java

@Override
public synchronized ListenableFuture<C> acquire() {
    if (promises.size() < options.getMaxWaiters()) {
        SettableFuture<C> future = SettableFuture.create();
        Promise<C> promise = new Promise<>(future);
        promises.add(promise);/*from w w  w.  j  ava  2s  .co  m*/
        processPromises();
        if (options.getTimeoutMs() > 0 && !future.isDone()) {
            setTimeout(promise);
        }
        return future;
    }

    return Futures.immediateFailedFuture(new ClientPoolException("Too many waiters"));
}

From source file:com.veloxsw.impl.NcclientServiceImpl.java

@Override
public Future<RpcResult<PythonVersionOutput>> pythonVersion() {
    try {/*  ww  w  .j av a2s. c o  m*/
        final UnixCommandReturnDTO ret = execCommand("python --version");
        final PythonVersionOutputBuilder builder = new PythonVersionOutputBuilder();
        builder.setOutput(ret.getOutput());
        builder.setError(ret.getError());
        builder.setReturnCode(ret.getReturnCode());
        return RpcResultBuilder.success(builder).buildFuture();
    } catch (final IOException | InterruptedException e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:org.esbtools.eventhandler.PollingDocumentEventProcessorRoute.java

@Override
public void configure() throws Exception {
    from("timer:pollForDocumentEvents-" + routeId + "?period=" + pollingInterval.toMillis()).routeId(routeId)
            .process(exchange -> {/*from w  ww  .  ja  v a2  s .  c  o m*/
                List<? extends DocumentEvent> documentEvents = documentEventRepository
                        .retrievePriorityDocumentEventsUpTo(batchSize);
                Map<DocumentEvent, Future<?>> eventsToFutureDocuments = new HashMap<>(documentEvents.size());

                // Intentionally cache all futures before resolving them.
                for (DocumentEvent event : documentEvents) {
                    try {
                        eventsToFutureDocuments.put(event, event.lookupDocument());
                    } catch (Exception e) {
                        log.error("Failed to get future document for document event: " + event, e);
                        eventsToFutureDocuments.put(event, Futures.immediateFailedFuture(e));
                    }
                }

                Map<DocumentEvent, Object> eventsToDocuments = new HashMap<>(documentEvents.size());
                List<FailedDocumentEvent> failedEvents = new ArrayList<>();

                for (Map.Entry<DocumentEvent, Future<?>> eventToFutureDocument : eventsToFutureDocuments
                        .entrySet()) {
                    DocumentEvent event = eventToFutureDocument.getKey();
                    Future<?> futureDoc = eventToFutureDocument.getValue();

                    try {
                        eventsToDocuments.put(event,
                                futureDoc.get(processTimeout.toMillis(), TimeUnit.MILLISECONDS));
                    } catch (ExecutionException | InterruptedException e) {
                        log.error("Failed to get document for document event: " + event, e);
                        failedEvents.add(new FailedDocumentEvent(event, e));
                    }
                }

                try {
                    documentEventRepository.markDocumentEventsPublishedOrFailed(Collections.emptyList(),
                            failedEvents);
                } catch (Exception e) {
                    if (log.isErrorEnabled()) {
                        log.error("Failed to update failed events. They will be reprocessed. "
                                + "Failures were: " + failedEvents, e);
                    }
                }

                Iterator<Map.Entry<DocumentEvent, Object>> eventsToDocumentsIterator = eventsToDocuments
                        .entrySet().iterator();
                while (eventsToDocumentsIterator.hasNext()) {
                    Map.Entry<DocumentEvent, Object> eventToDocument = eventsToDocumentsIterator.next();
                    try {
                        documentEventRepository.ensureTransactionActive(eventToDocument.getKey());
                    } catch (Exception e) {
                        eventsToDocumentsIterator.remove();
                        if (log.isWarnEnabled()) {
                            log.warn("Event transaction no longer active, not processing: "
                                    + eventToDocument.getKey(), e);
                        }
                    }
                }

                log.debug("Publishing {} documents on route {}: {}", eventsToDocuments.size(),
                        exchange.getFromRouteId(), eventsToDocuments.values());

                exchange.getIn().setBody(Iterables.concat(eventsToDocuments.entrySet(), failedEvents));
            }).split(body()).streaming().choice().when(e -> e.getIn().getBody() instanceof FailedDocumentEvent)
            .to(failureEndpoint).otherwise().process(exchange -> {
                Map.Entry<DocumentEvent, Object> eventToDocument = exchange.getIn().getBody(Map.Entry.class);
                exchange.setProperty("originalEvent", eventToDocument.getKey());
                exchange.getIn().setBody(eventToDocument.getValue());
            }).to(documentEndpoint)
            // If producing to documentEndpoint succeeded, update original event status...
            // TODO(ahenning): This updates event status one at a time. We could consider using
            // aggregation strategy with splitter to update all in bulk which would take
            // advantage of repository implementations which can update many statuses in one
            // call.
            .process(exchange -> {
                DocumentEvent event = exchange.getProperty("originalEvent", DocumentEvent.class);

                if (event == null) {
                    throw new IllegalStateException("Could not get original event from "
                            + "exchange. Won't update event status as published. Exchange was: " + exchange);
                }

                documentEventRepository.markDocumentEventsPublishedOrFailed(Collections.singleton(event),
                        Collections.emptyList());
            });
}

From source file:org.voltdb.rejoin.StreamSnapshotDataTarget.java

@Override
public ListenableFuture<?> write(Callable<BBContainer> tupleData, SnapshotTableTask context) {
    assert (context != null);

    BBContainer chunk = null;//from  ww w.  j av  a2  s  .c om
    try {
        chunk = tupleData.call();
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }

    if (m_writeFailed) {
        if (chunk != null) {
            chunk.discard();
        }
        return null;
    }
    if (!m_outThread.isAlive()) {
        if (chunk != null) {
            chunk.discard();
        }

        m_writeFailed = true;
        IOException e = new IOException("Trying to write snapshot data " + "after the stream is closed");
        return Futures.immediateFailedFuture(e);
    }

    if (chunk != null) {
        // Have we seen this table before, if not, send schema
        if (m_schemas.containsKey(context.getTableId())) {
            // remove the schema once sent
            byte[] schema = m_schemas.remove(context.getTableId());
            rejoinLog.debug("Sending schema for table " + context.getTableId());
            sendSchema(schema);
        }

        chunk.b.put((byte) StreamSnapshotMessageType.DATA.ordinal());
        chunk.b.putInt(m_blockIndex++); // put chunk index
        chunk.b.putInt(context.getTableId()); // put table ID
        chunk.b.position(0);

        m_ackTracker.waitForAcks(m_blockIndex - 1, 1);
        m_out.offer(chunk);
    }

    return null;
}

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

/**
 * Get PureCloud license definition./*ww  w. ja v a2s  . 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<LicenseDefinition> getLicenseDefinitionAsync(GetLicenseDefinitionRequest request,
        final AsyncApiCallback<LicenseDefinition> callback) {
    try {
        final SettableFuture<LicenseDefinition> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<LicenseDefinition>() {
        }, new AsyncApiCallback<ApiResponse<LicenseDefinition>>() {
            @Override
            public void onCompleted(ApiResponse<LicenseDefinition> 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:org.opendaylight.openflowplugin.impl.services.SalRoleServiceImpl.java

@Override
public Future<RpcResult<SetRoleOutput>> setRole(final SetRoleInput input) {
    LOG.info("SetRole called with input:{}", input);

    synchronized (this) {
        // compare with last known role and set if different. If they are same, then return.
        if (currentRole == input.getControllerRole()) {
            LOG.info("Role to be set is same as the last known role for the device:{}. Hence ignoring.",
                    input.getControllerRole());
            return RpcResultBuilder.<SetRoleOutput>success().buildFuture();
        }/*from   ww  w.j  av  a  2 s. co  m*/

        int retryCounter = 0;
        do {
            // Check current connection state
            final CONNECTION_STATE state = deviceContext.getPrimaryConnectionContext().getConnectionState();
            switch (state) {
            case RIP:
                LOG.info("Device {} has been disconnected", input.getNode());
                return Futures.immediateFailedFuture(new Exception(String.format(
                        "Device connection doesn't exist anymore. Primary connection status : %s", state)));
            case WORKING:
                // We can proceed
                break;
            default:
                LOG.info("Device {} is in state {}, role change is not allowed", input.getNode(), state);
                return RpcResultBuilder.<SetRoleOutput>failed().buildFuture();
            }

            LOG.info("Requesting state change to {}", input.getControllerRole());

            try {
                final SetRoleOutput result = tryChangeRole(input.getControllerRole());
                LOG.info("setRoleOutput received after roleChangeTask execution:{}", result);

                currentRole = input.getControllerRole();
                return RpcResultBuilder.<SetRoleOutput>success().withResult(result).buildFuture();
            } catch (RoleChangeException e) {
                retryCounter++;
                LOG.info("Exception in setRole(), will retry: {} times.", MAX_RETRIES - retryCounter, e);
            } catch (Exception e) {
                LOG.warn("Unexpected failure to set role on {}", nodeId, e);
                return Futures.immediateFailedFuture(e);
            }
        } while (retryCounter < MAX_RETRIES);
    }

    return Futures.immediateFailedFuture(new RoleChangeException(
            "Set Role failed after " + MAX_RETRIES + "tries on device " + input.getNode().getValue()));
}

From source file:com.proofpoint.testing.SerialScheduledExecutorService.java

@Override
public <T> Future<T> submit(Runnable runnable, T t) {
    Preconditions.checkNotNull(runnable, "Task object is null");
    try {//from  w ww . java2  s. c o  m
        runnable.run();
        return Futures.immediateFuture(t);
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:org.apache.hadoop.yarn.util.FSDownload.java

/**
 * Creates the cache loader for the status loading cache. This should be used
 * to create an instance of the status cache that is passed into the
 * FSDownload constructor.//from w  w w  .  j a  va  2 s  .  c  om
 */
public static CacheLoader<Path, Future<FileStatus>> createStatusCacheLoader(final Configuration conf) {
    return new CacheLoader<Path, Future<FileStatus>>() {
        public Future<FileStatus> load(Path path) {
            try {
                FileSystem fs = path.getFileSystem(conf);
                return Futures.immediateFuture(fs.getFileStatus(path));
            } catch (Throwable th) {
                // report failures so it can be memoized
                return Futures.immediateFailedFuture(th);
            }
        }
    };
}

From source file:com.orangerhymelabs.helenus.cassandra.table.ViewService.java

public ListenableFuture<View> update(View view) {
    ListenableFuture<Boolean> tableFuture = tables.exists(view.databaseName(), view.tableName());
    return Futures.transformAsync(tableFuture, new AsyncFunction<Boolean, View>() {
        @Override//from  w ww. ja va2s . co m
        public ListenableFuture<View> apply(Boolean exists) throws Exception {
            if (exists) {
                try {
                    ValidationEngine.validateAndThrow(view);
                    return views.update(view);
                } catch (ValidationException e) {
                    return Futures.immediateFailedFuture(e);
                }
            } else {
                return Futures.immediateFailedFuture(
                        new ItemNotFoundException("Database not found: " + view.databaseName()));
            }
        }
    });
}