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.BierTopologyManager.java

public boolean delIpFromNode(String topologyId, final DomainId domainId, final SubDomainId subDomainId,
        final int bitstringlength, final MplsLabel bierMplsLabelBase, final BierNode node, final String type) {
    BierTopologyProcess<BierNode> processor = new BierTopologyProcess<BierNode>(dataBroker,
            BierTopologyProcess.FLAG_WRITE, (new BierNodeBuilder()).build());

    final InstanceIdentifier<BierNode> path = getNodePath(topologyId, node.getNodeId());

    processor.enqueueOperation(new BierTopologyOperation() {
        @Override//from   w w  w  .j av a 2  s  .c o m
        public void writeOperation(ReadWriteTransaction transaction) {
            BierNodeBuilder newNodeBuilder = new BierNodeBuilder(node);
            int domainIndex = getDomainIndex(domainId, node);
            int subDomainIndex = getSubDomainIndex(domainId, subDomainId, node);
            int ipIndex = getIpIndex(domainId, subDomainId, bitstringlength, bierMplsLabelBase, node, type);
            if (type.equals("ipv4")) {
                List<Ipv4> newIpv4List = newNodeBuilder.getBierNodeParams().getDomain().get(domainIndex)
                        .getBierGlobal().getSubDomain().get(subDomainIndex).getAf().getIpv4();
                newIpv4List.remove(ipIndex);
            } else if (type.equals("ipv6")) {
                List<Ipv6> newIpv6List = newNodeBuilder.getBierNodeParams().getDomain().get(domainIndex)
                        .getBierGlobal().getSubDomain().get(subDomainIndex).getAf().getIpv6();
                newIpv6List.remove(ipIndex);
            }

            transaction.put(datastoreType, path, newNodeBuilder.build());
        }

        @SuppressWarnings("unchecked")
        @Override
        public ListenableFuture<Optional<BierNode>> readOperation(ReadWriteTransaction transaction) {
            return null;
        }
    });

    Future<ListenableFuture<BierNode>> future = EXECUTOR.submit(processor);

    try {
        ListenableFuture<BierNode> result = future.get();
        if (null == result.get()) {
            LOG.error("Del bier node ipv4 or ipv6 failed!");
            return false;
        }

        LOG.info("Del bier node ipv4 or ipv6 succeed!");
        return true;
    } catch (InterruptedException e) {
        LOG.error("Del bier node ipv4 or ipv6 is Interrupted by", e);
    } catch (ExecutionException e) {
        LOG.error("Del bier node ipv4 or ipv6 is faild cause by", e);
    }

    LOG.error("Del bier Node ipv4 or ipv6 failed!");
    return false;
}

From source file:org.opennms.newts.gsod.ImportRunner.java

private Observable<Boolean> parMap(Observable<List<Sample>> samples, ExecutorService executorSvc,
        final MetricRegistry metrics, final Func1<List<Sample>, Boolean> insert) {
    final ListeningExecutorService executor = MoreExecutors.listeningDecorator(executorSvc);

    Observable<Boolean> o = samples.lift(new Operator<ListenableFuture<Boolean>, List<Sample>>() {

        @Override//from  w  w w . j a  v a  2  s  .c o m
        public Subscriber<? super List<Sample>> call(final Subscriber<? super ListenableFuture<Boolean>> s) {
            return new Subscriber<List<Sample>>() {

                @Override
                public void onCompleted() {
                    if (!s.isUnsubscribed()) {
                        s.onCompleted();
                    }
                    executor.shutdown();
                }

                @Override
                public void onError(Throwable e) {
                    if (!s.isUnsubscribed()) {
                        s.onError(e);
                    }
                }

                @Override
                public void onNext(final List<Sample> t) {
                    if (!s.isUnsubscribed()) {
                        try {
                            ListenableFuture<Boolean> f = executor.submit(new Callable<Boolean>() {

                                @Override
                                public Boolean call() throws Exception {
                                    return insert.call(t);
                                }

                            });
                            s.onNext(f);
                        } catch (Throwable ex) {
                            onError(ex);
                        }

                    }
                }
            };
        }

    }).observeOn(Schedulers.io()).map(new Func1<ListenableFuture<Boolean>, Boolean>() {

        @Override
        public Boolean call(ListenableFuture<Boolean> f) {
            try {
                return f.get();
            } catch (Throwable e) {
                throw Exceptions.propagate(e);
            }
        }

    });

    return o;
}

From source file:org.apache.hadoop.hbase.replication.regionserver.ReplicationSource.java

public void terminate(String reason, Exception cause, boolean join) {
    if (cause == null) {
        LOG.info("Closing source " + this.peerClusterZnode + " because: " + reason);

    } else {/*from ww  w .j a v a 2s  .c  o  m*/
        LOG.error("Closing source " + this.peerClusterZnode + " because an error occurred: " + reason, cause);
    }
    this.sourceRunning = false;
    Collection<ReplicationSourceWorkerThread> workers = workerThreads.values();
    for (ReplicationSourceWorkerThread worker : workers) {
        worker.setWorkerRunning(false);
        worker.interrupt();
    }
    ListenableFuture<Service.State> future = null;
    if (this.replicationEndpoint != null) {
        future = this.replicationEndpoint.stop();
    }
    if (join) {
        for (ReplicationSourceWorkerThread worker : workers) {
            Threads.shutdown(worker, this.sleepForRetries);
            LOG.info("ReplicationSourceWorker " + worker.getName() + " terminated");
        }
        if (future != null) {
            try {
                future.get();
            } catch (Exception e) {
                LOG.warn("Got exception:" + e);
            }
        }
    }
}

From source file:co.cask.cdap.app.runtime.spark.SparkRuntimeService.java

@Override
protected void run() throws Exception {
    ListenableFuture<RunId> jobCompletion = completion.getAndSet(submitSpark.call());
    // If the jobCompletion is not null, meaning the stop() was called before the atomic reference "completion" has been
    // updated. This mean the job is cancelled. We also need to cancel the future returned by submitSpark.call().
    if (jobCompletion != null) {
        completion.get().cancel(true);/*from  w  w  w . j  a v  a2s  .  c o m*/
    } else {
        // It's possible that the completion reference is changed by the triggerShutdown call between the getAndSet()
        // and the get() call here. But it's ok since the triggeredShutdown will always put a cancelled future in the
        // atomic reference and cancel the actual one.
        jobCompletion = completion.get();
    }

    try {
        // Block for job completion
        jobCompletion.get();
    } catch (Exception e) {
        // See if it is due to job cancelation. If it is, then it's not an error.
        if (jobCompletion.isCancelled()) {
            LOG.info("Spark program execution cancelled: {}", runtimeContext);
        } else {
            throw e;
        }
    }
}

From source file:org.opendaylight.centinel.impl.CentinelStreamImpl.java

@Override
public Future<RpcResult<DeleteStreamOutput>> deleteStream(final DeleteStreamInput input) {

    final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
    final SettableFuture<RpcResult<DeleteStreamOutput>> futureResult = SettableFuture.create();
    boolean idMatches = false;
    if (input.getStreamID() == null || input.getStreamID().isEmpty() || input.getStreamID().trim().isEmpty()) {
        LOG.debug("STREAM ID CANNOT BE NULL");
        return Futures.immediateFailedCheckedFuture(
                new TransactionCommitFailedException("inalid-input", streamIdcannotbenullError()));
    }//  w  ww .j  a va2 s  . co  m
    final DeleteStreamOutputBuilder deleteStreamRuleOutputBuilder = new DeleteStreamOutputBuilder();
    deleteStreamRuleOutputBuilder.setMessage(input.getStreamID());

    ListenableFuture<Optional<StreamRecord>> readFutureOperational = tx.read(LogicalDatastoreType.OPERATIONAL,
            streamRecordId);
    ListenableFuture<Optional<StreamRecord>> readFutureConfigure = tx.read(LogicalDatastoreType.CONFIGURATION,
            streamRecordId);

    String configId = null;

    try {

        Optional<StreamRecord> record = readFutureOperational.get();
        if (record.isPresent()) {
            StreamRecord operationalRecord = readFutureOperational.get().get();
            List<StreamList> streamList = new ArrayList<StreamList>();
            if (!operationalRecord.getStreamList().isEmpty()) {
                streamList = operationalRecord.getStreamList();
                Iterator<StreamList> iterator = streamList.iterator();

                while (iterator.hasNext()) {
                    StreamList operationalObject = iterator.next();
                    if (operationalObject.getStreamID().equals(input.getStreamID())) {
                        configId = operationalObject.getConfigID();
                        idMatches = true;
                    }
                }
                if (!idMatches) {
                    return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException(
                            "invalid-input", RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                                    "Invalid Stream id or The stream is not present in operational data store")));
                }
            }
        } else {
            return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("invalid-input",
                    RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                            "Record is not present in operational data store")));
        }
    }

    catch (Exception ex) {

        deleteStreamRuleOutputBuilder
                .setMessage("Stream with stream id" + input.getStreamID() + "does not exists");
        return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("invalid-input",
                RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                        "Invalid Stream id or The stream is not present in operational data store")));

    }
    final String confID = configId;
    final ListenableFuture<Void> commitFuture = Futures.transform(readFutureConfigure,
            new AsyncFunction<Optional<StreamRecord>, Void>() {

                @Override
                public ListenableFuture<Void> apply(final Optional<StreamRecord> streamRulesRecord)
                        throws Exception {

                    List<StreamList> streamRulesLists = new ArrayList<StreamList>();
                    if (streamRulesRecord.isPresent()) {
                        streamRulesLists = streamRulesRecord.get().getStreamList();
                    }
                    Iterator<StreamList> iterator = streamRulesLists.iterator();

                    while (iterator.hasNext()) {
                        StreamList configObject = iterator.next();
                        if (configObject.getConfigID().equalsIgnoreCase(confID)) {
                            tx.delete(LogicalDatastoreType.CONFIGURATION,
                                    streamRecordId.child(StreamList.class, configObject.getKey()));
                        }

                    }
                    return tx.submit();
                }
            });
    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {

            futureResult.set(RpcResultBuilder.<DeleteStreamOutput>success(deleteStreamRuleOutputBuilder.build())
                    .build());
        }

        @Override
        public void onFailure(final Throwable ex) {

            LOG.debug("Failed to commit Rule", ex);

            futureResult.set(RpcResultBuilder.<DeleteStreamOutput>failed()
                    .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build());
        }
    });
    return futureResult;
}

From source file:org.jclouds.openstack.swift.v1.blobstore.RegionScopedSwiftBlobStore.java

@Beta
@Override// ww w  .j a  v  a2s. co  m
public InputStream streamBlob(final String container, final String name, final ExecutorService executor) {

    final ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(executor);
    // User will receive the Input end of the piped stream
    final PipedOutputStream output;
    final PipedInputStream input;
    try {
        output = new PipedOutputStream();
        input = new PipedInputStream(output,
                getMinimumMultipartPartSize() * 5 > Integer.MAX_VALUE ? Integer.MAX_VALUE
                        : (int) getMinimumMultipartPartSize() * 5);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // The total length of the file to download is needed to determine ranges
    // It has to be obtainable without downloading the whole file
    final long contentLength = api.getObjectApi(regionId, container).getWithoutBody(name).getPayload()
            .getContentMetadata().getContentLength();

    // Determine download buffer size, smaller means less memory usage; larger is faster as long as threads are saturated
    final long partSize = getMinimumMultipartPartSize();

    // Used to communicate between the producer and consumer threads
    final LinkedBlockingQueue<ListenableFuture<byte[]>> results = new LinkedBlockingQueue<ListenableFuture<byte[]>>();

    listeningExecutor.submit(new Runnable() {
        @Override
        public void run() {
            ListenableFuture<byte[]> result;
            long from;
            try {
                for (from = 0; from < contentLength; from = from + partSize) {
                    logger.debug(Thread.currentThread() + " writing to output");
                    result = results.take();
                    if (result == null) {
                        output.close();
                        input.close();
                        throw new RuntimeException("Error downloading file part to stream");
                    }
                    output.write(result.get());
                }
            } catch (Exception e) {
                logger.debug(e.toString());
                // Close pipe so client is notified of an exception
                Closeables2.closeQuietly(input);
                throw new RuntimeException(e);
            } finally {
                // Finished writing results to stream
                Closeables2.closeQuietly(output);
            }
        }
    });

    listeningExecutor.submit(new Runnable() {
        @Override
        public void run() {
            long from;
            long to;
            // Loop through ranges within the file
            for (from = 0; from < contentLength; from = from + partSize) {
                to = (from + partSize >= contentLength) ? contentLength - 1 : from + partSize - 1;
                BlobStreamDownloader b = new BlobStreamDownloader(container, name, from, to);
                results.add(listeningExecutor.submit(b));
            }
        }
    });
    return input;
}

From source file:org.opendaylight.centinel.impl.CentinelStreamImpl.java

@Override
public Future<RpcResult<UpdateStreamOutput>> updateStream(final UpdateStreamInput input) {
    final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
    final SettableFuture<RpcResult<UpdateStreamOutput>> futureResult = SettableFuture.create();
    boolean idMatches = false;
    if (input.getStreamID() == null || input.getStreamID().isEmpty() || input.getStreamID().trim().isEmpty()) {
        LOG.debug("STREAM ID CANNOT BE NULL");
        return Futures.immediateFailedCheckedFuture(
                new TransactionCommitFailedException("inalid-input", streamIdcannotbenullError()));
    }//from ww w  . ja  va  2 s.c o m
    final UpdateStreamOutputBuilder updateStreamRuleOutputBuilder = new UpdateStreamOutputBuilder();
    updateStreamRuleOutputBuilder.setTitle(input.getTitle());
    updateStreamRuleOutputBuilder.setDescription(input.getDescription());
    ListenableFuture<Optional<StreamRecord>> readFutureOperational = tx.read(LogicalDatastoreType.OPERATIONAL,
            streamRecordId);

    ListenableFuture<Optional<StreamRecord>> readFutureConfigure = tx.read(LogicalDatastoreType.CONFIGURATION,
            streamRecordId);

    String configId = null;

    try {
        Optional<StreamRecord> record = readFutureOperational.get();
        if (record.isPresent()) {
            StreamRecord operationalRecord = readFutureOperational.get().get();
            List<StreamList> streamRulesList = new ArrayList<StreamList>();
            if (!operationalRecord.getStreamList().isEmpty()) {
                streamRulesList = operationalRecord.getStreamList();
                Iterator<StreamList> iterator = streamRulesList.iterator();
                while (iterator.hasNext()) {
                    StreamList operationalObject = iterator.next();
                    if (operationalObject.getStreamID().equals(input.getStreamID())) {
                        configId = operationalObject.getConfigID();
                        idMatches = true;
                    }
                }
                if (!idMatches) {

                    return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException(
                            "invalid-input", RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                                    "Invalid Stream id or The stream is not present in operational data store")));
                }
            }
        } else {
            return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("invalid-input",
                    RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                            "Record is not present in operational data store")));
        }
    } catch (InterruptedException | ExecutionException e) {

        futureResult.set(RpcResultBuilder.<UpdateStreamOutput>failed()
                .withRpcErrors(((TransactionCommitFailedException) e).getErrorList()).build());
        return futureResult;
    }
    final String confId = configId;

    final ListenableFuture<Void> commitFuture = Futures.transform(readFutureConfigure,
            new AsyncFunction<Optional<StreamRecord>, Void>() {

                @Override
                public ListenableFuture<Void> apply(final Optional<StreamRecord> streamRulesRecord)
                        throws Exception {

                    List<StreamList> streamRuleList = new ArrayList<StreamList>();
                    List<StreamList> updatedStreamRuleList = new ArrayList<StreamList>();

                    if (streamRulesRecord.isPresent()) {

                        streamRuleList = streamRulesRecord.get().getStreamList();
                        StreamList configObject = null;
                        Iterator<StreamList> iterator = streamRuleList.iterator();

                        while (iterator.hasNext()) {

                            configObject = iterator.next();

                            if (configObject.getConfigID().equalsIgnoreCase(confId)) {

                                updatedStreamRuleList.add(buildUpdateStreamListRecord(input, configObject));

                                tx.merge(LogicalDatastoreType.CONFIGURATION, streamRecordId,
                                        new StreamRecordBuilder().setStreamList(updatedStreamRuleList).build());
                            }
                        }
                    }
                    return tx.submit();
                }

            });
    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {

            futureResult.set(RpcResultBuilder.<UpdateStreamOutput>success(updateStreamRuleOutputBuilder.build())
                    .build());
        }

        @Override
        public void onFailure(final Throwable ex) {

            LOG.debug("Failed to commit Rule", ex);

            futureResult.set(RpcResultBuilder.<UpdateStreamOutput>failed()
                    .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build());
        }
    });
    return futureResult;
}

From source file:org.apache.druid.segment.realtime.appenderator.AppenderatorImpl.java

@Override
public void clear() throws InterruptedException {
    // Drop commit metadata, then abandon all segments.

    try {//from   w  w w.j  a v a  2s  .  c  om
        throwPersistErrorIfExists();

        if (persistExecutor != null) {
            final ListenableFuture<?> uncommitFuture = persistExecutor.submit(() -> {
                try {
                    commitLock.lock();
                    objectMapper.writeValue(computeCommitFile(), Committed.nil());
                } finally {
                    commitLock.unlock();
                }
                return null;
            });

            // Await uncommit.
            uncommitFuture.get();

            // Drop everything.
            final List<ListenableFuture<?>> futures = Lists.newArrayList();
            for (Map.Entry<SegmentIdentifier, Sink> entry : sinks.entrySet()) {
                futures.add(abandonSegment(entry.getKey(), entry.getValue(), true));
            }

            // Await dropping.
            Futures.allAsList(futures).get();
        }
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.opendaylight.alto.altohosttracker.plugin.internal.AltoHostTrackerImpl.java

public void registerAsDataChangeListener() {
    ResourceId ridForDelete = new ResourceId(NMRESOURCEID);
    InstanceIdentifier<NetworkMap> networkMapForDelete = InstanceIdentifier.builder(Resources.class)
            .child(NetworkMaps.class).child(NetworkMap.class, new NetworkMapKey(ridForDelete)).build();

    InstanceIdentifier<HostNode> hostNodes = InstanceIdentifier.builder(NetworkTopology.class)//
            .child(Topology.class, new TopologyKey(new TopologyId(topologyId)))//
            .child(Node.class).augmentation(HostNode.class).build();

    InstanceIdentifier<Addresses> addrCapableNodeConnectors = //
            InstanceIdentifier.builder(Nodes.class)
                    //
                    .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class) //
                    .child(NodeConnector.class) //
                    .augmentation(AddressCapableNodeConnector.class)//
                    .child(Addresses.class).build();

    // ReadOnlyTransaction newReadOnlyTransaction =
    // dataService.newReadOnlyTransaction();
    InstanceIdentifier<Nodes> iins = addrCapableNodeConnectors.firstIdentifierOf(Nodes.class);
    // InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node>
    // iin////from ww w.  j a  v  a  2s  . com
    // =
    // addrCapableNodeConnectors.firstIdentifierOf(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class);
    // ListenableFuture<Optional<NodeConnector>> dataFuture =
    // newReadOnlyTransaction.read(LogicalDatastoreType.OPERATIONAL, iinc);
    ListenableFuture<Optional<Nodes>> futureNodes;
    /*
     * try { NodeConnector get = dataFuture.get().get();
     * log.info("test "+get); } catch (InterruptedException |
     * ExecutionException ex) {
     * //java.util.logging.Logger.getLogger(HostTracker2Impl
     * .class.getName()).log(Level.SEVERE, null, ex);
     * log.info("exception on get"); }
     */
    try (ReadOnlyTransaction readTx = dataService.newReadOnlyTransaction()) {
        futureNodes = readTx.read(LogicalDatastoreType.OPERATIONAL, iins);
        // futureNode = readTx.read(LogicalDatastoreType.OPERATIONAL, iin);
        readTx.close();
    }
    Optional<Nodes> opNodes = null;
    try {
        opNodes = futureNodes.get();
    } catch (ExecutionException | InterruptedException ex) {
        log.warn(ex.getLocalizedMessage());
    }

    List<Addresses> addrsList = new ArrayList<Addresses>();
    if (opNodes != null && opNodes.isPresent()) {
        // log.info("node connector:"+opNodes.get());
        Nodes ns = opNodes.get();
        for (org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node n : ns.getNode()) {
            for (NodeConnector nc : n.getNodeConnector()) {
                AddressCapableNodeConnector acnc = nc.getAugmentation(AddressCapableNodeConnector.class);
                if (acnc != null) {
                    for (Addresses addrs : acnc.getAddresses()) {
                        log.info("existing address: " + addrs);
                        addrsList.add(addrs);
                        mergeEndpointPropertyMapForAddresses(addrs);
                    }
                }
            }
        }
    }
    mergeNetworkMapForAddressesList(addrsList, NMRESOURCEID, "pid1", "ipv4");
    /*
     * Futures.addCallback(dataFuture, new
     * FutureCallback<Optional<NodeConnector>>() {
     * @Override public void onSuccess(final Optional<NodeConnector> result)
     * { if (result.isPresent()) { log.info("Processing NEW NODE? " +
     * result.get().getId().getValue()); // processHost(result, dataObject,
     * node); } }
     * @Override public void onFailure(Throwable arg0) { } });
     */

    this.hostNodeListerRegistration = dataService.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL,
            hostNodes, this, DataChangeScope.SUBTREE);

    this.networkMapListerRegistration = dataService.registerDataChangeListener(
            LogicalDatastoreType.CONFIGURATION, networkMapForDelete, this, DataChangeScope.BASE);

    // log.info("register data change");
}

From source file:diskCacheV111.srm.SrmHandler.java

private Object dispatch(Object request, Function<Object, SrmRequest> toMessage)
        throws InterruptedException, ExecutionException, SRMInternalErrorException {
    try (MappedRequest mapped = mapRequest(request)) {
        ListenableFuture<SrmResponse> future = (mapped == null)
                ? srmManagerStub.send(toMessage.apply(request), SrmResponse.class)
                : srmManagerStub.send(mapped.getBackend(), toMessage.apply(mapped.getRequest()),
                        SrmResponse.class);
        return mapResponse(future.get());
    }//from w  w  w . j a v  a 2  s.com
}