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.alm.plugin.authentication.facades.VsoAuthInfoProvider.java

@Override
public void getAuthenticationInfoAsync(final String serverUri, final AuthenticationInfoCallback callback) {
    final SettableFuture<AuthenticationInfo> authenticationInfoFuture = SettableFuture
            .<AuthenticationInfo>create();

    // start the authentication on yet another thread
    final Runnable authenticateTask = new Runnable() {
        @Override//from  w ww .  j  a v  a 2  s  .  c  o m
        public void run() {

            // Callback for the Device Flow dialog to cancel the current authenticating process.
            // Normally this is hooked up to the cancel button so if user cancels, we do not wait forever in
            // a polling loop.  This doesn't stop the polling currently, there is no clean way to shutdown a thread.
            // We just let the GUI continue, and forget the polling thread.  It eventually will stop after certain
            // period of time
            // TODO: add an explicit time limit for the polling to stop in the auth library, right now it depends
            // on how long the server think it is reasonable
            final Action<String> cancellationCallback = new Action<String>() {
                @Override
                public void call(final String reasonForCancel) {
                    authenticationInfoFuture.setException(new AuthorizationException(reasonForCancel));
                }
            };

            // Must share the same accessTokenStore with the member variable vstsPatAuthenticator to avoid prompt the user
            // when we generate PAT
            final OAuth2Authenticator oAuth2Authenticator = OAuth2Authenticator.getAuthenticator(CLIENT_ID,
                    REDIRECT_URL, accessTokenStore, deviceFlowResponsePrompt.getCallback(cancellationCallback));

            final JaxrsClientProvider jaxrsClientProvider = new JaxrsClientProvider(oAuth2Authenticator);

            try {
                AuthenticationInfo authenticationInfo = null;
                String errorMessage = null;
                final Client client = jaxrsClientProvider.getClient();

                if (client != null) {
                    //Or we could reconsider the name of the token.  Now we call Profile endpoint just to get the email address
                    //which is used in token description, but do we need it?  User can only view PATs after they login, and
                    //at that time user knows which account/email they are logged in under already.  So the email provides
                    //no additional value.
                    final AccountHttpClient accountHttpClient = new AccountHttpClient(client,
                            OAuth2Authenticator.APP_VSSPS_VISUALSTUDIO);

                    final Profile me = accountHttpClient.getMyProfile();
                    final String emailAddress = me.getCoreAttributes().getEmailAddress().getValue();

                    final String tokenDescription = AuthHelper.getTokenDescription(emailAddress);

                    final Token token = vstsPatAuthenticator.getPersonalAccessToken(
                            VsoTokenScope.or(VsoTokenScope.CodeAll, VsoTokenScope.WorkRead,
                                    VsoTokenScope.BuildAccess, VsoTokenScope.BuildExecute),
                            tokenDescription, PromptBehavior.AUTO);

                    if (token != null) {
                        authenticationInfo = new AuthenticationInfo(me.getId().toString(), token.Value,
                                serverUri, emailAddress);
                    } else {
                        errorMessage = "Failed to get a Personal Access Token";
                    }
                } else {
                    errorMessage = "Failed to get authenticated jaxrs client.";
                }

                if (authenticationInfo != null) {
                    authenticationInfoFuture.set(authenticationInfo);
                } else {
                    authenticationInfoFuture.setException(new AuthorizationException(errorMessage));
                }

            } catch (Throwable t) {
                authenticationInfoFuture.setException(t);
            }
        }
    };
    Futures.addCallback(authenticationInfoFuture, callback);

    // start the authentication job
    executorService.submit(authenticateTask);
}

From source file:co.cask.cdap.data.stream.AbstractStreamCoordinator.java

@Override
public ListenableFuture<Long> changeTTL(final StreamConfig streamConfig, final long newTTL) {
    return Futures.transform(
            propertyStore.get().update(streamConfig.getName(), new PropertyUpdater<StreamProperty>() {
                @Override//from w w w.  j av  a  2  s  .  c om
                public ListenableFuture<StreamProperty> apply(@Nullable final StreamProperty property) {
                    final SettableFuture<StreamProperty> resultFuture = SettableFuture.create();
                    updateExecutor.execute(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                int currentGeneration = (property == null)
                                        ? StreamUtils.getGeneration(streamConfig)
                                        : property.getGeneration();

                                StreamConfig newConfig = new StreamConfig(streamConfig.getName(),
                                        streamConfig.getPartitionDuration(), streamConfig.getIndexInterval(),
                                        newTTL, streamConfig.getLocation());
                                saveConfig(newConfig);
                                resultFuture.set(new StreamProperty(currentGeneration, newTTL));
                            } catch (IOException e) {
                                resultFuture.setException(e);
                            }
                        }
                    });
                    return resultFuture;
                }
            }), new Function<StreamProperty, Long>() {
                @Override
                public Long apply(StreamProperty property) {
                    return property.getTTL();
                }
            });
}

From source file:com.microsoft.office365.starter.helpers.AuthenticationController.java

/**
 * Description: Calls AuthenticationContext.acquireToken(...) once to initialize with
 * user's credentials and avoid interactive prompt on later calls.
 * If all tokens expire, app must call initialize() again to prompt user interactively and
 * set up authentication context.//w w w. j  a  va 2 s.co m
 *
 * @return A signal to wait on before continuing execution.
 */
public SettableFuture<Boolean> initialize() {

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

    if (verifyAuthenticationContext()) {
        getAuthenticationContext().acquireToken(this.contextActivity, this.resourceId, Constants.CLIENT_ID,
                Constants.REDIRECT_URI, PromptBehavior.Auto,
                new AuthenticationCallback<AuthenticationResult>() {

                    @Override
                    public void onSuccess(final AuthenticationResult authenticationResult) {

                        if (authenticationResult != null
                                && authenticationResult.getStatus() == AuthenticationStatus.Succeeded) {
                            dependencyResolver = new ADALDependencyResolver(getAuthenticationContext(),
                                    resourceId, Constants.CLIENT_ID);
                            storeUserId(contextActivity, authenticationResult);
                            result.set(true);
                        }
                    }

                    @Override
                    public void onError(Exception t) {
                        result.setException(t);
                    }

                    private void storeUserId(final Activity rootActivity,
                            final AuthenticationResult authenticationResult) {

                        UserInfo userInfo = authenticationResult.getUserInfo();
                        SharedPreferences sharedPref = rootActivity.getPreferences(Context.MODE_PRIVATE);

                        if (userInfo != null) {
                            mLoggedInUser = userInfo.getUserId();
                            Editor editor = sharedPref.edit();
                            editor.putString("UserId", mLoggedInUser);
                            editor.putString("DisplayName",
                                    userInfo.getGivenName() + " " + userInfo.getFamilyName());
                            editor.apply();
                        } else {
                            mLoggedInUser = sharedPref.getString("UserId", "");
                        }
                    }
                });
    } else {
        result.setException(new Throwable("Auth context verification failed. Did you set a context activity?"));
    }
    return result;
}

From source file:com.facebook.swift.service.ThriftClientManager.java

public <T, C extends NiftyClientChannel> ListenableFuture<T> createClient(
        final NiftyClientConnector<C> connector, final Class<T> type, final Duration connectTimeout,
        final Duration readTimeout, final Duration writeTimeout, final String clientName,
        HostAndPort socksProxy) {/*from ww  w .  j  a  v a2  s  .c  o  m*/
    NiftyClientChannel channel = null;
    try {
        final SettableFuture<T> clientFuture = SettableFuture.create();
        ListenableFuture<C> connectFuture = niftyClient.connectAsync(connector, connectTimeout, readTimeout,
                writeTimeout, this.toSocksProxyAddress(socksProxy));
        Futures.addCallback(connectFuture, new FutureCallback<C>() {
            @Override
            public void onSuccess(C result) {
                NiftyClientChannel channel = result;

                if (readTimeout.toMillis() > 0) {
                    channel.setReceiveTimeout(readTimeout);
                }
                if (writeTimeout.toMillis() > 0) {
                    channel.setSendTimeout(writeTimeout);
                }
                clientFuture.set(createClient(channel, type,
                        Strings.isNullOrEmpty(clientName) ? connector.toString() : clientName));
            }

            @Override
            public void onFailure(Throwable t) {
                clientFuture.setException(t);
            }
        });
        return clientFuture;
    } catch (RuntimeException | Error e) {
        if (channel != null) {
            channel.close();
        }
        throw e;
    }
}

From source file:co.cask.hydrator.plugin.RunExternalProgramExecutor.java

/**
 * Sends input to the executable threads, and emits the output structured records.
 *
 * @param line - Space separated sequence of the inputs that will be passed as STDIN to the executable binary.
 * @param emitter/*from   w ww . j  a  va  2s.c o m*/
 * @param structuredRecord
 * @param outputSchema
 */
void submit(String line, Emitter<StructuredRecord> emitter, StructuredRecord structuredRecord,
        Schema outputSchema) {
    SettableFuture<String> completion = SettableFuture.create();
    try {
        eventQueue.put(new Event(line, completion));
        Futures.successfulAsList(completion).get();

        // Read the output and emit the structured record.
        for (String output : outputList) {
            StructuredRecord.Builder builder = StructuredRecord.builder(outputSchema);
            for (Schema.Field field : outputSchema.getFields()) {
                if (structuredRecord.getSchema().getField(field.getName()) != null) {
                    builder.set(field.getName(), structuredRecord.get(field.getName()));
                } else {
                    if (field.getSchema().getType().equals(Schema.Type.STRING)) {
                        builder.set(field.getName(), output);
                    } else {
                        builder.convertAndSet(field.getName(), output);
                    }
                }
            }
            emitter.emit(builder.build());
            outputList.clear();
        }
    } catch (Exception e) {
        completion.setException(e);
    }
}

From source file:org.attribyte.api.http.impl.jetty.JettyClient.java

@Override
public ListenableFuture<org.attribyte.api.http.Response> asyncSend(org.attribyte.api.http.Request request,
        RequestOptions options) {// ww  w  . ja va 2  s . c o  m
    final SettableFuture<org.attribyte.api.http.Response> fut = SettableFuture.create();
    toJettyRequest(request).followRedirects(options.followRedirects)
            .send(new BufferingResponseListener(options.maxResponseBytes) {
                @Override
                public void onComplete(Result result) {
                    if (!result.isFailed()) {
                        ResponseBuilder builder = new ResponseBuilder();
                        Response response = result.getResponse();
                        builder.setStatusCode(response.getStatus());
                        HttpFields headers = response.getHeaders();
                        for (HttpField header : headers) {
                            builder.addHeader(header.getName(), header.getValue());
                        }
                        byte[] responseContent = getContent();
                        if (responseContent != null) {
                            builder.setBody(responseContent);
                        }
                        fut.set(builder.create());
                    } else {
                        fut.setException(result.getFailure());
                    }
                }
            });

    return fut;
}

From source file:eu.esdihumboldt.hale.io.haleconnect.internal.HaleConnectServiceImpl.java

private ApiCallback<Feedback> createUploadFileCallback(final SettableFuture<Boolean> future,
        final ProgressIndicator progress, final File file, final int totalWork) {
    return new ApiCallback<Feedback>() {

        AtomicLong chunkWritten = new AtomicLong(0);
        AtomicLong bytesReported = new AtomicLong(0);

        @Override/* w w  w  . j  a  va 2s . c o  m*/
        public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
            // not required
        }

        @Override
        public void onFailure(com.haleconnect.api.projectstore.v1.ApiException e, int statusCode,
                Map<String, List<String>> responseHeaders) {
            progress.end();
            future.setException(new HaleConnectException(e.getMessage(), e, statusCode, responseHeaders));
        }

        @Override
        public void onSuccess(Feedback result, int statusCode, Map<String, List<String>> responseHeaders) {
            if (result.getError()) {
                log.error(MessageFormat.format("Error uploading project file \"{0}\": {1}",
                        file.getAbsolutePath(), result.getMessage()));
                future.set(false);
            } else {
                future.set(true);
            }
            progress.end();
        }

        @Override
        public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
            // bytesWritten contains the accumulated amount of bytes written
            if (totalWork != ProgressIndicator.UNKNOWN) {
                // Wait until at least 1 KiB was written
                long chunk = chunkWritten.get();
                chunk += bytesWritten - bytesReported.get();
                if (chunk >= 1024) {
                    long workToReport = chunk >> 10;
                    // cannot overflow, total size in KiB
                    // is guaranteed to be < Integer.MAX_VALUE
                    progress.advance(Math.toIntExact(workToReport));
                    chunk -= workToReport << 10;
                    // chunkWritten now always < 1024
                }
                chunkWritten.set(chunk);
                bytesReported.set(bytesWritten);
            }
        }
    };
}

From source file:org.waveprotocol.box.server.waveletstate.block.BlockWaveletStateImpl.java

Collection<ListenableFuture<Block>> executeReadBlocksRequest(final Set<String> blockIds) {
    List<ListenableFuture<Block>> futures = CollectionUtils.newLinkedList();
    for (String blockId : blockIds) {
        SettableFuture<Block> future = SettableFuture.<Block>create();
        futures.add(future);//  w  w w. j a v a  2 s  .com
        readBlocksFutures.put(blockId, future);
    }
    persistExecutor.execute(new Runnable() {

        @Override
        public void run() {
            try {
                Collection<Block> blocks = blockAccess.readBlocks(blockIds);
                for (Block block : blocks) {
                    registerBlock(block);
                    SettableFuture<Block> future = readBlocksFutures.remove(block.getBlockId());
                    if (future != null) {
                        future.set(block);
                    }
                }
            } catch (Exception ex) {
                for (String blockId : blockIds) {
                    SettableFuture<Block> future = readBlocksFutures.remove(blockId);
                    if (future != null) {
                        future.setException(ex);
                    }
                }
            }
        }
    });
    return futures;
}

From source file:com.yahoo.yqlplus.engine.internal.scope.ScopedTracingExecutor.java

public <T> ListenableFuture<T> withTimeoutAsync(final Callable<ListenableFuture<T>> callable,
        final Timeout tracker) {
    final SettableFuture<T> result = SettableFuture.create();
    final TimeUnit units = tracker.getTickUnits();
    final ListenableFuture<ListenableFuture<T>> source = submit(callable);
    Futures.addCallback(source, new FutureCallback<ListenableFuture<T>>() {
        @Override/*from w  w w .j  a v a  2s  .co m*/
        public void onSuccess(@Nullable ListenableFuture<T> next) {
            try {
                long remaining = tracker.verify();
                final ScheduledFuture<?> remainingFuture = timers
                        .schedule(new TimeoutTask<>(next, result, remaining, units), remaining, units);
                Futures.addCallback(next, new FutureCallback<T>() {
                    @Override
                    public void onSuccess(T out) {
                        remainingFuture.cancel(false);
                        result.set(out);
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        remainingFuture.cancel(false);
                        result.setException(t);
                    }
                }, ScopedTracingExecutor.this);
            } catch (TimeoutException e) {
                next.cancel(true);
                result.setException(e);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            result.setException(t);
        }
    });
    return new WrappedListenableFuture<>(result);
}

From source file:com.microsoftopentechnologies.intellij.helpers.o365.Office365RestAPIManager.java

private <T> ListenableFuture<T> requestWithToken(final RequestCallback<T> requestCallback)
        throws ParseException {
    final SettableFuture<T> wrappedFuture = SettableFuture.create();
    Futures.addCallback(requestCallback.execute(), new FutureCallback<T>() {
        @Override/*from   w  w  w  .  j av a  2s. co  m*/
        public void onSuccess(T val) {
            wrappedFuture.set(val);
        }

        @Override
        public void onFailure(Throwable throwable) {
            if (isErrorUnauthorized(throwable)) {
                try {
                    requestWithRefreshToken(requestCallback, wrappedFuture);
                } catch (ParseException e) {
                    wrappedFuture.setException(throwable);
                }
            } else {
                wrappedFuture.setException(throwable);
            }
        }
    });

    return wrappedFuture;
}