Example usage for com.google.common.util.concurrent Futures addCallback

List of usage examples for com.google.common.util.concurrent Futures addCallback

Introduction

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

Prototype

public static <V> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback) 

Source Link

Document

Registers separate success and failure callbacks to be run when the Future 's computation is java.util.concurrent.Future#isDone() complete or, if the computation is already complete, immediately.

Usage

From source file:com.continuuity.weave.internal.zookeeper.FailureRetryZKClient.java

@Override
public OperationFuture<Stat> exists(final String path, final Watcher watcher) {
    final SettableOperationFuture<Stat> result = SettableOperationFuture.create(path,
            Threads.SAME_THREAD_EXECUTOR);
    Futures.addCallback(super.exists(path, watcher), new OperationFutureCallback<Stat>(OperationType.EXISTS,
            System.currentTimeMillis(), path, result, new Supplier<OperationFuture<Stat>>() {
                @Override//from  w  ww  .j a v a2s .  c om
                public OperationFuture<Stat> get() {
                    return FailureRetryZKClient.super.exists(path, watcher);
                }
            }));
    return result;
}

From source file:dynamite.zafroshops.app.fragment.ReviewDialogFragment.java

@NonNull
@Override/*from  w  w  w .j  a va  2s .  co  m*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
    rating = 0;
    zopID = getArguments().getString(DIALOG_ZOP_ID);
    location = (Location) getArguments().getSerializable(DIALOG_ZOP_LOCATION);

    Activity activity = getActivity();
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    LayoutInflater inflater = activity.getLayoutInflater();
    final View view = inflater.inflate(R.layout.review_dialog, null);

    builder.setView(view).setTitle(R.string.app_name)
            .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MobileConfirmation confirmation = new MobileConfirmation();
                    Boolean confirmed = false;
                    int id = ((RadioGroup) view.findViewById(R.id.review_confirmation_group))
                            .getCheckedRadioButtonId();

                    if (id == view.findViewById(R.id.review_confirmation_know).getId()) {
                        confirmed = true;
                    } else if (id == view.findViewById(R.id.review_confirmation_been).getId()) {
                        confirmed = false;
                    }

                    confirmation.ZopID = Integer.parseInt(zopID);
                    confirmation.Comments = ((EditText) view.findViewById(R.id.review_comments)).getText()
                            .toString();
                    confirmation.Confirmed = confirmed;
                    confirmation.ConfirmedBy = "Android";
                    confirmation.ConfirmedDate = Calendar.getInstance().getTime();
                    confirmation.Rating = rating;

                    // submit
                    ListenableFuture<JsonElement> result = MainActivity.MobileClient
                            .invokeApi("mobileConfirmation", confirmation, JsonElement.class);
                    Futures.addCallback(result, new FutureCallback<JsonElement>() {
                        @Override
                        public void onSuccess(JsonElement result) {
                            ((MenuItem) view.findViewById(R.id.menu_zop_review)).setEnabled(false);
                        }

                        @Override
                        public void onFailure(@NonNull Throwable t) {

                        }
                    });
                }
            }).setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });

    RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.review_confirmation_group);

    view.findViewById(R.id.review_rating).setVisibility(View.INVISIBLE);
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.review_confirmation_been) {
                view.findViewById(R.id.review_rating).setVisibility(View.VISIBLE);
            } else {
                view.findViewById(R.id.review_rating).setVisibility(View.INVISIBLE);
            }
        }
    });

    return builder.create();
}

From source file:ratpack.exec.Fulfiller.java

/**
 * Fulfills via the given ListenableFuture.
 *
 * @param listenableFuture the future to use to fulfill
 *///from  w  ww . j a  v a  2 s  .c o m
default void accept(ListenableFuture<? extends T> listenableFuture) {
    Futures.addCallback(listenableFuture, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            success(result);
        }

        @Override
        public void onFailure(Throwable t) {
            error(t);
        }
    });
}

From source file:com.microsoft.office.integration.test.ContactsAsyncTestCase.java

private void deleteAndCheck() throws Exception {
    removeContact();//ww  w  .  j a v a 2s .  c om
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getContacts().getAsync(contact.getId()), new FutureCallback<IContact>() {
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        public void onSuccess(IContact result) {
            try {
                assertNull(result);
            } catch (Throwable t) {
                reportError(t);
            }
            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:org.opendaylight.openflowplugin.impl.services.SalMeterServiceImpl.java

@Override
public Future<RpcResult<AddMeterOutput>> addMeter(final AddMeterInput input) {
    addMeter.getDeviceContext().getDeviceMeterRegistry().store(input.getMeterId());

    final ListenableFuture<RpcResult<AddMeterOutput>> resultFuture = addMeter.handleServiceCall(input);
    Futures.addCallback(resultFuture, new FutureCallback<RpcResult<AddMeterOutput>>() {

        @Override//ww  w. j  ava  2s  .  c  o m
        public void onSuccess(@Nullable RpcResult<AddMeterOutput> result) {
            if (result.isSuccessful()) {
                LOG.debug("Meter add finished without error, id={}", input.getMeterId());
                addIfNecessaryToDS(input.getMeterId(), input);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error("Meter add failed for id={}. Exception {}", input.getMeterId(), t);
        }
    });

    return resultFuture;
}

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

private void startRetry(final SettableFuture<Response> future, final Supplier<ListenableFuture<Response>> code,
        final long deadline, final long delayMillis, final URI uri) {

    ListenableFuture<Response> codeFuture;
    try {/*from  w  w  w  .  j  a  v  a2  s.  c o m*/
        codeFuture = code.get();
    } catch (Exception e) {
        log.debug("Failed to connect to {}, retrying in {} seconds.", uri.toString(),
                TimeUnit.MILLISECONDS.toSeconds(delayMillis));
        log.debug("Specific reason for connection failure follows", e);
        handleFailure(future, code, deadline, delayMillis, e, uri);
        return;
    }

    Futures.addCallback(codeFuture, new FutureCallback<Response>() {
        @Override
        public void onSuccess(Response result) {
            future.set(result);
        }

        @Override
        public void onFailure(@NotNull Throwable t) {
            log.warn("Failed to connect to {}, retrying in {} seconds. Exception chain was: {} ",
                    uri.toString(), TimeUnit.MILLISECONDS.toSeconds(delayMillis), getChainAsString(t));
            log.debug("Specific reason for connection failure follows", t);
            handleFailure(future, code, deadline, delayMillis, t, uri);
        }
    });
}

From source file:com.microsoft.services.odata.BaseODataContainer.java

@Override
protected ListenableFuture<ODataResponse> oDataExecute(Request request) {
    final SettableFuture<ODataResponse> result = SettableFuture.create();
    final Logger logger = resolver.getLogger();

    try {/*from ww w  .  j a v  a 2s. c o m*/
        request.getUrl().setBaseUrl(this.url);
        String fullUrl = request.getUrl().toString();

        String executionInfo = String.format("URL: %s - HTTP VERB: %s", fullUrl, request.getVerb());
        logger.log("Start preparing OData execution for " + executionInfo, LogLevel.INFO);

        if (request.getContent() != null) {
            logger.log("With " + request.getContent().length + " bytes of payload", LogLevel.INFO);
        }

        HttpTransport httpTransport = resolver.getHttpTransport();

        String userAgent = resolver.getPlatformUserAgent(this.getClass().getCanonicalName());
        request.addHeader(Constants.USER_AGENT_HEADER, userAgent);
        request.addHeader(Constants.TELEMETRY_HEADER, userAgent);
        request.addHeader(Constants.CONTENT_TYPE_HEADER, Constants.JSON_CONTENT_TYPE);
        request.addHeader(Constants.ACCEPT_HEADER, Constants.JSON_CONTENT_TYPE);
        request.addHeader(Constants.ODATA_VERSION_HEADER, Constants.ODATA_VERSION);
        request.addHeader(Constants.ODATA_MAXVERSION_HEADER, Constants.ODATA_MAXVERSION);

        if (request.getHeaders() != null) {
            for (String key : request.getHeaders().keySet()) {
                request.addHeader(key, request.getHeaders().get(key));
            }
        }

        boolean credentialsSet = false;

        Credentials cred = resolver.getCredentials();
        if (cred != null) {
            cred.prepareRequest(request);
            credentialsSet = true;
        }

        if (!credentialsSet) {
            logger.log("Executing request without setting credentials", LogLevel.WARNING);
        }

        logger.log("Request Headers: ", LogLevel.VERBOSE);
        for (String key : request.getHeaders().keySet()) {
            logger.log(key + " : " + request.getHeaders().get(key), LogLevel.VERBOSE);
        }

        final ListenableFuture<Response> future = httpTransport.execute(request);
        logger.log("OData request executed", LogLevel.INFO);

        Futures.addCallback(future, new FutureCallback<Response>() {

            @Override
            public void onSuccess(Response response) {
                try {
                    logger.log("OData response received", LogLevel.INFO);

                    logger.log("Reading response data...", LogLevel.VERBOSE);
                    byte[] data = readAllBytes(response.getStream());
                    logger.log(data.length + " bytes read from response", LogLevel.VERBOSE);

                    int status = response.getStatus();
                    logger.log("Response Status Code: " + status, LogLevel.INFO);

                    try {
                        logger.log("Closing response", LogLevel.VERBOSE);
                        response.close();
                    } catch (Throwable t) {
                        logger.log("Error closing response: " + t.toString(), LogLevel.ERROR);
                        result.setException(t);
                        return;
                    }

                    ODataResponse odataResponse = new ODataResponseImpl(data, response);
                    if (status < 200 || status > 299) {
                        logger.log("Invalid status code. Processing response content as String",
                                LogLevel.VERBOSE);
                        String responseData = new String(data, Constants.UTF8_NAME);
                        String message = "Response status: " + response.getStatus() + "\n"
                                + "Response content: " + responseData;
                        logger.log(message, LogLevel.ERROR);
                        result.setException(new ODataException(odataResponse, message));
                        return;
                    }
                    result.set(odataResponse);
                } catch (Throwable t) {
                    logger.log("Unexpected error: " + t.toString(), LogLevel.ERROR);
                    ODataResponse odataResponse = new ODataResponseImpl(null, response);
                    result.setException(new ODataException(odataResponse, t));
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                result.setException(throwable);
            }
        });
    } catch (Throwable t) {
        result.setException(t);
    }
    return result;

}

From source file:com.microsoft.assetmanagement.AssetApplication.java

/**
 * Authenticate.//from w w w . ja  v a  2s  . c om
 * 
 * @param activity
 *            the activity
 * @return the office future
 */
public ListenableFuture<Credentials> authenticate(Activity activity) {
    final SettableFuture<Credentials> result = SettableFuture.create();

    String method = mPreferences.getAuthenticationMethod();
    if (method.equals(Constants.AUTHENTICATIONMETHOD_COOKIES)) {
        ListenableFuture<CookieCredentials> future = SharepointCookieCredentials
                .requestCredentials(mPreferences.getSharepointServer(), activity);

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

            @Override
            public void onSuccess(CookieCredentials credentials) {
                mCredentials = credentials;
                result.set(credentials);
            }
        });
    } else if (method.equals(Constants.AUTHENTICATIONMETHOD_AAD)) {
        getAuthenticationContext(activity).acquireToken(activity, mPreferences.getSharepointServer(),
                mPreferences.getClientId(), mPreferences.getRedirectUrl(), PromptBehavior.Auto,

                new AuthenticationCallback<AuthenticationResult>() {

                    @Override
                    public void onSuccess(AuthenticationResult authenticationResult) {
                        // once succeeded we create a credentials instance
                        // using the token from ADAL
                        mCredentials = new OAuthCredentials(authenticationResult.getAccessToken());
                        result.set(mCredentials);
                    }

                    @Override
                    public void onError(Exception exc) {
                        result.setException(exc);
                    }
                });
    } else {
        String userName = mPreferences.getNTLMUser();
        String password = mPreferences.getNTLMPassword();
        mCredentials = new BasicAuthenticationCredentials(userName, password);
        result.set(mCredentials);
    }
    return result;
}

From source file:org.opendaylight.mdsal.dom.broker.ShardedDOMReadTransactionAdapter.java

@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    checkRunning();/*  www . j a v a 2 s . com*/
    LOG.debug("{}: Invoking read at {}:{}", txIdentifier, store, path);
    final ListenerRegistration<DOMDataTreeListener> reg;
    final SettableFuture<Optional<NormalizedNode<?, ?>>> initialDataTreeChangeFuture = SettableFuture.create();
    try {
        reg = service.registerListener(new ReadShardedListener(initialDataTreeChangeFuture),
                Collections.singleton(new DOMDataTreeIdentifier(store, path)), false, Collections.emptyList());
        registrations.add(reg);
    } catch (final DOMDataTreeLoopException e) {
        // This should not happen, we are not specifying any
        // producers when registering listener
        throw new IllegalStateException("Loop in listener and producers detected", e);
    }

    // After data tree change future is finished, we can close the listener registration
    Futures.addCallback(initialDataTreeChangeFuture, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
        @Override
        public void onSuccess(@Nullable final Optional<NormalizedNode<?, ?>> result) {
            reg.close();
        }

        @Override
        public void onFailure(final Throwable throwable) {
            reg.close();
        }
    });

    return Futures.makeChecked(initialDataTreeChangeFuture, ReadFailedException.MAPPER);
}

From source file:org.eclipse.osee.executor.admin.internal.ExecutorAdminImpl.java

@Override
public <T> Future<T> schedule(String id, Callable<T> callable, ExecutionCallback<T> callback) {
    ListenableFuture<T> listenableFuture = getExecutor(id).submit(callable);
    if (callback != null) {
        FutureCallback<T> futureCallback = asFutureCallback(callback);
        Futures.addCallback(listenableFuture, futureCallback);
    }/*from  w w w.  j  a  va2  s.c o  m*/
    return listenableFuture;
}