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.voltdb.SimpleFileSnapshotDataTarget.java

@Override
public ListenableFuture<?> write(final Callable<BBContainer> tupleData, SnapshotTableTask context) {
    final ListenableFuture<BBContainer> computedData = VoltDB.instance().getComputationService()
            .submit(tupleData);/*from w w w.  ja  va2 s .c o  m*/

    return m_es.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            try {
                final BBContainer data = computedData.get();
                /*
                 * If a filter nulled out the buffer do nothing.
                 */
                if (data == null)
                    return null;
                if (m_writeFailed) {
                    data.discard();
                    return null;
                }
                try {
                    while (data.b.hasRemaining()) {
                        int written = m_fc.write(data.b);
                        if (written > 0) {
                            m_bytesWritten += written;
                        }
                    }
                } finally {
                    data.discard();
                }
            } catch (Throwable t) {
                m_writeException = t;
                m_writeFailed = true;
                throw Throwables.propagate(t);
            }
            return null;
        }
    });
}

From source file:org.thingsboard.server.controller.DeviceController.java

@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/device/types", method = RequestMethod.GET)
@ResponseBody/*ww w  . j a  v  a  2  s  . co  m*/
public List<EntitySubtype> getDeviceTypes() throws ThingsboardException {
    try {
        SecurityUser user = getCurrentUser();
        TenantId tenantId = user.getTenantId();
        ListenableFuture<List<EntitySubtype>> deviceTypes = deviceService.findDeviceTypesByTenantId(tenantId);
        return checkNotNull(deviceTypes.get());
    } catch (Exception e) {
        throw handleException(e);
    }
}

From source file:org.thingsboard.server.controller.EntityViewController.java

@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/entityView/types", method = RequestMethod.GET)
@ResponseBody/*from   www.j ava2  s  . c om*/
public List<EntitySubtype> getEntityViewTypes() throws ThingsboardException {
    try {
        SecurityUser user = getCurrentUser();
        TenantId tenantId = user.getTenantId();
        ListenableFuture<List<EntitySubtype>> entityViewTypes = entityViewService
                .findEntityViewTypesByTenantId(tenantId);
        return checkNotNull(entityViewTypes.get());
    } catch (Exception e) {
        throw handleException(e);
    }
}

From source file:org.apache.drill.exec.store.hive.HiveAbstractReader.java

@Override
public void setup(OperatorContext context, OutputMutator output) throws ExecutionSetupException {
    // initializes "reader"
    final Callable<Void> readerInitializer = new Callable<Void>() {
        @Override/*from   ww  w. ja v  a2 s. c  o  m*/
        public Void call() throws Exception {
            init();
            return null;
        }
    };

    final ListenableFuture<Void> result = context.runCallableAs(proxyUgi, readerInitializer);
    try {
        result.get();
    } catch (InterruptedException e) {
        result.cancel(true);
        // Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the
        // interruption and respond to it if it wants to.
        Thread.currentThread().interrupt();
    } catch (ExecutionException e) {
        throw ExecutionSetupException.fromThrowable(e.getMessage(), e);
    }
    try {
        final OptionManager options = fragmentContext.getOptions();
        for (int i = 0; i < selectedColumnNames.size(); i++) {
            MajorType type = HiveUtilities.getMajorTypeFromHiveTypeInfo(selectedColumnTypes.get(i), options);
            MaterializedField field = MaterializedField.create(selectedColumnNames.get(i), type);
            Class<? extends ValueVector> vvClass = TypeHelper.getValueVectorClass(type.getMinorType(),
                    type.getMode());
            vectors.add(output.addField(field, vvClass));
        }

        for (int i = 0; i < selectedPartitionNames.size(); i++) {
            MajorType type = HiveUtilities.getMajorTypeFromHiveTypeInfo(selectedPartitionTypes.get(i), options);
            MaterializedField field = MaterializedField.create(selectedPartitionNames.get(i), type);
            Class<? extends ValueVector> vvClass = TypeHelper
                    .getValueVectorClass(field.getType().getMinorType(), field.getDataMode());
            pVectors.add(output.addField(field, vvClass));
        }
    } catch (SchemaChangeException e) {
        throw new ExecutionSetupException(e);
    }
}

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

private SegmentsAndMetadata pushAndClear(Collection<String> sequenceNames, long pushAndClearTimeoutMs)
        throws InterruptedException, ExecutionException, TimeoutException {
    final Map<SegmentIdentifier, SegmentWithState> requestedSegmentIdsForSequences = getAppendingSegments(
            sequenceNames)//from w  ww . ja  v a 2s.c o  m
                    .collect(Collectors.toMap(SegmentWithState::getSegmentIdentifier, Function.identity()));

    final ListenableFuture<SegmentsAndMetadata> future = ListenableFutures.transformAsync(
            pushInBackground(null, requestedSegmentIdsForSequences.keySet(), false), this::dropInBackground);

    final SegmentsAndMetadata segmentsAndMetadata = pushAndClearTimeoutMs == 0L ? future.get()
            : future.get(pushAndClearTimeoutMs, TimeUnit.MILLISECONDS);

    // Sanity check
    final Map<SegmentIdentifier, DataSegment> pushedSegmentIdToSegmentMap = segmentsAndMetadata.getSegments()
            .stream().collect(Collectors.toMap(SegmentIdentifier::fromDataSegment, Function.identity()));

    if (!pushedSegmentIdToSegmentMap.keySet().equals(requestedSegmentIdsForSequences.keySet())) {
        throw new ISE("Pushed segments[%s] are different from the requested ones[%s]",
                pushedSegmentIdToSegmentMap.keySet(), requestedSegmentIdsForSequences.keySet());
    }

    synchronized (segments) {
        for (String sequenceName : sequenceNames) {
            final SegmentsForSequence segmentsForSequence = segments.get(sequenceName);
            if (segmentsForSequence == null) {
                throw new ISE("Can't find segmentsForSequence for sequence[%s]", sequenceName);
            }

            segmentsForSequence.getAllSegmentsOfInterval().forEach(segmentsOfInterval -> {
                final SegmentWithState appendingSegment = segmentsOfInterval.getAppendingSegment();
                if (appendingSegment != null) {
                    final DataSegment pushedSegment = pushedSegmentIdToSegmentMap
                            .get(appendingSegment.getSegmentIdentifier());
                    if (pushedSegment == null) {
                        throw new ISE("Can't find pushedSegments for segment[%s]",
                                appendingSegment.getSegmentIdentifier());
                    }

                    segmentsOfInterval.finishAppendingToCurrentActiveSegment(
                            segmentWithState -> segmentWithState.pushAndDrop(pushedSegment));
                }
            });
        }
    }

    return segmentsAndMetadata;
}

From source file:com.ligerzero459.paycoin.tools.WalletTool.java

private static void sendPaymentRequest(String location, boolean verifyPki) {
    if (location.startsWith("http") || location.startsWith("peercoin")) {
        try {// w w  w.  j  a  v a  2s  .  c  om
            ListenableFuture<PaymentSession> future;
            if (location.startsWith("http")) {
                future = PaymentSession.createFromUrl(location, verifyPki);
            } else {
                PeercoinURI paymentRequestURI = new PeercoinURI(location);
                future = PaymentSession.createFromPeercoinUri(paymentRequestURI, verifyPki);
            }
            PaymentSession session = future.get();
            if (session != null) {
                send(session);
            } else {
                System.err.println("Server returned null session");
                System.exit(1);
            }
        } catch (PaymentProtocolException e) {
            System.err.println("Error creating payment session " + e.getMessage());
            System.exit(1);
        } catch (PeercoinURIParseException e) {
            System.err.println("Invalid peercoin uri: " + e.getMessage());
            System.exit(1);
        } catch (InterruptedException e) {
            // Ignore.
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    } else {
        // Try to open the payment request as a file.
        FileInputStream stream = null;
        try {
            File paymentRequestFile = new File(location);
            stream = new FileInputStream(paymentRequestFile);
        } catch (Exception e) {
            System.err.println("Failed to open file: " + e.getMessage());
            System.exit(1);
        }
        try {
            paymentRequest = com.ligerzero459.paycoinj.protocols.payments.Protos.PaymentRequest.newBuilder()
                    .mergeFrom(stream).build();
        } catch (IOException e) {
            System.err.println("Failed to parse payment request from file " + e.getMessage());
            System.exit(1);
        }
        PaymentSession session = null;
        try {
            session = new PaymentSession(paymentRequest, verifyPki);
        } catch (PaymentProtocolException e) {
            System.err.println("Error creating payment session " + e.getMessage());
            System.exit(1);
        }
        send(session);
    }
}

From source file:com.matthewmitchell.nubitsj.tools.WalletTool.java

private static void sendPaymentRequest(String location, boolean verifyPki) {
    if (location.startsWith("http") || location.startsWith("nubits")) {
        try {//from   w w  w  .  j  a va  2  s. c  o m
            ListenableFuture<PaymentSession> future;
            if (location.startsWith("http")) {
                future = PaymentSession.createFromUrl(location, verifyPki);
            } else {
                NubitsURI paymentRequestURI = new NubitsURI(location);
                future = PaymentSession.createFromNubitsUri(paymentRequestURI, verifyPki);
            }
            PaymentSession session = future.get();
            if (session != null) {
                send(session);
            } else {
                System.err.println("Server returned null session");
                System.exit(1);
            }
        } catch (PaymentProtocolException e) {
            System.err.println("Error creating payment session " + e.getMessage());
            System.exit(1);
        } catch (NubitsURIParseException e) {
            System.err.println("Invalid nubits uri: " + e.getMessage());
            System.exit(1);
        } catch (InterruptedException e) {
            // Ignore.
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    } else {
        // Try to open the payment request as a file.
        FileInputStream stream = null;
        try {
            File paymentRequestFile = new File(location);
            stream = new FileInputStream(paymentRequestFile);
        } catch (Exception e) {
            System.err.println("Failed to open file: " + e.getMessage());
            System.exit(1);
        }
        try {
            paymentRequest = org.nubits.protocols.payments.Protos.PaymentRequest.newBuilder().mergeFrom(stream)
                    .build();
        } catch (IOException e) {
            System.err.println("Failed to parse payment request from file " + e.getMessage());
            System.exit(1);
        }
        PaymentSession session = null;
        try {
            session = new PaymentSession(paymentRequest, verifyPki);
        } catch (PaymentProtocolException e) {
            System.err.println("Error creating payment session " + e.getMessage());
            System.exit(1);
        }
        send(session);
    }
}

From source file:com.continuuity.weave.internal.kafka.client.KafkaBrokerCache.java

private void getTopic(final String path, final String topic) {
    Futures.addCallback(zkClient.getChildren(path, new Watcher() {
        @Override//w  w w.ja v a2 s.  co  m
        public void process(WatchedEvent event) {
            // Other event type changes are either could be ignored or handled by parent watcher
            if (event.getType() == Event.EventType.NodeChildrenChanged) {
                getTopic(path, topic);
            }
        }
    }), new FutureCallback<NodeChildren>() {
        @Override
        public void onSuccess(NodeChildren result) {
            List<String> children = result.getChildren();
            final List<ListenableFuture<BrokerPartition>> futures = Lists
                    .newArrayListWithCapacity(children.size());

            // Fetch data from each broken node
            for (final String brokerId : children) {
                Futures.transform(zkClient.getData(path + "/" + brokerId),
                        new Function<NodeData, BrokerPartition>() {
                            @Override
                            public BrokerPartition apply(NodeData input) {
                                return new BrokerPartition(brokerId,
                                        Integer.parseInt(new String(input.getData(), Charsets.UTF_8)));
                            }
                        });
            }

            // When all fetching is done, build the partition size->broker map for this topic
            Futures.successfulAsList(futures).addListener(new Runnable() {
                @Override
                public void run() {
                    Map<Integer, Set<String>> partitionBrokers = Maps.newHashMap();
                    for (ListenableFuture<BrokerPartition> future : futures) {
                        try {
                            BrokerPartition info = future.get();
                            Set<String> brokerSet = partitionBrokers.get(info.getPartitionSize());
                            if (brokerSet == null) {
                                brokerSet = Sets.newHashSet();
                                partitionBrokers.put(info.getPartitionSize(), brokerSet);
                            }
                            brokerSet.add(info.getBrokerId());
                        } catch (Exception e) {
                            // Exception is ignored, as it will be handled by parent watcher
                        }
                    }
                    topicBrokers.put(topic, ImmutableSortedMap.copyOf(partitionBrokers));
                }
            }, Threads.SAME_THREAD_EXECUTOR);
        }

        @Override
        public void onFailure(Throwable t) {
            // No-op. Failure would be handled by parent watcher already (e.g. node not exists -> children change in parent)
        }
    });
}

From source file:io.mappum.altcoinj.tools.WalletTool.java

private static void sendPaymentRequest(String location, boolean verifyPki) {
    if (location.startsWith("http") || location.startsWith("bitcoinj")) {
        try {/* w ww. java 2  s  .c  o m*/
            ListenableFuture<PaymentSession> future;
            if (location.startsWith("http")) {
                future = PaymentSession.createFromUrl(location, verifyPki);
            } else {
                BitcoinURI paymentRequestURI = new BitcoinURI(location);
                future = PaymentSession.createFromBitcoinUri(paymentRequestURI, verifyPki);
            }
            PaymentSession session = future.get();
            if (session != null) {
                send(session);
            } else {
                System.err.println("Server returned null session");
                System.exit(1);
            }
        } catch (PaymentProtocolException e) {
            System.err.println("Error creating payment session " + e.getMessage());
            System.exit(1);
        } catch (BitcoinURIParseException e) {
            System.err.println("Invalid bitcoinj uri: " + e.getMessage());
            System.exit(1);
        } catch (InterruptedException e) {
            // Ignore.
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    } else {
        // Try to open the payment request as a file.
        FileInputStream stream = null;
        try {
            File paymentRequestFile = new File(location);
            stream = new FileInputStream(paymentRequestFile);
        } catch (Exception e) {
            System.err.println("Failed to open file: " + e.getMessage());
            System.exit(1);
        }
        try {
            paymentRequest = org.bitcoin.protocols.payments.Protos.PaymentRequest.newBuilder().mergeFrom(stream)
                    .build();
        } catch (IOException e) {
            System.err.println("Failed to parse payment request from file " + e.getMessage());
            System.exit(1);
        }
        PaymentSession session = null;
        try {
            session = new PaymentSession(paymentRequest, verifyPki);
        } catch (PaymentProtocolException e) {
            System.err.println("Error creating payment session " + e.getMessage());
            System.exit(1);
        }
        send(session);
    }
}

From source file:qa.qcri.nadeef.core.pipeline.ViolationDetector.java

/**
 * {@inheritDoc}// w w w .j ava  2 s.  c  o  m
 */
@Override
@SuppressWarnings("unchecked")
public Collection<Violation> execute(Optional emptyInput) throws Exception {
    detectCount = 0;
    totalThreadCount = 0;
    finishedThreadCount = 0;

    Rule rule = getCurrentContext().getRule();
    IteratorBlockingQueue iteratorBlockingQueue = new IteratorBlockingQueue();
    resultCollection.clear();
    List<Object> tupleList;
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<ListenableFuture<Integer>> futures = Lists.newArrayList();
    while (true) {
        tupleList = iteratorBlockingQueue.poll();
        if (tupleList.size() == 0) {
            break;
        }

        totalThreadCount++;
        ListenableFuture<Integer> future = service.submit(new Detector(tupleList, rule));
        futures.add(future);
        Futures.addCallback(future, new DetectorCallback());
    }

    // wait until all the futures finished
    for (ListenableFuture<Integer> future : futures) {
        future.get();
    }

    PerfReport.appendMetric(PerfReport.Metric.DetectTimeOnly, stopwatch.elapsed(TimeUnit.MILLISECONDS));
    PerfReport.appendMetric(PerfReport.Metric.DetectCount, detectCount);
    PerfReport.appendMetric(PerfReport.Metric.DetectThreadCount, totalThreadCount);
    stopwatch.stop();
    return resultCollection;
}