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:io.ucoin.ucoinj.elasticsearch.service.ExecutorServiceImpl.java

@Override
public ProgressionModel getProgressionByJobId(String jobId) {
    if (StringUtils.isBlank(jobId)) {
        return null;
    }/*w  w  w  .  j  a  v a2  s  . c o  m*/
    synchronized (jobsById) {
        ListenableFuture<Job> job = jobsById.get(jobId);
        if (job != null) {
            try {
                return job.get().getProgressionModel();
            } catch (InterruptedException | ExecutionException e) {
                // continue
            }
        }
    }

    // Call the cache, but return null if the key is not present
    return progressionByJobIdCache.getIfPresent(jobId);
}

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

/**
 *
 * Invokes canCommit on underlying cohorts and blocks till
 * all results are returned./*  w  w  w .  j  a v  a2 s. c o m*/
 *
 * Valid state transition is from SUBMITTED to CAN_COMMIT,
 * if currentPhase is not SUBMITTED throws IllegalStateException.
 *
 * @throws TransactionCommitFailedException
 *             If one of cohorts failed can Commit
 *
 */
private void canCommitBlocking() throws TransactionCommitFailedException {
    for (final ListenableFuture<?> canCommit : canCommitAll()) {
        try {
            final Boolean result = (Boolean) canCommit.get();
            if (result == null || !result) {
                throw new TransactionCommitFailedException("Can Commit failed, no detailed cause available.");
            }
        } catch (InterruptedException | ExecutionException e) {
            throw TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER.apply(e);
        }
    }
}

From source file:com.facebook.presto.chicago.ChicagoRecordCursor.java

/**
 * Now this is where I need the API. I need to get the keys for that particular colFam
 * I got the API ready./*from  w ww .j  a  v  a  2  s .c  o  m*/
 * I need to use the ZKClient from the ChicagoClient to get the data
 * But probably need to check with JEff about exposing the ZKClient from chicagoclient.
 * @return
 */
private boolean fetchKeys() {
    try {
        switch (split.getKeyDataType()) {
        case STRING: {
            ListenableFuture<byte[]> f = cc.scanKeys(this.split.getTableName().getBytes());
            byte[] b = f.get();
            String resp = new String(b);
            List<String> keys = Arrays.asList(resp.split("\0")[0].split("@@@"));
            keysIterator = keys.iterator();
        }
            break;
        default:
            log.debug("Chicago type of key %s is unsupported", split.getKeyDataFormat());
            return false;
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
    return true;
}

From source file:org.opendaylight.netvirt.vpnmanager.InterfaceStateChangeListener.java

@Override
// TODO Clean up the exception handling
@SuppressWarnings("checkstyle:IllegalCatch")
protected void remove(InstanceIdentifier<Interface> identifier, Interface intrf) {
    final String interfaceName = intrf.getName();
    LOG.info("Detected interface remove event for interface {}", interfaceName);
    try {//  w w  w.  ja va  2 s.com
        if (intrf != null && (intrf.getType() != null) && !intrf.getType().equals(Tunnel.class)) {
            DataStoreJobCoordinator dataStoreCoordinator = DataStoreJobCoordinator.getInstance();
            dataStoreCoordinator.enqueueJob("VPNINTERFACE-" + interfaceName, () -> {
                WriteTransaction writeOperTxn = dataBroker.newWriteOnlyTransaction();
                WriteTransaction writeConfigTxn = dataBroker.newWriteOnlyTransaction();
                WriteTransaction writeInvTxn = dataBroker.newWriteOnlyTransaction();
                List<ListenableFuture<Void>> futures = new ArrayList<>();

                BigInteger dpId;
                InstanceIdentifier<VpnInterface> id = VpnUtil.getVpnInterfaceIdentifier(interfaceName);
                Optional<VpnInterface> optVpnInterface = VpnUtil.read(dataBroker,
                        LogicalDatastoreType.OPERATIONAL, id);
                if (optVpnInterface.isPresent()) {
                    final VpnInterface vpnInterface = optVpnInterface.get();
                    try {
                        dpId = InterfaceUtils.getDpIdFromInterface(intrf);
                    } catch (Exception e) {
                        LOG.error("Unable to retrieve dpnId from interface operational data store for interface"
                                + " {}. Fetching from vpn interface op data store. ", interfaceName, e);
                        dpId = vpnInterface.getDpnId();
                    }
                    final BigInteger dpnId = dpId;
                    final int ifIndex = intrf.getIfIndex();
                    vpnInterfaceManager.processVpnInterfaceDown(dpnId, interfaceName, ifIndex, false, false,
                            writeConfigTxn, writeOperTxn, writeInvTxn, intrf);
                    ListenableFuture<Void> operFuture = writeOperTxn.submit();
                    try {
                        operFuture.get();
                    } catch (ExecutionException e) {
                        LOG.error("InterfaceStateChange - Exception encountered while submitting operational"
                                + " future for removeVpnInterface {} : {}", vpnInterface.getName(), e);
                        return null;
                    }
                    futures.add(writeConfigTxn.submit());
                    futures.add(writeInvTxn.submit());
                } else {
                    LOG.debug("Interface {} is not a vpninterface, ignoring.", interfaceName);
                }

                return futures;
            });
        }
    } catch (Exception e) {
        LOG.error("Exception observed in handling deletion of VPN Interface {}. ", interfaceName, e);
    }
}

From source file:io.bitsquare.trade.protocol.trade.tasks.shared.SetupPayoutTxLockTimeReachedListener.java

@Override
protected void run() {
    try {/* ww w  . j  a  va2 s  .co  m*/
        runInterceptHook();
        log.debug("ChainHeight/LockTime: {} / {}", processModel.getTradeWalletService().getBestChainHeight(),
                trade.getLockTime());
        if (processModel.getTradeWalletService().getBestChainHeight() >= trade.getLockTime()) {
            broadcastTx();
        } else {
            ListenableFuture<StoredBlock> blockHeightFuture = processModel.getTradeWalletService()
                    .getBlockHeightFuture(trade.getPayoutTx());
            blockHeightFuture.addListener(() -> {
                try {
                    log.debug("Block height reached " + blockHeightFuture.get().getHeight());
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
                broadcastTx();
            }, Threading.USER_THREAD::execute);
        }
    } catch (Throwable t) {
        failed(t);
    }
}

From source file:org.openqa.selenium.safari.SafariDriverCommandExecutor.java

@Override
public synchronized Response execute(Command command) {
    if (!server.isRunning() && DriverCommand.QUIT.equals(command.getName())) {
        Response itsOkToQuitMultipleTimes = new Response();
        itsOkToQuitMultipleTimes.setStatus(ErrorCodes.SUCCESS);
        return itsOkToQuitMultipleTimes;
    }//from w  w w  . j  a  v  a2s  . c om

    checkState(connection != null, "Executor has not been started yet");

    // On quit(), the SafariDriver's browser extension simply returns a stub success
    // response, so we can short-circuit the process and just return that here.
    // The SafarIDriver's browser extension doesn't do anything on qu
    // There's no need to wait for a response when quitting.
    if (DriverCommand.QUIT.equals(command.getName())) {
        Response response = new Response(command.getSessionId());
        response.setStatus(ErrorCodes.SUCCESS);
        response.setState(ErrorCodes.SUCCESS_STRING);
        return response;
    }

    try {
        SafariCommand safariCommand = new SafariCommand(command);
        String rawJsonCommand = new BeanToJsonConverter().convert(serialize(safariCommand));
        ListenableFuture<String> futureResponse = connection.send(rawJsonCommand);

        JsonObject jsonResponse = new JsonParser().parse(futureResponse.get()).getAsJsonObject();
        Response response = new JsonToBeanConverter().convert(Response.class, jsonResponse.get("response"));
        if (response.getStatus() == ErrorCodes.SUCCESS) {
            checkArgument(safariCommand.getId().equals(jsonResponse.get("id").getAsString()),
                    "Response ID<%s> does not match command ID<%s>", jsonResponse.get("id").getAsString(),
                    safariCommand.getId());
        }

        return response;
    } catch (JsonSyntaxException e) {
        throw new JsonException(e);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new WebDriverException(e);
    } catch (ExecutionException e) {
        throw Throwables.propagate(e.getCause());
    }
}

From source file:org.opendaylight.netvirt.vpnmanager.InterfaceStateChangeListener.java

@SuppressWarnings("checkstyle:IllegalCatch")
@Override//from   ww w . j a  va2  s.co  m
protected void update(InstanceIdentifier<Interface> identifier, Interface original, Interface update) {
    final String interfaceName = update.getName();
    LOG.info("Detected interface update event for interface {}", interfaceName);
    LOG.trace("Detected interface update event for interface {} - Old: {}, New: {}", interfaceName, original,
            update);
    try {
        OperStatus originalOperStatus = original.getOperStatus();
        OperStatus updateOperStatus = update.getOperStatus();
        if (originalOperStatus.equals(Interface.OperStatus.Unknown)
                || updateOperStatus.equals(Interface.OperStatus.Unknown)) {
            LOG.debug("Interface {} state change is from/to null/UNKNOWN. Ignoring the update event.",
                    interfaceName);
            return;
        }

        if (update.getIfIndex() == null) {
            return;
        }
        if (update != null && (update.getType() != null) && !update.getType().equals(Tunnel.class)) {
            DataStoreJobCoordinator dataStoreCoordinator = DataStoreJobCoordinator.getInstance();
            dataStoreCoordinator.enqueueJob("VPNINTERFACE-" + interfaceName, () -> {
                WriteTransaction writeConfigTxn = dataBroker.newWriteOnlyTransaction();
                WriteTransaction writeOperTxn = dataBroker.newWriteOnlyTransaction();
                WriteTransaction writeInvTxn = dataBroker.newWriteOnlyTransaction();
                List<ListenableFuture<Void>> futures = new ArrayList<>();

                final VpnInterface vpnInterface = VpnUtil.getConfiguredVpnInterface(dataBroker, interfaceName);
                if (vpnInterface != null) {
                    final int ifIndex = update.getIfIndex();
                    final BigInteger dpnId = InterfaceUtils.getDpIdFromInterface(update);
                    if (update.getOperStatus().equals(Interface.OperStatus.Up)) {
                        vpnInterfaceManager.processVpnInterfaceUp(dpnId, vpnInterface, ifIndex, true,
                                writeConfigTxn, writeOperTxn, writeInvTxn, update);
                    } else if (update.getOperStatus().equals(Interface.OperStatus.Down)) {
                        vpnInterfaceManager.processVpnInterfaceDown(dpnId, interfaceName, ifIndex, true, false,
                                writeConfigTxn, writeOperTxn, writeInvTxn, update);
                    }
                    ListenableFuture<Void> operFuture = writeOperTxn.submit();
                    try {
                        operFuture.get();
                    } catch (ExecutionException e) {
                        LOG.error("InterfaceStateChange - Exception encountered while submitting operational"
                                + " future for updateVpnInterface {} : {}", vpnInterface.getName(), e);
                        return null;
                    }
                    futures.add(writeConfigTxn.submit());
                    futures.add(writeInvTxn.submit());
                } else {
                    LOG.debug("Interface {} is not a vpninterface, ignoring.", interfaceName);
                }

                return futures;
            });
        }
    } catch (Exception e) {
        LOG.error("Exception observed in handling updation of VPN Interface {}. ", update.getName(), e);
    }
}

From source file:org.thingsboard.server.service.script.RemoteJsInvokeService.java

@Override
protected void doRelease(UUID scriptId, String functionName) throws Exception {
    JsInvokeProtos.JsReleaseRequest jsRequest = JsInvokeProtos.JsReleaseRequest.newBuilder()
            .setScriptIdMSB(scriptId.getMostSignificantBits())
            .setScriptIdLSB(scriptId.getLeastSignificantBits()).setFunctionName(functionName).build();

    JsInvokeProtos.RemoteJsRequest jsRequestWrapper = JsInvokeProtos.RemoteJsRequest.newBuilder()
            .setReleaseRequest(jsRequest).build();

    ListenableFuture<JsInvokeProtos.RemoteJsResponse> future = kafkaTemplate.post(scriptId.toString(),
            jsRequestWrapper);/*from  w w  w.ja v  a 2  s . c o m*/
    JsInvokeProtos.RemoteJsResponse response = future.get();

    JsInvokeProtos.JsReleaseResponse compilationResult = response.getReleaseResponse();
    UUID compiledScriptId = new UUID(compilationResult.getScriptIdMSB(), compilationResult.getScriptIdLSB());
    if (compilationResult.getSuccess()) {
        scriptIdToBodysMap.remove(scriptId);
    } else {
        log.debug("[{}] Failed to release script due", compiledScriptId);
    }
}

From source file:monasca.persister.repository.cassandra.CassandraRepo.java

public int handleFlush(String id) throws RepoException {
    long startTime = System.nanoTime();

    int flushedCount = 0;
    List<ResultSetFuture> results = new ArrayList<>(queue.size());
    Statement query;/*from   w w w.  j a  v a 2s  . c o m*/
    while ((query = queue.poll()) != null) {
        flushedCount++;
        results.add(session.executeAsync(query));
    }

    List<ListenableFuture<ResultSet>> futures = Futures.inCompletionOrder(results);

    boolean cancel = false;
    Exception ex = null;
    for (ListenableFuture<ResultSet> future : futures) {
        if (cancel) {
            future.cancel(false);
            continue;
        }
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            cancel = true;
            ex = e;
        }
    }

    commitTimer.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);

    if (ex != null) {
        throw new RepoException(ex);
    }
    return flushedCount;
}

From source file:io.bitsquare.trade.protocol.trade.tasks.shared.BroadcastAfterLockTime.java

@Override
protected void run() {
    try {//from ww  w  . j a va 2  s. c o  m
        runInterceptHook();
        log.debug("ChainHeight/LockTime: {} / {}", processModel.getTradeWalletService().getBestChainHeight(),
                trade.getLockTimeAsBlockHeight());
        if (trade.getLockTimeAsBlockHeight() == 0 || processModel.getTradeWalletService()
                .getBestChainHeight() >= trade.getLockTimeAsBlockHeight()) {
            broadcastTx();
        } else {
            ListenableFuture<StoredBlock> blockHeightFuture = processModel.getTradeWalletService()
                    .getBlockHeightFuture(trade.getPayoutTx());
            blockHeightFuture.addListener(() -> {
                try {
                    log.debug("Block height reached " + blockHeightFuture.get().getHeight());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                broadcastTx();
            }, UserThread::execute);
        }
    } catch (Throwable t) {
        failed(t);
    }
}