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:io.v.x.jni.test.fortune.FortuneServerImpl.java

@Override
public ListenableFuture<MultipleStreamingGetOut> multipleStreamingGet(final VContext context, ServerCall call,
        final ServerStream<String, Boolean> stream) {
    final SettableFuture<MultipleStreamingGetOut> future = SettableFuture.create();
    final AtomicInteger numSent = new AtomicInteger(0);
    Futures.addCallback(InputChannels.withCallback(stream, new InputChannelCallback<Boolean>() {
        @Override// w ww.jav  a2 s . c o  m
        public ListenableFuture<Void> onNext(Boolean result) {
            if (lastAddedFortune == null) {
                return Futures.immediateFailedFuture(new NoFortunesException(context));
            }
            return Futures.transform(stream.send(lastAddedFortune), new Function<Void, Void>() {
                @Override
                public Void apply(Void input) {
                    numSent.incrementAndGet();
                    return null;
                }
            });
        }
    }), new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            MultipleStreamingGetOut ret = new MultipleStreamingGetOut();
            ret.total = numSent.get();
            ret.another = numSent.get();
            future.set(ret);
        }

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

From source file:co.cask.cdap.internal.app.runtime.distributed.AbstractProgramTwillRunnable.java

@Override
public void run() {
    LOG.info("Starting metrics service");
    Futures.getUnchecked(Services.chainStart(zkClientService, kafkaClientService, metricsCollectionService,
            streamCoordinatorClient, resourceReporter));

    LOG.info("Starting runnable: {}", name);
    controller = injector.getInstance(getProgramClass()).run(program, programOpts);
    final SettableFuture<ProgramController.State> state = SettableFuture.create();
    controller.addListener(new AbstractListener() {

        @Override/*  w  ww .j av  a  2 s. c o  m*/
        public void alive() {
            runlatch.countDown();
        }

        @Override
        public void init(ProgramController.State currentState, @Nullable Throwable cause) {
            if (currentState == ProgramController.State.ALIVE) {
                alive();
            } else {
                super.init(currentState, cause);
            }
        }

        @Override
        public void completed() {
            state.set(ProgramController.State.COMPLETED);
        }

        @Override
        public void killed() {
            state.set(ProgramController.State.KILLED);
        }

        @Override
        public void error(Throwable cause) {
            LOG.error("Program runner error out.", cause);
            state.setException(cause);
        }
    }, MoreExecutors.sameThreadExecutor());

    try {
        state.get();
        LOG.info("Program stopped.");
    } catch (InterruptedException e) {
        LOG.warn("Program interrupted.", e);
    } catch (ExecutionException e) {
        LOG.error("Program execution failed.", e);
        if (propagateServiceError()) {
            throw Throwables.propagate(Throwables.getRootCause(e));
        }
    } finally {
        // Always unblock the handleCommand method if it is not unblocked before (e.g if program failed to start).
        // The controller state will make sure the corresponding command will be handled correctly in the correct state.
        runlatch.countDown();
    }
}

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

private synchronized void handleSuccessfulJoinCondition(SettableFuture<Lease> leasePromise) {
    try {/* w  w w  . ja  v a2s. co  m*/
        // This is called asynchronously when join condition has been met,
        // so we need to re-check the intended state
        if (state == State.JOINED) {
            membership = new ServiceNodeMembership(zkClient, serviceName, address);
            Futures.addCallback(membership.create(leasePromise), new FutureCallback<Void>() {
                @Override
                public void onSuccess(Void result) {
                    logger.info("Created a znode for {} with value {}", serviceName, address);
                }

                @Override
                public void onFailure(Throwable t) {
                    logger.info("Resetting the state to NOT_JOINED for {}", serviceName);
                    cleanup();
                    state = State.NOT_JOINED;
                }
            });
        } else {
            cleanup();
        }
    } catch (Exception e) {
        if (state == State.JOINED) {
            // Failed to create the znode. Reset the state to NOT_JOINED so that we
            // can retry calling join() again.
            state = State.NOT_JOINED;
        }
        leasePromise.setException(e);
    }
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncContext.java

/**
 * Pushes all pending operations up to the remote store.
 *
 * @return A ListenableFuture that is done when operations have been pushed.
 */// w  w  w  . j ava 2  s .c  om
public ListenableFuture<Void> push() {
    final MobileServiceSyncContext thisContext = this;
    final SettableFuture<Void> result = SettableFuture.create();

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                thisContext.pushContext();

                result.set(null);
            } catch (Throwable throwable) {
                result.setException(throwable);
            }
        }
    }).start();

    return result;
}

From source file:com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.java

private ListenableFuture<String> createRegistrationId() {

    String path = PNS_API_URL + "/registrationids/";

    final SettableFuture<String> resultFuture = SettableFuture.create();
    ListenableFuture<ServiceFilterResponse> serviceFilterFuture = mHttpClient.request(path, null, "POST", null,
            null);/*from w w w. ja v a  2 s . co  m*/

    Futures.addCallback(serviceFilterFuture, new FutureCallback<ServiceFilterResponse>() {
        @Override
        public void onFailure(Throwable exception) {
            resultFuture.setException(exception);
        }

        @Override
        public void onSuccess(ServiceFilterResponse response) {
            for (Header header : response.getHeaders()) {
                if (header.getName().equalsIgnoreCase(NEW_REGISTRATION_LOCATION_HEADER)) {

                    URI regIdUri = null;
                    try {
                        regIdUri = new URI(header.getValue());
                    } catch (URISyntaxException e) {
                        resultFuture.setException(e);

                        return;
                    }

                    String[] pathFragments = regIdUri.getPath().split("/");
                    String result = pathFragments[pathFragments.length - 1];

                    resultFuture.set(result);
                }
            }
        }
    });

    return resultFuture;
}

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

private ListenableFuture<Void> fileOp(final String operation, String source, String destination,
        boolean overwrite, String library) {
    final SettableFuture<Void> result = SettableFuture.create();
    String url;//from ww w.j av a 2 s .  c  o m

    String targetEncoded = urlEncode("target='" + destination + "', overwrite=" + Boolean.toString(overwrite));

    if (library == null || library.length() == 0) {
        url = getSiteUrl()
                + String.format("_api/files('%s')/%s(%s)", urlEncode(source), operation, targetEncoded);
    } else {
        url = getSiteUrl() + String.format("_api/web/lists/getbytitle('%s')/files('%s')/%s(%s)",
                urlEncode(library), urlEncode(source), operation, targetEncoded);
    }

    ListenableFuture<JSONObject> request = executeRequestJsonWithDigest(url, "POST", null, null);

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

        @Override
        public void onSuccess(JSONObject json) {
            result.set(null);
        }
    });
    return result;
}

From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceJsonTable.java

/**
 * Make the request to the mobile service witht the query URL
 *
 * @param url The query url//from w  w  w .j a va 2  s  .c o m
 * @param features The features used in the request
 */
private ListenableFuture<JsonElement> executeUrlQuery(final String url,
        EnumSet<MobileServiceFeatures> features) {
    final SettableFuture<JsonElement> future = SettableFuture.create();

    ListenableFuture<Pair<JsonElement, ServiceFilterResponse>> internalFuture = executeGetRecords(url,
            features);

    Futures.addCallback(internalFuture, new FutureCallback<Pair<JsonElement, ServiceFilterResponse>>() {
        @Override
        public void onFailure(Throwable exc) {
            future.setException(exc);
        }

        @Override
        public void onSuccess(Pair<JsonElement, ServiceFilterResponse> result) {

            String nextLinkHeaderValue = getHeaderValue(result.second.getHeaders(), "Link");

            if (nextLinkHeaderValue != null) {

                JsonObject jsonResult = new JsonObject();

                String nextLink = nextLinkHeaderValue.replace("; rel=next", "");

                jsonResult.addProperty("nextLink", nextLink);
                jsonResult.add("results", result.first);

                future.set(jsonResult);

            } else {
                future.set(result.first);
            }
        }
    });

    return future;
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncContext.java

/**
 * Initializes the sync context.//from w w  w  .j a v  a 2  s. co m
 *
 * @param store   An instance of MobileServiceLocalStore
 * @param handler An instance of MobileServiceSyncHandler
 * @return A ListenableFuture that is done when sync context has
 * initialized.
 */
public ListenableFuture<Void> initialize(final MobileServiceLocalStore store,
        final MobileServiceSyncHandler handler) {
    final MobileServiceSyncContext thisContext = this;
    final SettableFuture<Void> result = SettableFuture.create();

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                thisContext.initializeContext(store, handler);

                result.set(null);
            } catch (Throwable throwable) {
                result.setException(throwable);
            }
        }
    }).start();

    return result;
}

From source file:com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.java

/**
 * Unregisters the client for all notifications
 *
 * @param pnsHandle PNS specific identifier
 * @return Future with TemplateRegistration Information
 *///from ww w  .  j a v  a 2 s  . c o m
public ListenableFuture<Void> unregisterAll(String pnsHandle) {

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

    ListenableFuture<ArrayList<Registration>> fullRegistrationInformationFuture = getFullRegistrationInformation(
            pnsHandle);

    Futures.addCallback(fullRegistrationInformationFuture, new FutureCallback<ArrayList<Registration>>() {
        @Override
        public void onFailure(Throwable exception) {
            resultFuture.setException(exception);
        }

        @Override
        public void onSuccess(ArrayList<Registration> registrations) {

            ListenableFuture<Void> unregisterAllInternalFuture = unregisterAllInternal(registrations);

            Futures.addCallback(unregisterAllInternalFuture, new FutureCallback<Void>() {
                @Override
                public void onFailure(Throwable exception) {
                    resultFuture.setException(exception);
                }

                @Override
                public void onSuccess(Void v) {
                    resultFuture.set(null);
                }
            });
        }
    });

    return resultFuture;
}

From source file:com.microsoft.tooling.msservices.helpers.auth.AADManagerImpl.java

private <V> void authenticatedRequest(@NotNull final UserInfo userInfo, @NotNull final String resource,
        @NotNull final String title, @NotNull final RequestCallback<ListenableFuture<V>> requestCallback,
        final SettableFuture<V> wrappedFuture) {
    try {/*from w w  w . j  a v a2 s .c  o  m*/
        AuthenticationResult authenticationResult = getAuthenticationResult(userInfo, resource);

        Futures.addCallback(requestCallback.execute(authenticationResult.getAccessToken()),
                new FutureCallback<V>() {
                    @Override
                    public void onSuccess(V val) {
                        wrappedFuture.set(val);
                    }

                    @Override
                    public void onFailure(Throwable throwable) {
                        if (isErrorResourceUnauthorized(throwable)) {
                            unauthenticatedRequest(userInfo, resource, title, requestCallback, wrappedFuture);
                        } else {
                            wrappedFuture.setException(throwable);
                        }
                    }
                });
    } catch (Throwable e) {
        wrappedFuture.setException(e);
    }
}