Example usage for com.google.common.util.concurrent ListenableFuture get

List of usage examples for com.google.common.util.concurrent ListenableFuture get

Introduction

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

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:org.opendaylight.topomanager.impl.BierTopologyProcess.java

@Override
public ListenableFuture<T> call() throws Exception {
    T object = mtT;//from ww w .  j  a  v a2 s .  c  o  m
    //try
    {
        BierTopologyOperation op = mqueTopoOperation.take();
        final ReadWriteTransaction tx = this.mcDataBroker.newReadWriteTransaction();
        int ops = 0;

        do {
            if (0 == miProcessFlag) {
                ListenableFuture<Optional<T>> readResult = op.readOperation(tx);
                //try
                {
                    object = readResult.get().get();
                }
                /*catch (Exception e) {
                LOG.error("Read Data failed", e);
                }*/
            } else {
                op.writeOperation(tx);

                //try
                {
                    tx.submit().checkedGet();
                }
                /*catch (final TransactionCommitFailedException e) {
                tObject = null;
                LOG.warn("Stat DataStoreOperation unexpected State!", e);
                //m_cTxChain.close();
                //m_cTxChain = m_cDataBroker.createTransactionChain(this);
                }*/
            }

            ops++;
            if (ops < MAX_TRANSACTION_OPERATIONS) {
                op = mqueTopoOperation.poll();
            } else {
                op = null;
            }

        } while (op != null);

    }
    /*catch (final Exception e) {
    LOG.warn("Stat DataStore Operation executor fail!", e);
    }*/

    cleanDataStoreOperQueue();

    return Futures.immediateFuture(object);
}

From source file:org.apache.hive.ptest.execution.Phase.java

protected List<RemoteCommandResult> initalizeHosts() throws Exception {
    List<ListenableFuture<List<RemoteCommandResult>>> futures = Lists.newArrayList();
    ListeningExecutorService executor = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(hostExecutors.size()));
    try {//ww  w .  ja  v  a2s . co  m
        for (final HostExecutor hostExecutor : hostExecutors) {
            futures.add(executor.submit(new Callable<List<RemoteCommandResult>>() {
                @Override
                public List<RemoteCommandResult> call() throws Exception {
                    return initalizeHost(hostExecutor);
                }
            }));
        }
        List<RemoteCommandResult> results = Lists.newArrayList();
        for (ListenableFuture<List<RemoteCommandResult>> future : futures) {
            List<RemoteCommandResult> result = future.get();
            if (result != null) {
                results.addAll(result);
            }
        }
        executor.shutdown();
        return results;
    } finally {
        if (executor.isShutdown()) {
            executor.shutdownNow();
        }
    }
}

From source file:org.excalibur.core.compute.monitoring.monitors.InstanceStateMonitor.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public void monitorUserInstances(String providerName) throws InterruptedException {
    logger.info("Starting the job to get the states of the instances available on provider {}!", providerName);

    final Provider provider = this.providerRepository_.findByExactlyProviderName(providerName);

    List<UserProviderCredentials> users = this.userRepository_
            .listUsersLoginCredentialsOfProvider(provider.getId());

    for (final UserProviderCredentials userCredentials : users) {
        if (MONITORS_TASKS.get(userCredentials.getUserId()) == null) {
            InstanceMonitorTask task = tasks_.get(userCredentials,
                    new Callable<InstanceStateMonitor.InstanceMonitorTask>() {
                        @Override
                        public InstanceMonitorTask call() throws Exception {
                            return new InstanceMonitorTask(userCredentials);
                        }/*from   w  w w  .jav a  2 s  .co  m*/
                    });

            MONITORS_TASKS.putIfAbsent(userCredentials.getId(), task);
        }
    }

    List<ListenableFuture<List<VirtualMachine>[]>> futures = (List) executor.invokeAll(MONITORS_TASKS.values());

    for (ListenableFuture<List<VirtualMachine>[]> future : futures) {
        try {
            List<VirtualMachine>[] lists = future.get();

            if (!lists[0].isEmpty()) {
                this.listenerNotifier
                        .post(new InstancesEvent(this, lists[0], InstanceStateType.CREATED, new Date()));
            }

            if (!lists[1].isEmpty()) {
                this.listenerNotifier
                        .post(new InstancesEvent(this, lists[1], InstanceStateType.UPDATED, new Date()));
            }

        } catch (ExecutionException e) {
            logger.error(e.getMessage());
        }
    }

    logger.info("Finished the job to get the states of the instances available on provider {}!", providerName);
}

From source file:com.google.idea.blaze.android.run.deployinfo.BlazeApkDeployInfoProtoHelper.java

@Nullable
private String getExecutionRoot(BlazeContext context) {
    ListenableFuture<String> execRootFuture = BlazeInfo.getInstance().runBlazeInfo(context,
            Blaze.getBuildSystem(project), workspaceRoot, buildFlags, BlazeInfo.EXECUTION_ROOT_KEY);
    try {//w  ww  .j  ava2 s.co m
        return execRootFuture.get();
    } catch (InterruptedException e) {
        context.setCancelled();
    } catch (ExecutionException e) {
        LOG.error(e);
        context.setHasError();
    }
    return null;
}

From source file:com.github.nethad.clustermeister.provisioning.ec2.commands.StartNodeCommand.java

@Override
public void execute(CommandLineArguments arguments) {
    CommandLineHandle console = getCommandLineHandle();
    AmazonNodeManager nodeManager = getNodeManager();
    CredentialsManager credentialsManager = nodeManager.getCredentialsManager();
    AwsEc2Facade ec2Facade = nodeManager.getEc2Facade();

    if (this.isArgumentsCountFalse(arguments)) {
        return;// w w w. j a va2s .  c om
    }

    Scanner scanner = arguments.asScanner();

    String instanceId = scanner.next();
    String keypairName = scanner.next();
    Credentials credentials = credentialsManager.getCredentials(keypairName);
    if (credentials == null || !(credentials instanceof KeyPairCredentials)) {
        console.print(String.format("No keypair credentials found for credentials '%s'.", credentials));
        return;
    }

    final NodeMetadata instanceMetadata = ec2Facade.getInstanceMetadata(instanceId);

    NodeState state = instanceMetadata.getState();
    if (state == NodeState.RUNNING || state == NodeState.SUSPENDED) {
        final AmazonNodeConfiguration amazonNodeConfiguration = AmazonNodeConfiguration
                .fromInstanceProfile(AWSInstanceProfile.fromInstanceMetadata(instanceMetadata));

        amazonNodeConfiguration.setDriverAddress("localhost");
        amazonNodeConfiguration.setNodeType(NodeType.NODE);
        amazonNodeConfiguration.setCredentials(credentials);

        console.print("Starting node on %s", instanceId);
        ListenableFuture<? extends Node> future = nodeManager.addNode(amazonNodeConfiguration,
                Optional.of(instanceId));
        try {
            Node node = future.get();
            if (node != null) {
                console.print("Node started on %s", instanceId);
            } else {
                console.print("Failed to start node on %s.", instanceId);
            }
        } catch (InterruptedException ex) {
            logger.warn("Interrupted while waiting for node to start.", ex);
        } catch (ExecutionException ex) {
            logger.warn("Could not wait for node to start.", ex);
        }
    } else {
        console.print(String.format("Can not start node on %s because the instance is in state '%s'.",
                instanceId, state));
    }

}

From source file:org.opendaylight.controller.md.sal.dom.broker.impl.CommitCoordinationTask.java

/**
 *
 * Invokes commit on underlying cohorts and blocks till
 * all results are returned./*from   ww  w  .ja  va 2  s. c  o m*/
 *
 * Valid state transition is from PRE_COMMIT to COMMIT, if not throws
 * IllegalStateException.
 *
 * @throws TransactionCommitFailedException
 *             If one of cohorts failed preCommit
 *
 */
private void commitBlocking() throws TransactionCommitFailedException {
    final ListenableFuture<?>[] commitFutures = commitAll();
    try {
        for (final ListenableFuture<?> future : commitFutures) {
            future.get();
        }
    } catch (InterruptedException | ExecutionException e) {
        throw TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER.apply(e);
    }
}

From source file:org.opendaylight.controller.md.sal.dom.broker.impl.CommitCoordinationTask.java

/**
 *
 * Invokes preCommit on underlying cohorts and blocks till
 * all results are returned./*  w  w  w .j  a  v a 2s  .c  o m*/
 *
 * Valid state transition is from CAN_COMMIT to PRE_COMMIT, if current
 * state is not CAN_COMMIT
 * throws IllegalStateException.
 *
 * @throws TransactionCommitFailedException
 *             If one of cohorts failed preCommit
 *
 */
private void preCommitBlocking() throws TransactionCommitFailedException {
    final ListenableFuture<?>[] preCommitFutures = preCommitAll();
    try {
        for (final ListenableFuture<?> future : preCommitFutures) {
            future.get();
        }
    } catch (InterruptedException | ExecutionException e) {
        throw TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER.apply(e);
    }
}

From source file:gobblin.writer.http.AbstractHttpWriter.java

/**
 * Default implementation is to use HttpClients socket timeout which is waiting based on elapsed time between
 * last packet sent from client till receive it from server.
 *
 * {@inheritDoc}/*from w  w w.  j  a v a 2 s .co  m*/
 * @see gobblin.writer.http.HttpWriterDecoration#waitForResponse(com.google.common.util.concurrent.ListenableFuture)
 */
@Override
public CloseableHttpResponse waitForResponse(ListenableFuture<CloseableHttpResponse> responseFuture) {
    try {
        return responseFuture.get();
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.magnet.yak.functional.FunctionalBench.java

public void start() throws Exception {
    if (!started.get()) {
        started.set(true);/*from w w w. j a  v a  2  s.c o  m*/
    }
    ListenableFuture<List<RegisterUserCmdOutput>> registerFuture = ExecUtil.getService()
            .submit(new RegisterUsersTask());
    try {
        List<RegisterUserCmdOutput> registerCmdOutputs = registerFuture.get();

        for (int i = 0; i < registerCmdOutputs.size(); i++) {
            LOGGER.debug("start : User:{} has registered", registerCmdOutputs.get(i).getUsername());
        }

        int numMessages = GlobalConfig.getConfiguration(YakBench.ENV_NAME).getLoad().getMessagesPerUser();

        int size = registerCmdOutputs.size();

        if (size < 2)
            LOGGER.trace("start : not sending messages users should be greater than 2");

        if (size % 2 != 0)
            LOGGER.trace("start : odd users, messages are sent in pairs last user will be idle");

        int newSize = size - 1;

        List<SendMsgCmdInput> msgInputs = new ArrayList<SendMsgCmdInput>();

        for (int i = 0; i < newSize; i = i + 2) {
            RegisterUserCmdOutput from = registerCmdOutputs.get(i);
            RegisterUserCmdOutput to = registerCmdOutputs.get(i + 1);
            SendMsgCmdInput sendMsgInput1 = new SendMsgCmdInput(from.getClient(), to.getClient(), numMessages);
            SendMsgCmdInput sendMsgInput2 = new SendMsgCmdInput(to.getClient(), from.getClient(), numMessages);
            msgInputs.add(sendMsgInput1);
            msgInputs.add(sendMsgInput2);
        }

        ListenableFuture<List<SendMsgCmdOutput>> sendMsgFuture = ExecUtil.getService()
                .submit(new SendMsgTask(msgInputs));

        List<MMXClient> clients = new ArrayList<MMXClient>();

        for (int i = 0; i < registerCmdOutputs.size(); i++) {
            clients.add(registerCmdOutputs.get(i).getClient());
        }

        new TopicSummaryTest().publishItems(clients);

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

From source file:com.google.pubsub.kafka.sink.CloudPubSubSinkTask.java

@Override
public void flush(Map<TopicPartition, OffsetAndMetadata> partitionOffsets) {
    log.debug("Flushing...");
    // Publish all messages that have not been published yet.
    for (Map.Entry<String, Map<Integer, UnpublishedMessagesForPartition>> entry : allUnpublishedMessages
            .entrySet()) {/*from w ww.ja va 2  s . co m*/
        for (Map.Entry<Integer, UnpublishedMessagesForPartition> innerEntry : entry.getValue().entrySet()) {
            publishMessagesForPartition(entry.getKey(), innerEntry.getKey(), innerEntry.getValue().messages);
        }
    }
    allUnpublishedMessages.clear();
    // Process results of all the outstanding futures specified by each TopicPartition.
    for (Map.Entry<TopicPartition, OffsetAndMetadata> partitionOffset : partitionOffsets.entrySet()) {
        log.trace("Received flush for partition " + partitionOffset.getKey().toString());
        Map<Integer, OutstandingFuturesForPartition> outstandingFuturesForTopic = allOutstandingFutures
                .get(partitionOffset.getKey().topic());
        if (outstandingFuturesForTopic == null) {
            continue;
        }
        OutstandingFuturesForPartition outstandingFutures = outstandingFuturesForTopic
                .get(partitionOffset.getKey().partition());
        if (outstandingFutures == null) {
            continue;
        }
        try {
            for (ListenableFuture<PublishResponse> publishFuture : outstandingFutures.futures) {
                publishFuture.get();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    allOutstandingFutures.clear();
}