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.DocumentService.java

private ListenableFuture<Document> createViewDocument(View view, Document document) {
    try {//from w  ww  .  j  a va 2  s  .  com
        AbstractDocumentRepository docs = acquireRepositoryFor(view).get();
        return docs.create(document);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return Futures.immediateFailedFuture(e);
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return Futures.immediateFailedFuture(e);
    }
    //      ListenableFuture<AbstractDocumentRepository> docs = acquireRepositoryFor(view);
    //      return Futures.transformAsync(docs, new AsyncFunction<AbstractDocumentRepository, Document>()
    //      {
    //         @Override
    //         public ListenableFuture<Document> apply(AbstractDocumentRepository docRepo)
    //         throws Exception
    //         {
    //            return docRepo.create(document);
    //         }
    //      });
}

From source file:net.floodlightcontroller.core.internal.OFConnection.java

@Override
public <R extends OFMessage> ListenableFuture<R> writeRequest(OFRequest<R> request) {
    if (!isConnected()) {
        return Futures.immediateFailedFuture(new SwitchDisconnectedException(getDatapathId()));
    }/*from   w  ww  .  j ava2 s. com*/

    DeliverableListenableFuture<R> future = new DeliverableListenableFuture<R>(request);
    xidDeliverableMap.put(request.getXid(), future);
    listener.messageWritten(this, request);
    this.write(request);
    return future;
}

From source file:com.ltln.modules.openflow.controller.manager.OFConnection.java

@Override
public <R extends OFMessage> ListenableFuture<R> writeRequest(OFRequest<R> request) {
    if (!isConnected()) {
        return Futures.immediateFailedFuture(new SwitchDisconnectedException(getDatapathId()));
    }//from  ww  w  .  j  av a2s.  com

    DeliverableListenableFuture<R> future = new DeliverableListenableFuture<R>();
    xidDeliverableMap.put(request.getXid(), future);
    listener.messageWritten(this, request);
    this.write(request);
    return future;
}

From source file:org.opendaylight.faas.fabric.general.EndPointRegister.java

@Override
public Future<RpcResult<Void>> locateEndpoint(LocateEndpointInput input) {

    final RpcResult<Void> result = RpcResultBuilder.<Void>success().build();

    if (input == null) {
        return Futures.immediateFailedCheckedFuture(new IllegalArgumentException("endpoint can not be empty!"));
    }/*from www .  j  a v  a 2s . co m*/
    final Uuid epId = input.getEndpointId();

    if (epId == null) {
        return Futures.immediateFailedCheckedFuture(new IllegalArgumentException("endpoint can not be empty!"));
    }
    final FabricId fabricid = input.getFabricId();
    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricid);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(new IllegalArgumentException("fabric is not exist!"));
    }

    ReadWriteTransaction trans = dataBroker.newReadWriteTransaction();

    EndpointBuilder epBuilder = new EndpointBuilder();
    LocationBuilder locBuilder = new LocationBuilder(input.getLocation());
    epBuilder.setEndpointUuid(epId);
    epBuilder.setLocation(locBuilder.build());

    final InstanceIdentifier<Endpoint> eppath = Constants.DOM_ENDPOINTS_PATH.child(Endpoint.class,
            new EndpointKey(epId));
    trans.merge(LogicalDatastoreType.OPERATIONAL, eppath, epBuilder.build());

    CheckedFuture<Void, TransactionCommitFailedException> future = trans.submit();

    return Futures.transform(future, new AsyncFunction<Void, RpcResult<Void>>() {

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void input) throws Exception {
            return Futures.immediateFuture(result);
        }
    }, executor);
}

From source file:org.thingsboard.server.service.script.RemoteJsInvokeService.java

@Override
protected ListenableFuture<Object> doInvokeFunction(UUID scriptId, String functionName, Object[] args) {
    String scriptBody = scriptIdToBodysMap.get(scriptId);
    if (scriptBody == null) {
        return Futures.immediateFailedFuture(
                new RuntimeException("No script body found for scriptId: [" + scriptId + "]!"));
    }/*from w  ww.j  av  a2 s.  co  m*/
    JsInvokeProtos.JsInvokeRequest.Builder jsRequestBuilder = JsInvokeProtos.JsInvokeRequest.newBuilder()
            .setScriptIdMSB(scriptId.getMostSignificantBits())
            .setScriptIdLSB(scriptId.getLeastSignificantBits()).setFunctionName(functionName)
            .setTimeout((int) maxRequestsTimeout).setScriptBody(scriptIdToBodysMap.get(scriptId));

    for (int i = 0; i < args.length; i++) {
        jsRequestBuilder.addArgs(args[i].toString());
    }

    JsInvokeProtos.RemoteJsRequest jsRequestWrapper = JsInvokeProtos.RemoteJsRequest.newBuilder()
            .setInvokeRequest(jsRequestBuilder.build()).build();

    ListenableFuture<JsInvokeProtos.RemoteJsResponse> future = kafkaTemplate.post(scriptId.toString(),
            jsRequestWrapper);
    return Futures.transform(future, response -> {
        JsInvokeProtos.JsInvokeResponse invokeResult = response.getInvokeResponse();
        if (invokeResult.getSuccess()) {
            return invokeResult.getResult();
        } else {
            log.debug("[{}] Failed to compile script due to [{}]: {}", scriptId,
                    invokeResult.getErrorCode().name(), invokeResult.getErrorDetails());
            throw new RuntimeException(invokeResult.getErrorDetails());
        }
    });
}

From source file:io.crate.executor.transport.task.UpsertByIdTask.java

@Override
public ListenableFuture<List<Long>> executeBulk() {
    try {//from  w w  w  . ja  va  2  s  .co m
        List<SettableFuture<Long>> resultList = executeBulkShardProcessor();
        return Futures.allAsList(resultList);
    } catch (Throwable throwable) {
        return Futures.immediateFailedFuture(throwable);
    }
}

From source file:org.attribyte.relay.AsyncPublisher.java

/**
 * Enqueue a notification for future posting.
 * @param notification The notification.
 * @param headers A colleciton of headers.
 * @return The (listenable) future result.
 *///from w w w.  j  av  a2  s .c  o  m
public final ListenableFuture<NotificationResult> enqueueNotification(final Notification notification,
        final Collection<Header> headers) {
    try {
        return notificationExecutor.submit(new NotificationCallable(notification, headers));
    } catch (RejectedExecutionException re) {
        rejectedNotifications.mark();
        return Futures.immediateFailedFuture(re);
    }
}

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

/**
 * Get all PureCloud license definitions available for the organization.
 * //ww w .j a v a2  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<List<LicenseDefinition>> getLicenseDefinitionsAsync(GetLicenseDefinitionsRequest request,
        final AsyncApiCallback<List<LicenseDefinition>> callback) {
    try {
        final SettableFuture<List<LicenseDefinition>> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<List<LicenseDefinition>>() {
        }, new AsyncApiCallback<ApiResponse<List<LicenseDefinition>>>() {
            @Override
            public void onCompleted(ApiResponse<List<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:io.v.v23.syncbase.nosql.DatabaseImpl.java

@Override
public ListenableFuture<Boolean> upgradeIfOutdated(final VContext ctx) {
    if (schema == null) {
        Futures.immediateFailedFuture(new BadStateException(ctx));
    }/*  w w  w  . j a v a 2 s .  com*/
    if (schema.getMetadata().getVersion() < 0) {
        Futures.immediateFailedFuture(new BadStateException(ctx));
    }
    final SchemaManager schemaManager = new SchemaManager(fullName);
    final SettableFuture<Boolean> ret = SettableFuture.create();
    Futures.addCallback(schemaManager.getSchemaMetadata(ctx), new FutureCallback<SchemaMetadata>() {
        @Override
        public void onFailure(Throwable t) {
            if (t instanceof NoExistException) {
                // If the client app did not set a schema as part of database creation,
                // getSchemaMetadata() will throw NoExistException. In this case, we set the
                // schema here.
                Futures.addCallback(schemaManager.setSchemaMetadata(ctx, schema.getMetadata()),
                        new FutureCallback<Void>() {
                            @Override
                            public void onSuccess(Void result) {
                                ret.set(false);
                            }

                            @Override
                            public void onFailure(Throwable t) {
                                // The database may not yet exist. If so, setSchemaMetadata
                                // will throw NoExistException, and here we return set the
                                // return value of 'false'; otherwise, we fail the
                                // return future.
                                if (t instanceof NoExistException) {
                                    ret.set(false);
                                } else {
                                    ret.setException(t);
                                }
                            }
                        });
            } else {
                ret.setException(t);
            }
        }

        @Override
        public void onSuccess(SchemaMetadata currMetadata) {
            // Call the Upgrader provided by the app to upgrade the schema.
            //
            // TODO(jlodhia): disable sync before running Upgrader and reenable
            // once Upgrader is finished.
            //
            // TODO(jlodhia): prevent other processes (local/remote) from accessing
            // the database while upgrade is in progress.
            try {
                schema.getUpgrader().run(DatabaseImpl.this, currMetadata.getVersion(),
                        schema.getMetadata().getVersion());
                // Update the schema metadata in db to the latest version.
                Futures.addCallback(schemaManager.setSchemaMetadata(ctx, schema.getMetadata()),
                        new FutureCallback<Void>() {
                            @Override
                            public void onSuccess(Void result) {
                                ret.set(true);
                            }

                            @Override
                            public void onFailure(Throwable t) {
                                ret.setException(t);
                            }
                        });
            } catch (VException e) {
                ret.setException(e);
            }
        }
    });
    return ret;
}

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

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

    if (encryptedKey == null) {
        throw new IllegalArgumentException("encryptedKey ");
    }// w ww  .  j av a2 s . co m

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

    // Interpret the requested 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(encryptedKey));
    } catch (Exception e) {
        result = Futures.immediateFailedFuture(e);
    }

    return result;
}