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.microsoft.office365.lists.SharepointListsClient.java

public ListenableFuture<List<String>> getColumnsFromDefaultView(final String listName) {
    final SettableFuture<List<String>> result = SettableFuture.create();
    String getViewUrl = getSiteUrl()
            + String.format("_api/web/lists/GetByTitle('%s')/defaultView/viewfields", urlEncode(listName));
    ListenableFuture<JSONObject> request = executeRequestJson(getViewUrl, "GET");

    Futures.addCallback(request, new FutureCallback<JSONObject>() {
        @Override//from  w  w w  .  j a  v  a 2 s . c o  m
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(JSONObject json) {
            try {
                JSONObject container = json.getJSONObject("d");
                JSONArray results = container.getJSONObject("Items").getJSONArray("results");
                ArrayList<String> columnNames = new ArrayList<String>();

                for (int i = 0; i < results.length(); i++) {
                    columnNames.add(results.get(i).toString());
                }
                result.set(columnNames);
            } catch (JSONException e) {
                log(e);
            }
        }
    });
    return result;
}

From source file:io.viewserver.network.netty.NettyNetworkAdapter.java

@Override
public ListenableFuture<IChannel> connect(IEndpoint endpoint) {
    SettableFuture<IChannel> promise = SettableFuture.create();
    final INettyEndpoint.IClient client = ((INettyEndpoint) endpoint).getClient(getClientWorkerGroup(),
            new NettyPipelineInitialiser(networkMessageWheel));
    ChannelFuture channelFuture = client.connect();
    channelFuture.addListener(new ChannelFutureListener() {
        @Override// w w w .  j  a v  a 2  s  .c  o m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                NettyChannel channel = new NettyChannel(future.channel());
                promise.set(channel);
            } else {
                promise.setException(future.cause());
            }
        }
    });
    return promise;
}

From source file:org.apache.tajo.client.QueryClientImpl.java

@Override
public Future<TajoMemoryResultSet> fetchNextQueryResultAsync(final QueryId queryId, final int fetchRowNum) {

    final SettableFuture<TajoMemoryResultSet> future = SettableFuture.create();
    executor.submit(new Runnable() {
        @Override//from w w  w .  j  a  v a 2 s  .  co m
        public void run() {
            try {
                future.set(fetchNextQueryResult(queryId, fetchRowNum));
            } catch (Throwable e) {
                future.setException(e);
            }
        }
    });
    return future;
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.log.DaylightLogger.java

private ListenableFuture<Void> postResult(String authAccessToken, JsonArray testResultArray) {
    String body = testResultArray.toString();
    String requestUrl = mDaylightUrl + "/api/zumo2/results?access_token=" + authAccessToken;

    HttpPost request = new HttpPost(requestUrl);

    try {//from w  w w.jav a  2s. co  m
        request.setEntity(new StringEntity(body, "UTF-8"));
    } catch (UnsupportedEncodingException uee) {
    }

    final SettableFuture<Void> result = SettableFuture.create();

    ListenableFuture<HttpURLConnection> internalFuture = execute(request);

    Futures.addCallback(internalFuture, new FutureCallback<HttpURLConnection>() {
        @Override
        public void onFailure(Throwable throwable) {
            result.setException(throwable);
        }

        @Override
        public void onSuccess(HttpURLConnection connection) {
            try {
                int statusCode = connection.getResponseCode();

                if (statusCode == 200) {
                    result.set(null);
                } else {
                    result.setException(new Exception("Invalid response status code " + statusCode));
                }
            } catch (Throwable t) {
                result.setException(t);
            }
        }
    });

    return result;
}

From source file:com.spotify.helios.client.RetryingRequestDispatcher.java

private void handleFailure(final SettableFuture<Response> future,
        final Supplier<ListenableFuture<Response>> code, final long deadline, final long delayMillis,
        final Throwable t, final URI uri) {
    if (clock.now().getMillis() < deadline) {
        if (delayMillis > 0) {
            executorService.schedule(new Runnable() {
                @Override//from   w  w w .  j av  a  2  s  .c o m
                public void run() {
                    startRetry(future, code, deadline - 1, delayMillis, uri);
                }
            }, delayMillis, TimeUnit.MILLISECONDS);
        } else {
            startRetry(future, code, deadline - 1, delayMillis, uri);
        }
    } else {
        future.setException(t);
    }
}

From source file:org.opendaylight.distributed.tx.impl.DTXTestTransaction.java

@Override
public <T extends DataObject> CheckedFuture<Optional<T>, ReadFailedException> read(
        LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<T> instanceIdentifier) {
    T obj = null;//from  w  w  w . ja v a2 s  .  c  om

    if (txDataMap.get(instanceIdentifier).size() > 0)
        obj = (T) txDataMap.get(instanceIdentifier).getFirst();

    final Optional<T> retOpt = Optional.fromNullable(obj);

    final SettableFuture<Optional<T>> retFuture = SettableFuture.create();
    Runnable readResult = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(delayTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            boolean readException = getAndResetExceptionWithInstanceIdentifier(readExceptionMap,
                    instanceIdentifier);
            if (readException == false) {
                retFuture.set(retOpt);
            } else {
                retFuture.setException(new Throwable("Read error"));
            }
            retFuture.notifyAll();
        }
    };

    new Thread(readResult).start();

    Function<Exception, ReadFailedException> f = new Function<Exception, ReadFailedException>() {
        @Nullable
        @Override
        public ReadFailedException apply(@Nullable Exception e) {
            return new ReadFailedException("Read failed", e);
        }
    };

    return Futures.makeChecked(retFuture, f);
}

From source file:org.apache.twill.internal.zookeeper.ReentrantDistributedLock.java

/**
 * Acquires a distributed lock through ZooKeeper.
 *
 * @param interruptible true if acquisition of lock can be interrupted
 * @param waitForLock true if wants to wait for the lock when not able to acquire it
 * @param timeout time to wait for the lock before giving up
 * @param unit unit for the timeout//from   w  w  w . ja  va2 s.  co  m
 * @throws InterruptedException if {@code interruptible} is set to {@code true} and the current thread is interrupted
 *                              while acquiring the lock
 * @throws ExecutionException if there is failure while trying to acquire the lock
 */
private boolean acquire(boolean interruptible, final boolean waitForLock, long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
    Preconditions.checkState(lock.isHeldByCurrentThread(), "Not owner of local lock.");
    if (lock.getHoldCount() > 1) {
        // Already owner of the lock, simply return.
        return true;
    }

    // Use a Future to help deal with different variants of locking
    // (lock, lockInterruptibly, tryLock, tryLock with timeout)
    // When the completion future is completed successfully, it means the lock is acquired and the future contains
    // the ZK node path to the ephemeral node that is representing this lock.
    // If it is failed, it means there is exception while trying to acquire the lock
    // If it is cancelled, it means to abort the acquisition logic (due to timeout / interrupt).
    final SettableFuture<String> completion = SettableFuture.create();

    // If the connection expired, fail the locking process if it is still in progress
    final Cancellable watcherCancellable = zkClient.addConnectionWatcher(new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.Expired) {
                completion.setException(new IllegalStateException("ZK session expired"));
            }
        }
    });
    // Always remove the watcher on completion
    completion.addListener(new Runnable() {
        @Override
        public void run() {
            watcherCancellable.cancel();
        }
    }, Threads.SAME_THREAD_EXECUTOR);

    // Step 1. Create a ephemeral sequential node
    final String guid = UUID.randomUUID().toString();
    final String lockPath = String.format("%s/%s-", path, guid);
    OperationFuture<String> future = zkClient.create(lockPath, null, CreateMode.EPHEMERAL_SEQUENTIAL, true);

    Futures.addCallback(future, new FutureCallback<String>() {
        @Override
        public void onSuccess(final String lockNode) {
            // If lock failed due to whatever reason, delete the lock node.
            deleteNodeOnFailure(completion, lockNode);

            // If the lock is completed (mainly due to cancellation), simply abort the lock acquisition logic.
            if (completion.isDone()) {
                return;
            }

            // Step 2-5. Try to determine who is the lock owner and watch for ZK node changes if itself is not the owner.
            doAcquire(completion, waitForLock, guid, lockNode);
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof KeeperException.ConnectionLossException) {
                // Ignore connection exception in create. Going to handle it in next step.
                // See the ZK receipt for details about the possible failure situation that can cause this.
                doAcquire(completion, waitForLock, guid, null);
            } else {
                LOG.error("Exception raised when creating lock node at {}", lockPath, t);
                completion.setException(t);
            }
        }
    });

    // Gets the result from the completion
    try {
        if (interruptible) {
            localLockNode.set(completion.get(timeout, unit));
        } else {
            localLockNode.set(Uninterruptibles.getUninterruptibly(completion, timeout, unit));
        }
        return true;
    } catch (InterruptedException e) {
        completion.cancel(true);
        throw e;
    } catch (TimeoutException e) {
        completion.cancel(true);
        throw e;
    } catch (CancellationException e) {
        // If the completion get cancelled, meaning the lock acquisition is aborted.
        return false;
    }
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.log.DaylightLogger.java

private ListenableFuture<String> requestRunId(String authAccessToken, JsonObject testRun) {
    String jsonStr = testRun.toString();
    String requestUrl = mDaylightUrl + "/api/zumo2/runs?access_token=" + authAccessToken;

    HttpPost request = new HttpPost(requestUrl);
    request.addHeader("Accept", "application/json");

    try {//from w  w w  . j  a v a  2s  .  c  o m
        request.setEntity(new StringEntity(jsonStr, "UTF-8"));
    } catch (UnsupportedEncodingException uee) {
    }

    final SettableFuture<String> result = SettableFuture.create();

    ListenableFuture<HttpURLConnection> internalFuture = execute(request);

    Futures.addCallback(internalFuture, new FutureCallback<HttpURLConnection>() {
        @Override
        public void onFailure(Throwable throwable) {
            result.setException(throwable);
        }

        @Override
        public void onSuccess(HttpURLConnection connection) {
            try {
                int statusCode = connection.getResponseCode();

                if (statusCode == 201) {
                    String content = getContent(connection);
                    JsonObject json = new JsonParser().parse(content).getAsJsonObject();
                    String runId = json.get("run_id").getAsString();
                    result.set(runId);
                } else {
                    result.setException(new Exception("Invalid response status code " + statusCode));
                }
            } catch (Throwable t) {
                result.setException(t);
            }
        }
    });

    return result;
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.log.DaylightLogger.java

private ListenableFuture<String> requestBlobAccessToken(String authAccessToken) {
    String body = "grant_type=urn%3Adaylight%3Aoauth2%3Ashared-access-signature&permissions=rwdl&scope=attachments";
    String requestUrl = mDaylightUrl + "/api/zumo2/storageaccounts/token?access_token=" + authAccessToken;

    HttpPost request = new HttpPost(requestUrl);
    request.addHeader("Content-Type", "application/x-www-form-urlencoded");

    try {/* w w  w .  ja va 2  s  .c  om*/
        request.setEntity(new StringEntity(body, "UTF-8"));
    } catch (UnsupportedEncodingException uee) {
    }

    final SettableFuture<String> result = SettableFuture.create();

    ListenableFuture<HttpURLConnection> internalFuture = execute(request);

    Futures.addCallback(internalFuture, new FutureCallback<HttpURLConnection>() {
        @Override
        public void onFailure(Throwable throwable) {
            result.setException(throwable);
        }

        @Override
        public void onSuccess(HttpURLConnection connection) {
            try {
                int statusCode = connection.getResponseCode();

                if (statusCode == 201) {
                    String content = getContent(connection);
                    JsonObject json = new JsonParser().parse(content).getAsJsonObject();
                    String blobAccessToken = json.get("access_token").getAsString();
                    result.set(blobAccessToken);
                } else {
                    result.setException(new Exception("Invalid response status code " + statusCode));
                }
            } catch (Throwable t) {
                result.setException(t);
            }
        }
    });

    return result;
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.log.DaylightLogger.java

private ListenableFuture<String> requestAuthAccessToken() {
    String url = mDaylightUrl + "/oauth2/token";

    HttpPost request = new HttpPost(url);
    request.addHeader("Content-Type", "application/x-www-form-urlencoded");

    try {/*from   w  w w . ja v  a  2 s . c  o  m*/
        request.setEntity(new StringEntity(
                "grant_type=client_credentials&client_id=" + mClientId + "&client_secret=" + mClientSecret,
                "UTF-8"));
    } catch (UnsupportedEncodingException uee) {
    }

    final SettableFuture<String> result = SettableFuture.create();

    ListenableFuture<HttpURLConnection> internalFuture = execute(request);

    Futures.addCallback(internalFuture, new FutureCallback<HttpURLConnection>() {
        @Override
        public void onFailure(Throwable throwable) {
            result.setException(throwable);
        }

        @Override
        public void onSuccess(HttpURLConnection connection) {
            try {
                int statusCode = connection.getResponseCode();

                if (statusCode == 200) {
                    String content = getContent(connection);
                    JsonObject json = new JsonParser().parse(content).getAsJsonObject();
                    String authAccessToken = json.get("access_token").getAsString();
                    result.set(authAccessToken);
                } else {
                    result.setException(new Exception("Invalid response status code " + statusCode));
                }
            } catch (Throwable t) {
                result.setException(t);
            }
        }
    });

    return result;
}