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:eu.esdihumboldt.hale.ui.service.project.ProjectResourcesUtil.java

/**
 * Execute the given I/O provider with the given I/O advisor.
 * //from   w  w w . j av a2 s  . c om
 * @param provider the I/O provider
 * @param advisor the I/O advisor
 * @param publishReport if the report should be published
 * @param cacheCallback call back that is notified on cache changes for the
 *            I/O provider, may be <code>null</code>
 * @return the future yielding the report on success
 */
public static ListenableFuture<IOReport> executeProvider(final IOProvider provider,
        @SuppressWarnings("rawtypes") final IOAdvisor advisor, final boolean publishReport,
        final CacheCallback cacheCallback) {
    final SettableFuture<IOReport> result = SettableFuture.create();
    IRunnableWithProgress op = new IRunnableWithProgress() {

        @SuppressWarnings("unchecked")
        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            if (cacheCallback != null && provider instanceof CachingImportProvider) {
                // enable cache generation
                ((CachingImportProvider) provider).setProvideCache();
            }

            IOReporter reporter = provider.createReporter();
            ATransaction trans = log.begin(reporter.getTaskName());
            try {
                // use advisor to configure provider
                advisor.prepareProvider(provider);
                advisor.updateConfiguration(provider);

                // execute
                IOReport report = provider.execute(new ProgressMonitorIndicator(monitor));

                if (publishReport) {
                    // publish report
                    ReportService rs = PlatformUI.getWorkbench().getService(ReportService.class);
                    rs.addReport(report);
                }

                // handle cache update
                if (cacheCallback != null && provider instanceof CachingImportProvider) {
                    CachingImportProvider cip = (CachingImportProvider) provider;
                    if (cip.isCacheUpdate()) {
                        Value cache = cip.getCache();
                        cacheCallback.update(cache);
                    }
                }

                // handle results
                if (report.isSuccess()) {
                    advisor.handleResults(provider);
                }
                result.set(report);
            } catch (Exception e) {
                log.error("Error executing an I/O provider.", e);
                result.setException(e);
            } finally {
                trans.end();
            }
        }
    };
    try {
        ThreadProgressMonitor.runWithProgressDialog(op, provider.isCancelable());
    } catch (Exception e) {
        log.error("Error executing an I/O provider.", e);
        result.setException(e);
    }
    return result;
}

From source file:org.apache.qpid.server.security.SiteSpecificTrustStoreImpl.java

@StateTransition(currentState = { State.UNINITIALIZED, State.ERRORED }, desiredState = State.ACTIVE)
protected ListenableFuture<Void> doActivate() {
    final SettableFuture<Void> result = SettableFuture.create();
    if (_x509Certificate == null) {
        final String currentCertificate = getCertificate();

        final ListenableFuture<X509Certificate> certFuture = downloadCertificate(getSiteUrl());
        addFutureCallback(certFuture, new FutureCallback<X509Certificate>() {
            @Override//from   w w w  . ja  v  a2  s .c o  m
            public void onSuccess(final X509Certificate cert) {
                _x509Certificate = cert;
                attributeSet(CERTIFICATE, currentCertificate, _x509Certificate);
                generateTrustAndSetState(result);
            }

            @Override
            public void onFailure(final Throwable t) {
                _trustManagers = new TrustManager[0];
                setState(State.ERRORED);
                result.setException(t);

            }
        }, getTaskExecutor());
        return result;
    } else {
        generateTrustAndSetState(result);
    }
    return result;
}

From source file:io.crate.protocols.postgres.BulkPortal.java

private ListenableFuture<Void> executeBulk(Executor executor, Plan plan, final UUID jobId,
        final StatsTables statsTables) {
    final SettableFuture<Void> future = SettableFuture.create();
    Futures.addCallback(executor.executeBulk(plan), new FutureCallback<List<Long>>() {
        @Override//from w w  w. j  av  a2  s .  c om
        public void onSuccess(@Nullable List<Long> result) {
            assert result != null && result.size() == resultReceivers
                    .size() : "number of result must match number of rowReceivers";

            Long[] cells = new Long[1];
            RowN row = new RowN(cells);
            for (int i = 0; i < result.size(); i++) {
                cells[0] = result.get(i);
                ResultReceiver resultReceiver = resultReceivers.get(i);
                resultReceiver.setNextRow(row);
                resultReceiver.allFinished();
            }
            future.set(null);
            statsTables.logExecutionEnd(jobId, null);
        }

        @Override
        public void onFailure(Throwable t) {
            for (ResultReceiver resultReceiver : resultReceivers) {
                resultReceiver.fail(t);
            }
            future.setException(t);
            statsTables.logExecutionEnd(jobId, Exceptions.messageOf(t));

        }
    });
    return future;
}

From source file:io.v.x.jni.test.fortune.FortuneServerImpl.java

@Override
public ListenableFuture<Integer> streamingGet(final VContext context, ServerCall call,
        final ServerStream<String, Boolean> stream) {
    final SettableFuture<Integer> future = SettableFuture.create();
    final AtomicInteger numSent = new AtomicInteger(0);
    Futures.addCallback(InputChannels.withCallback(stream, new InputChannelCallback<Boolean>() {
        @Override/*from w  w  w .  j av a2s  .  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) {
            future.set(numSent.get());
        }

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

From source file:org.voltdb.export.ExportDataSource.java

public ListenableFuture<BBContainer> poll() {
    final SettableFuture<BBContainer> fut = SettableFuture.create();
    m_es.submit(new Runnable() {
        @Override/*  w  ww  . ja v  a 2  s .c  o  m*/
        public void run() {
            /*
             * The poll is blocking through the future, shouldn't
             * call poll a second time until a response has been given
             * which nulls out the field
             */
            if (m_pollFuture != null) {
                fut.setException(new RuntimeException("Should not poll more than once"));
                return;
            }
            pollImpl(fut);
        }
    });
    return fut;
}

From source file:org.opendaylight.netconf.topology.util.BaseTopologyManager.java

@Override
public ListenableFuture<Node> onNodeCreated(final NodeId nodeId, final Node node) {
    LOG.debug("TopologyManager({}) onNodeCreated received, nodeid: {} , isMaster: {}", id, nodeId.getValue(),
            isMaster);/*from   w ww  . java 2s .  co m*/

    if (created.contains(nodeId)) {
        LOG.warn("Node{} already exists, triggering update..", nodeId);
        return onNodeUpdated(nodeId, node);
    }
    created.add(nodeId);
    final ArrayList<ListenableFuture<Node>> futures = new ArrayList<>();

    if (isMaster) {

        futures.add(delegateTopologyHandler.onNodeCreated(nodeId, node));
        // only master should call connect on peers and aggregate futures
        for (TopologyManager topologyManager : peers.values()) {
            // convert binding into NormalizedNode for transfer
            final Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> normalizedNodeEntry = codecRegistry
                    .toNormalizedNode(TopologyUtil.createTopologyNodePath(topologyId), node);

            LOG.debug("YangInstanceIdentifier {}", normalizedNodeEntry.getKey());
            LOG.debug("Value {}", normalizedNodeEntry.getValue());

            // add a future into our futures that gets its completion status from the converted scala future
            final SettableFuture<Node> settableFuture = SettableFuture.create();
            futures.add(settableFuture);
            final Future<NormalizedNodeMessage> scalaFuture = topologyManager.onRemoteNodeCreated(
                    new NormalizedNodeMessage(normalizedNodeEntry.getKey(), normalizedNodeEntry.getValue()));
            scalaFuture.onComplete(new OnComplete<NormalizedNodeMessage>() {
                @Override
                public void onComplete(Throwable failure, NormalizedNodeMessage success) throws Throwable {
                    if (failure != null) {
                        settableFuture.setException(failure);
                        return;
                    }
                    final Entry<InstanceIdentifier<?>, DataObject> fromNormalizedNode = codecRegistry
                            .fromNormalizedNode(success.getIdentifier(), success.getNode());
                    final Node value = (Node) fromNormalizedNode.getValue();

                    settableFuture.set(value);
                }
            }, TypedActor.context().dispatcher());
        }

        final ListenableFuture<Node> aggregatedFuture = aggregator.combineCreateAttempts(futures);
        Futures.addCallback(aggregatedFuture, new FutureCallback<Node>() {
            @Override
            public void onSuccess(final Node result) {
                LOG.debug("Futures aggregated succesfully");
                naSalNodeWriter.init(nodeId, result);
            }

            @Override
            public void onFailure(final Throwable t) {
                // If the combined connection attempt failed, set the node to connection failed
                LOG.debug("Futures aggregation failed");
                naSalNodeWriter.update(nodeId, delegateTopologyHandler.getFailedState(nodeId, node));
            }
        }, TypedActor.context().dispatcher());

        //combine peer futures
        return aggregatedFuture;
    }

    // trigger create on this slave
    return delegateTopologyHandler.onNodeCreated(nodeId, node);
}

From source file:com.google.cloud.pubsub.StreamingSubscriberConnection.java

@Override
void initialize() {
    final SettableFuture<Void> errorFuture = SettableFuture.create();
    final ClientResponseObserver<StreamingPullRequest, StreamingPullResponse> responseObserver = new ClientResponseObserver<StreamingPullRequest, StreamingPullResponse>() {
        @Override//w ww.  j a  v  a 2  s.  com
        public void beforeStart(ClientCallStreamObserver<StreamingPullRequest> requestObserver) {
            StreamingSubscriberConnection.this.requestObserver = requestObserver;
            requestObserver.disableAutoInboundFlowControl();
        }

        @Override
        public void onNext(StreamingPullResponse response) {
            processReceivedMessages(response.getReceivedMessagesList());
            // Only if not shutdown we will request one more batch of messages to be delivered.
            if (isAlive()) {
                requestObserver.request(1);
            }
        }

        @Override
        public void onError(Throwable t) {
            logger.debug("Terminated streaming with exception", t);
            errorFuture.setException(t);
        }

        @Override
        public void onCompleted() {
            logger.debug("Streaming pull terminated successfully!");
            errorFuture.set(null);
        }
    };
    final ClientCallStreamObserver<StreamingPullRequest> requestObserver = (ClientCallStreamObserver<StreamingPullRequest>) (ClientCalls
            .asyncBidiStreamingCall(
                    channel.newCall(SubscriberGrpc.METHOD_STREAMING_PULL,
                            CallOptions.DEFAULT.withCallCredentials(MoreCallCredentials.from(credentials))),
                    responseObserver));
    logger.debug("Initializing stream to subscription {} with deadline {}", subscription,
            getMessageDeadlineSeconds());
    requestObserver.onNext(StreamingPullRequest.newBuilder().setSubscription(subscription)
            .setStreamAckDeadlineSeconds(getMessageDeadlineSeconds()).build());
    requestObserver.request(1);

    Futures.addCallback(errorFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(@Nullable Void result) {
            channelReconnectBackoff = INITIAL_CHANNEL_RECONNECT_BACKOFF;
            // The stream was closed. And any case we want to reopen it to continue receiving
            // messages.
            initialize();
        }

        @Override
        public void onFailure(Throwable t) {
            Status errorStatus = Status.fromThrowable(t);
            if (isRetryable(errorStatus) && isAlive()) {
                long backoffMillis = channelReconnectBackoff.getMillis();
                channelReconnectBackoff = channelReconnectBackoff.plus(backoffMillis);
                executor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        initialize();
                    }
                }, backoffMillis, TimeUnit.MILLISECONDS);
            } else {
                if (isAlive()) {
                    notifyFailed(t);
                }
            }
        }
    }, executor);
}

From source file:com.google.pubsub.flic.controllers.GCEController.java

/**
 * Instantiates the load test on Google Compute Engine.
 *//*  w  w w  .  j av  a2  s.  co m*/
private GCEController(String projectName, Map<String, Map<ClientParams, Integer>> types,
        ScheduledExecutorService executor, Storage storage, Compute compute, Pubsub pubsub) throws Throwable {
    super(executor);
    this.projectName = projectName;
    this.types = types;
    this.storage = storage;
    this.compute = compute;

    // For each unique type of CPS Publisher, create a Topic if it does not already exist, and then
    // delete and recreate any subscriptions attached to it so that we do not have backlog from
    // previous runs.
    List<SettableFuture<Void>> pubsubFutures = new ArrayList<>();
    types.values().forEach(paramsMap -> {
        paramsMap.keySet().stream().map(p -> p.getClientType()).distinct().filter(ClientType::isCpsPublisher)
                .forEach(clientType -> {
                    SettableFuture<Void> pubsubFuture = SettableFuture.create();
                    pubsubFutures.add(pubsubFuture);
                    executor.execute(() -> {
                        String topic = Client.TOPIC_PREFIX + Client.getTopicSuffix(clientType);
                        try {
                            pubsub.projects().topics()
                                    .create("projects/" + projectName + "/topics/" + topic, new Topic())
                                    .execute();
                        } catch (GoogleJsonResponseException e) {
                            if (e.getStatusCode() != ALREADY_EXISTS) {
                                pubsubFuture.setException(e);
                                return;
                            }
                            log.info("Topic already exists, reusing.");
                        } catch (IOException e) {
                            pubsubFuture.setException(e);
                            return;
                        }
                        // Recreate each subscription attached to the topic.
                        paramsMap.keySet().stream()
                                .filter(p -> p.getClientType() == clientType.getSubscriberType())
                                .map(p -> p.subscription).forEach(subscription -> {
                                    try {
                                        pubsub.projects().subscriptions().delete(
                                                "projects/" + projectName + "/subscriptions/" + subscription)
                                                .execute();
                                    } catch (IOException e) {
                                        log.debug(
                                                "Error deleting subscription, assuming it has not yet been created.",
                                                e);
                                    }
                                    try {
                                        pubsub.projects().subscriptions().create(
                                                "projects/" + projectName + "/subscriptions/" + subscription,
                                                new Subscription()
                                                        .setTopic(
                                                                "projects/" + projectName + "/topics/" + topic)
                                                        .setAckDeadlineSeconds(10))
                                                .execute();
                                    } catch (IOException e) {
                                        pubsubFuture.setException(e);
                                    }
                                });
                        pubsubFuture.set(null);
                    });
                });
    });
    try {
        createStorageBucket();
        createFirewall();

        List<SettableFuture<Void>> filesRemaining = new ArrayList<>();
        Files.walk(Paths.get(resourceDirectory)).filter(Files::isRegularFile).forEach(filePath -> {
            SettableFuture<Void> fileRemaining = SettableFuture.create();
            filesRemaining.add(fileRemaining);
            executor.execute(() -> {
                try {
                    uploadFile(filePath);
                    fileRemaining.set(null);
                } catch (Exception e) {
                    fileRemaining.setException(e);
                }
            });
        });
        List<SettableFuture<Void>> createGroupFutures = new ArrayList<>();
        types.forEach((zone, paramsMap) -> paramsMap.forEach((param, n) -> {
            SettableFuture<Void> createGroupFuture = SettableFuture.create();
            createGroupFutures.add(createGroupFuture);
            executor.execute(() -> {
                try {
                    createManagedInstanceGroup(zone, param.getClientType());
                    createGroupFuture.set(null);
                } catch (Exception e) {
                    createGroupFuture.setException(e);
                }
            });
        }));

        // Wait for files and instance groups to be created.
        Futures.allAsList(pubsubFutures).get();
        log.info("Pub/Sub actions completed.");
        Futures.allAsList(filesRemaining).get();
        log.info("File uploads completed.");
        Futures.allAsList(createGroupFutures).get();
        log.info("Instance group creation completed.");

        // Everything is set up, let's start our instances
        log.info("Starting instances.");
        List<SettableFuture<Void>> resizingFutures = new ArrayList<>();
        types.forEach((zone, paramsMap) -> paramsMap.forEach((type, n) -> {
            SettableFuture<Void> resizingFuture = SettableFuture.create();
            resizingFutures.add(resizingFuture);
            executor.execute(() -> {
                try {
                    startInstances(zone, type.getClientType(), n);
                    resizingFuture.set(null);
                } catch (Exception e) {
                    resizingFuture.setException(e);
                }
            });
        }));
        Futures.allAsList(resizingFutures).get();

        // We wait for all instances to finish starting, and get the external network address of each
        // newly created instance.
        List<SettableFuture<Void>> startFutures = new ArrayList<>();
        for (String zone : types.keySet()) {
            Map<ClientParams, Integer> paramsMap = types.get(zone);
            for (ClientParams type : paramsMap.keySet()) {
                SettableFuture<Void> startFuture = SettableFuture.create();
                startFutures.add(startFuture);
                executor.execute(() -> {
                    int numErrors = 0;
                    while (true) {
                        try {
                            addInstanceGroupInfo(zone, type);
                            startFuture.set(null);
                            return;
                        } catch (IOException e) {
                            numErrors++;
                            if (numErrors > 3) {
                                startFuture.setException(new Exception("Failed to get instance information."));
                                return;
                            }
                            log.error("Transient error getting status for instance group, continuing", e);
                        }
                    }
                });
            }
        }

        Futures.allAsList(startFutures).get();
        log.info("Successfully started all instances.");
    } catch (ExecutionException e) {
        shutdown(e.getCause());
        throw e.getCause();
    } catch (Exception e) {
        shutdown(e);
        throw e;
    }
}

From source file:org.opendaylight.controller.cluster.datastore.ThreePhaseCommitCohortProxy.java

private void finishCanCommit(final SettableFuture<Boolean> returnFuture) {
    LOG.debug("Tx {} finishCanCommit", transactionId);

    // For empty transactions return immediately
    if (cohorts.size() == 0) {
        LOG.debug("Tx {}: canCommit returning result true", transactionId);
        returnFuture.set(Boolean.TRUE);
        return;//from w  ww . j a va  2  s. c o m
    }

    commitOperationCallback = new TransactionRateLimitingCallback(actorContext);
    commitOperationCallback.run();

    final Iterator<CohortInfo> iterator = cohorts.iterator();

    final OnComplete<Object> onComplete = new OnComplete<Object>() {
        @Override
        public void onComplete(Throwable failure, Object response) {
            if (failure != null) {
                LOG.debug("Tx {}: a canCommit cohort Future failed", transactionId, failure);

                returnFuture.setException(failure);
                commitOperationCallback.failure();
                return;
            }

            // Only the first call to pause takes effect - subsequent calls before resume are no-ops. So
            // this means we'll only time the first transaction canCommit which should be fine.
            commitOperationCallback.pause();

            boolean result = true;
            if (CanCommitTransactionReply.isSerializedType(response)) {
                CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(response);

                LOG.debug("Tx {}: received {}", transactionId, response);

                if (!reply.getCanCommit()) {
                    result = false;
                }
            } else {
                LOG.error("Unexpected response type {}", response.getClass());
                returnFuture.setException(new IllegalArgumentException(
                        String.format("Unexpected response type %s", response.getClass())));
                return;
            }

            if (iterator.hasNext() && result) {
                sendCanCommitTransaction(iterator.next(), this);
            } else {
                LOG.debug("Tx {}: canCommit returning result: {}", transactionId, result);
                returnFuture.set(Boolean.valueOf(result));
            }

        }
    };

    sendCanCommitTransaction(iterator.next(), onComplete);
}

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

private ListenableFuture<String> createRegistrationId(final Registration registration) {

    String registrationId = null;

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

    try {/*from  w w w .jav a 2 s.co m*/
        registrationId = retrieveRegistrationId(registration.getName());
    } catch (Exception e) {
        resultFuture.setException(e);
        return resultFuture;
    }

    if (isNullOrWhiteSpace(registrationId)) {
        return createRegistrationIdInternal(registration);
    } else {
        ListenableFuture<Void> unregisterInternalFuture = unregisterInternal(registration.getName());

        Futures.addCallback(unregisterInternalFuture, new FutureCallback<Void>() {

            @Override
            public void onFailure(Throwable exception) {
                resultFuture.setException(exception);
            }

            @Override
            public void onSuccess(Void v) {

                ListenableFuture<String> createRegistrationIdInternalFuture = createRegistrationIdInternal(
                        registration);

                Futures.addCallback(createRegistrationIdInternalFuture, new FutureCallback<String>() {

                    @Override
                    public void onFailure(Throwable exception) {
                        resultFuture.setException(exception);
                    }

                    @Override
                    public void onSuccess(String registrationId) {
                        resultFuture.set(registrationId);
                    }
                });
            }
        });
    }

    return resultFuture;
}