Example usage for com.google.common.util.concurrent SettableFuture setException

List of usage examples for com.google.common.util.concurrent SettableFuture setException

Introduction

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

Prototype

@Override
    public boolean setException(Throwable throwable) 

Source Link

Usage

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

/**
 * Creates a new membership node in Zookeeper and sets the provided future when creation is complete.
 *
 * @param leasePromise promise that gets fulfilled when node is created
 * @return a listenable future to get notified when the znode gets created
 * @throws Exception/*  www  .j  a  v  a2  s  .com*/
 */
public synchronized ListenableFuture<Void> create(final SettableFuture<ServiceNode.Lease> leasePromise)
        throws Exception {
    logger.debug("Creating membership node for {}", membershipNode);

    final SettableFuture<Void> future = SettableFuture.create();
    BackgroundCallback callback = new BackgroundCallback() {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
            if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
                leasePromise.set(new ServiceNode.Lease() {
                    @Override
                    public ListenableFuture<Void> getExpirationFuture() {
                        return expirationPromise;
                    }
                });
                future.set(null);
            } else {
                logger.error("Failed to create node {}: {}", membershipNode, event.getResultCode());
                future.setException(KeeperException.create(KeeperException.Code.get(event.getResultCode())));
                leasePromise
                        .setException(KeeperException.create(KeeperException.Code.get(event.getResultCode())));
            }
        }
    };

    zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(callback)
            .forPath(membershipNode, getSerializedAddress());
    return future;
}

From source file:io.crate.blob.v2.BlobIndices.java

public ListenableFuture<Void> createBlobTable(String tableName, Settings indexSettings) {
    ImmutableSettings.Builder builder = ImmutableSettings.builder();
    builder.put(indexSettings);//  w  w w .j  a v  a 2  s .c om
    builder.put(SETTING_INDEX_BLOBS_ENABLED, true);

    final SettableFuture<Void> result = SettableFuture.create();
    transportCreateIndexActionProvider.get().execute(
            new CreateIndexRequest(fullIndexName(tableName), builder.build()),
            new ActionListener<CreateIndexResponse>() {
                @Override
                public void onResponse(CreateIndexResponse createIndexResponse) {
                    assert createIndexResponse.isAcknowledged();
                    result.set(null);
                }

                @Override
                public void onFailure(Throwable e) {
                    result.setException(e);
                }
            });
    return result;
}

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

public ListenableFuture<Long> execute(DropRepositoryAnalyzedStatement analyzedStatement) {
    final SettableFuture<Long> future = SettableFuture.create();
    final String repoName = analyzedStatement.repositoryName();
    deleteRepositoryAction.execute(new DeleteRepositoryRequest(repoName),
            new ActionListener<DeleteRepositoryResponse>() {
                @Override/*from   w w w  .  java 2  s .  c o  m*/
                public void onResponse(DeleteRepositoryResponse deleteRepositoryResponse) {
                    if (!deleteRepositoryResponse.isAcknowledged()) {
                        LOGGER.info("delete repository '{}' not acknowledged", repoName);
                    }
                    future.set(1L);
                }

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

From source file:io.crate.blob.v2.BlobIndicesService.java

public ListenableFuture<Void> createBlobTable(String tableName, Settings indexSettings) {
    Settings.Builder builder = Settings.builder();
    builder.put(indexSettings);//from   w w w .  j a va  2  s .c om
    builder.put(SETTING_INDEX_BLOBS_ENABLED, true);

    final SettableFuture<Void> result = SettableFuture.create();
    transportCreateIndexActionProvider.get().execute(
            new CreateIndexRequest(fullIndexName(tableName), builder.build()),
            new ActionListener<CreateIndexResponse>() {
                @Override
                public void onResponse(CreateIndexResponse createIndexResponse) {
                    assert createIndexResponse.isAcknowledged();
                    result.set(null);
                }

                @Override
                public void onFailure(Throwable e) {
                    result.setException(e);
                }
            });
    return result;
}

From source file:com.microsoft.services.sharepoint.ListClient.java

/**
 * Gets the list fields./*from   ww w . ja v  a2s  .  c  o  m*/
 *
 * @param listName the list name
 * @param query the query
 * @return the list fields
 */
public ListenableFuture<List<SPListField>> getListFields(String listName, Query query) {
    final SettableFuture<List<SPListField>> result = SettableFuture.create();

    String getListUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')/Fields?"
            + generateODataQueryString(query);
    getListUrl = String.format(getListUrl, urlEncode(listName));
    ListenableFuture<JSONObject> request = executeRequestJson(getListUrl, "GET");

    Futures.addCallback(request, new FutureCallback<JSONObject>() {
        @Override
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(JSONObject json) {
            try {
                result.set(SPListField.listFromJson(json));
            } catch (JSONException e) {
                log(e);
            }
        }
    });

    return result;
}

From source file:org.opendaylight.netconf.topology.pipeline.tx.ProxyReadOnlyTransaction.java

@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    final Future<Boolean> existsFuture = delegate.exists(store, path);
    final SettableFuture<Boolean> settableFuture = SettableFuture.create();
    final CheckedFuture<Boolean, ReadFailedException> checkedFuture = Futures.makeChecked(settableFuture,
            new Function<Exception, ReadFailedException>() {
                @Nullable/*from ww  w.  j av a 2  s .  c  o m*/
                @Override
                public ReadFailedException apply(Exception cause) {
                    return new ReadFailedException("Read from transaction failed", cause);
                }
            });
    existsFuture.onComplete(new OnComplete<Boolean>() {
        @Override
        public void onComplete(Throwable throwable, Boolean result) throws Throwable {
            if (throwable == null) {
                settableFuture.set(result);
            } else {
                settableFuture.setException(throwable);
            }
        }
    }, actorSystem.dispatcher());
    return checkedFuture;
}

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

private <T> void notifyFailure(SettableFuture<T> future, AsyncApiCallback<T> callback, Throwable exception) {
    if (callback != null) {
        try {/* w w  w . j a va  2s .  com*/
            callback.onFailed(exception);
            future.setException(exception);
        } catch (Throwable callbackException) {
            future.setException(callbackException);
        }
    } else {
        future.setException(exception);
    }
}

From source file:org.apache.bookkeeper.common.util.OrderedExecutor.java

public <T> ListenableFuture<T> submitOrdered(long orderingKey, Callable<T> task) {
    SettableFuture<T> future = SettableFuture.create();
    executeOrdered(orderingKey, () -> {
        try {//from  w ww.  j a va  2 s .  co m
            T result = task.call();
            future.set(result);
        } catch (Throwable t) {
            future.setException(t);
        }
    });

    return future;
}

From source file:io.crate.action.sql.DDLAnalysisDispatcher.java

@Override
public ListenableFuture<Long> visitRefreshTableAnalysis(RefreshTableAnalysis analysis, Void context) {
    String[] indexNames = getIndexNames(analysis.table(), analysis.partitionName());
    if (analysis.schema().systemSchema() || indexNames.length == 0) {
        // shortcut when refreshing on system tables
        // or empty partitioned tables
        return Futures.immediateFuture(null);
    } else {//  w  w w . ja v  a  2s  . c om
        final SettableFuture<Long> future = SettableFuture.create();
        RefreshRequest request = new RefreshRequest(indexNames);
        transportRefreshAction.execute(request, new ActionListener<RefreshResponse>() {
            @Override
            public void onResponse(RefreshResponse refreshResponse) {
                future.set(null); // no row count
            }

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

From source file:com.microsoft.sharepointservices.DocLibClient.java

/**
 * Retrieves the value of property with a given path and library
 * /*from   w  w w  .j  a va2s . com*/
 * @param property
 * @param path
 * @param library
 * @return
 */
public ListenableFuture<Object> getProperty(final String property, String path, String library) {
    if (path == null || path.length() == 0) {
        throw new IllegalArgumentException("Path cannot be null or empty");
    }

    if (property == null || property.length() == 0) {
        throw new IllegalArgumentException("Property cannot be null or empty");
    }

    String getPropertyUrl;
    if (library == null) {
        getPropertyUrl = getSiteUrl() + String.format("_api/files('%s')/%s", urlEncode(path), property);
    } else {
        String url = getSiteUrl() + "_api/web/Lists/GetByTitle('%s')/files('%s')/%s";
        getPropertyUrl = String.format(url, urlEncode(library.trim()), urlEncode(path), property);
    }

    final SettableFuture<Object> result = SettableFuture.create();
    ListenableFuture<JSONObject> request = executeRequestJson(getPropertyUrl, "GET");

    Futures.addCallback(request, new FutureCallback<JSONObject>() {
        @Override
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(JSONObject json) {
            Object propertyResult;
            try {
                propertyResult = json.getJSONObject("d").get(property);
                result.set(propertyResult);
            } catch (JSONException e) {
                result.setException(e);
            }
        }
    });
    return result;
}