Example usage for com.google.common.util.concurrent Futures addCallback

List of usage examples for com.google.common.util.concurrent Futures addCallback

Introduction

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

Prototype

public static <V> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback) 

Source Link

Document

Registers separate success and failure callbacks to be run when the Future 's computation is java.util.concurrent.Future#isDone() complete or, if the computation is already complete, immediately.

Usage

From source file:io.crate.executor.transport.task.elasticsearch.QueryThenFetchPageableTaskResult.java

private void fetchFromSource(int from, int size, final FutureCallback<ObjectArray<Object[]>> callback) {
    Futures.addCallback(Futures.transform(operation.executePageQuery(from, size, ctx),
            new Function<InternalSearchResponse, ObjectArray<Object[]>>() {
                @javax.annotation.Nullable
                @Override/*from w w  w. ja  v  a  2  s  .c o m*/
                public ObjectArray<Object[]> apply(@Nullable InternalSearchResponse input) {
                    return ctx.toPage(input.hits().hits(), extractors);
                }
            }), callback);
}

From source file:com.fullcontact.sstable.index.SSTableIndexIndexer.java

public void index(final Path sstablePath) throws IOException {

    final FileSystem fileSystem = FileSystem.get(URI.create(sstablePath.toString()), configuration);
    final FileStatus fileStatus = fileSystem.getFileStatus(sstablePath);

    if (fileStatus.isDir()) {
        LOG.info("SSTable Indexing directory {}", sstablePath);
        final FileStatus[] statuses = fileSystem.listStatus(sstablePath);
        for (final FileStatus childStatus : statuses) {
            index(childStatus.getPath());
        }/*from  w w  w. ja  va 2s . c  o  m*/
    } else if (sstablePath.toString().endsWith(SST_EXTENSION)) {
        final Path sstableIndexPath = new Path(sstablePath.toString() + SSTableIndexIndex.SSTABLE_INDEX_SUFFIX);
        if (fileSystem.exists(sstableIndexPath)) {
            LOG.info("Skipping as SSTable index file already exists for {}", sstablePath);
        } else {
            // Kick a thread for the index.
            final ListenableFuture<IndexRequest> indexFuture = service.submit(new Callable<IndexRequest>() {
                @Override
                public IndexRequest call() throws Exception {
                    final long startTime = System.currentTimeMillis();
                    final long fileSize = fileStatus.getLen();

                    LOG.info("Indexing SSTABLE Indexing file {}, size {} GB...", sstablePath,
                            decimalFormat.format(fileSize / (1024.0 * 1024.0 * 1024.0)));

                    indexSingleFile(fileSystem, sstablePath);

                    return new IndexRequest(sstableIndexPath, startTime, fileSize);
                }
            });

            Futures.addCallback(indexFuture, new FutureCallback<IndexRequest>() {
                public void onSuccess(final IndexRequest indexRequest) {
                    long indexSize = 0;

                    try {
                        indexSize = fileSystem.getFileStatus(indexRequest.getIndexPath()).getLen();
                    } catch (IOException e) {
                        LOG.error("Error getting file status for index path: {}", indexRequest.getIndexPath());
                    }

                    final double elapsed = (System.currentTimeMillis() - indexRequest.getStartTime()) / 1000.0;

                    LOG.info("Completed SSTABLE Indexing in {} seconds ({} MB/s).  Index size is {} KB.",
                            decimalFormat.format(elapsed),
                            decimalFormat.format(indexRequest.getFileSize() / (1024.0 * 1024.0 * elapsed)),
                            decimalFormat.format(indexSize / 1024.0));
                }

                public void onFailure(Throwable e) {
                    LOG.error("Failed to index.", e);
                }
            });

        }
    }
}

From source file:com.facebook.presto.metadata.RemoteNodeState.java

public synchronized void asyncRefresh() {
    Duration sinceUpdate = nanosSince(lastUpdateNanos.get());
    if (nanosSince(lastWarningLogged.get()).toMillis() > 1_000 && sinceUpdate.toMillis() > 10_000
            && future.get() != null) {
        log.warn("Node state update request to %s has not returned in %s", stateInfoUri,
                sinceUpdate.toString(SECONDS));
        lastWarningLogged.set(System.nanoTime());
    }/* w ww  . j a  v  a2 s .com*/
    if (sinceUpdate.toMillis() > 1_000 && future.get() == null) {
        Request request = prepareGet().setUri(stateInfoUri).setHeader(CONTENT_TYPE, JSON_UTF_8.toString())
                .build();
        HttpResponseFuture<JsonResponse<NodeState>> responseFuture = httpClient.executeAsync(request,
                createFullJsonResponseHandler(jsonCodec(NodeState.class)));
        future.compareAndSet(null, responseFuture);

        Futures.addCallback(responseFuture, new FutureCallback<JsonResponse<NodeState>>() {
            @Override
            public void onSuccess(@Nullable JsonResponse<NodeState> result) {
                lastUpdateNanos.set(System.nanoTime());
                future.compareAndSet(responseFuture, null);
                if (result != null) {
                    if (result.hasValue()) {
                        nodeState.set(ofNullable(result.getValue()));
                    }
                    if (result.getStatusCode() != OK.code()) {
                        log.warn("Error fetching node state from %s returned status %d: %s", stateInfoUri,
                                result.getStatusCode(), result.getStatusMessage());
                        return;
                    }
                }
            }

            @Override
            public void onFailure(Throwable t) {
                log.warn("Error fetching node state from %s: %s", stateInfoUri, t.getMessage());
                lastUpdateNanos.set(System.nanoTime());
                future.compareAndSet(responseFuture, null);
            }
        });
    }
}

From source file:org.opendaylight.vtn.manager.it.ofmock.impl.AddFlowTask.java

/**
 * Construct a new instance./*from  w  w w  .j av a2 s . co  m*/
 *
 * @param node   The target switch.
 * @param input  The input for the add-flow RPC.
 * @param ofent  The ofmock flow entry created from the RPC input.
 */
public AddFlowTask(OfNode node, AddFlowInput input, OfMockFlowEntry ofent) {
    super(node.getOfMockProvider().getDataBroker());

    verify(EXPECTED_FLAGS, ofent.getFlowModFlags(), "Invalid flow-mod-flags");

    flowId = ofent.getFlowId();
    FlowId fid = new FlowId(flowId);
    FlowTable table = node.getFlowTable();

    targetNode = node;
    flowTable = table;
    mockFlow = ofent;
    flowEntry = new FlowBuilder(input).setId(fid).build();
    flowPath = table.getTablePath().child(Flow.class, new FlowKey(fid));
    ofent.setFlowEntry(flowEntry);
    Futures.addCallback(getFuture(), this);
}

From source file:ninja.leaping.permissionsex.command.PermissionsExExecutor.java

protected <TextType> void messageSubjectOnFuture(ListenableFuture<?> future, final Commander<TextType> src,
        final Translatable message) {
    Futures.addCallback(future, new FutureCallback<Object>() {
        @Override/*from  w w w  . j a  v  a 2 s.  co m*/
        public void onSuccess(Object result) {
            src.msg(message);
        }

        @Override
        public void onFailure(Throwable t) {
            src.msg(_("Error (%s) occurred while performing command task! Please see console for details: %s",
                    t.getClass().getSimpleName(), t.getMessage()));
            pex.getLogger().error(_("Error occurred while executing command for user %s", src.getName())
                    .translateFormatted(Locale.getDefault()), t);
        }
    });

}

From source file:org.opendaylight.l2switch.hosttracker.plugin.internal.OperationProcessor.java

public void submitTransaction(final ReadWriteTransaction tx, final int tries) {
    Futures.addCallback(tx.submit(), new FutureCallback<Object>() {
        public void onSuccess(Object o) {
            log.trace("tx {} succeeded", tx.getIdentifier());
        }/*from   w  w w . j  a  v  a2 s .  c  o m*/

        public void onFailure(Throwable t) {
            if (t instanceof OptimisticLockFailedException) {
                if ((tries - 1) > 0) {
                    log.warn("tx {} failed, retrying", tx.getIdentifier());
                    // do retry
                    submitTransaction(tx, tries - 1);
                } else {
                    log.warn("tx {} failed, out of retries", tx.getIdentifier());
                    // out of retries
                    chainFailure();
                }
            } else {
                // failed due to another type of
                // TransactionCommitFailedException.
                log.warn("tx {} failed: {}", t.getMessage());
                chainFailure();
            }
        }
    });
}

From source file:com.facebook.buck.event.listener.RemoteLogUploaderEventListener.java

private void registerPendingUpload(final ListenableFuture<Void> upload) {
    synchronized (pendingUploads) {
        pendingUploads.add(upload);//from   w  w  w  .  ja  v  a2 s . com
    }
    Futures.addCallback(upload, new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            failureCount.set(0);
            onDone();
        }

        @Override
        public void onFailure(Throwable t) {
            onDone();
            LOG.info(t, "Failed uploading event to the remote log.");
            if (failureCount.incrementAndGet() == MAX_FAILURE_COUNT) {
                LOG.info("Maximum number of log upload failures reached, giving up.");
            }
        }

        private void onDone() {
            synchronized (pendingUploads) {
                pendingUploads.remove(upload);
            }
        }
    });
}

From source file:com.microsoft.office.integration.test.FoldersAsyncTestCase.java

public void testDelete() {
    prepareFolder();/*from  www . ja va 2s .  com*/
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        public void onSuccess(Void result) {
            try {
                deleteAndCheck();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });
    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testDelete() timed out");
        }
    } catch (InterruptedException e) {
        fail("testDelete() has been interrupted");
    }
}

From source file:edu.dirla.app.ws.rest.services.LogsRestService.java

@ResponseBody
@RequestMapping(method = RequestMethod.POST)
public DataTrafficResult addLogs(@RequestBody CheckTrafficRep checkTrafficRep) {

    List<LogData> results = null;
    long t1 = Calendar.getInstance().getTimeInMillis();

    final List<String> filesToUpload = checkTrafficRep.getFilesToUpload();

    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(3));
    for (final String fileName : filesToUpload) {

        Callable<Integer> job = new Callable<Integer>() {

            @Override//from  ww  w.  ja  v a 2s  .c om
            public Integer call() throws Exception {
                List<LogData> lines = new ArrayList<LogData>();
                try {
                    lines.addAll(readFile(fileName));
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Map<String, Long> data = new HashMap<String, Long>();

                for (LogData res : lines) {
                    String key = res.getDomain();
                    long value = res.getSize();
                    Long oldValue = data.get(key);
                    data.put(key, value + (oldValue != null ? oldValue : 0));
                }

                logsService.pushLogs("accessLogs." + fileName, data);

                return 0;
            }
        }; // create the job here
        ListenableFuture<Integer> completion = executor.submit(job);
        Futures.addCallback(completion, new FutureCallback<Integer>() {

            @Override
            public void onFailure(Throwable t) {
                // log error
            }

            @Override
            public void onSuccess(Integer result) {
                // do something with the result
            }

        });
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    UserDataTrafficResult userTrafficData = logsService.checkDataTraffic(checkTrafficRep.getClientAddress());

    long t2 = Calendar.getInstance().getTimeInMillis();

    DataTrafficResult dtr = new DataTrafficResult();
    dtr.setCheckTrafficRequest(checkTrafficRep);
    dtr.setTrafficValue(userTrafficData);
    dtr.setTime(t2 - t1);
    return dtr;
}

From source file:ch.icclab.netfloc.impl.Flowprogrammer.java

private void commitWriteTransaction(final WriteTransaction wt, final FutureCallback<Void> cb,
        final int totalTries, final int tries) {
    Futures.addCallback(wt.submit(), new FutureCallback<Void>() {
        public void onSuccess(Void result) {
            logger.info("Transaction success after {} tries for {}", totalTries - tries + 1, wt);
            cb.onSuccess(result);/*from   w  w w.  j  a  v a 2 s. c o m*/
        }

        public void onFailure(Throwable t) {
            if (t instanceof OptimisticLockFailedException) {
                if ((tries - 1) > 0) {
                    logger.warn("Transaction retry {} for {}", totalTries - tries + 1, wt);
                    commitWriteTransaction(wt, cb, totalTries, tries - 1);
                } else {
                    logger.error("Transaction out of retries: ", wt);
                    cb.onFailure(t);
                }
            } else {
                if (t instanceof DataValidationFailedException) {
                    logger.error("Transaction validation failed {}", t.getMessage());
                } else {
                    logger.error("Transaction failed {}", t.getMessage());
                }
                cb.onFailure(t);
            }
        }
    });
}