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:org.gradle.internal.filewatch.jdk7.WatchServiceFileWatcherBacking.java

public FileWatcher start(ListeningExecutorService executorService) {
    if (started.compareAndSet(false, true)) {
        final ListenableFuture<?> runLoopFuture = executorService.submit(new Runnable() {
            @Override//from   w ww . j  a  v a2 s . c  o  m
            public void run() {
                if (!stopped.get()) {
                    running.set(true);
                    try {
                        try {
                            pumpEvents();
                        } catch (InterruptedException e) {
                            // just stop
                        } catch (Throwable t) {
                            stop();
                            onError.execute(t);
                        }
                    } finally {
                        stop();
                    }
                }
            }
        });

        // This is necessary so that the watcher indicates its not running if the runnable gets cancelled
        Futures.addCallback(runLoopFuture, new FutureCallback<Object>() {
            @Override
            public void onSuccess(Object result) {
                running.set(false);
            }

            @Override
            public void onFailure(Throwable t) {
                running.set(false);
            }
        });
        return fileWatcher;
    } else {
        throw new IllegalStateException("file watcher is started");
    }
}

From source file:org.robotninjas.barge.state.ReplicaManager.java

private ListenableFuture<AppendEntriesResponse> sendUpdate() {

    running++;//  w  ww  .j a v  a2  s  . c o m
    requested = false;

    // if the last rpc call was successful then try to send
    // as many updates as we can, otherwise, if we're
    // probing backwards, only send one entry as a probe, as
    // soon as we have a successful call forwards will become
    // true and we can catch up quickly
    GetEntriesResult result = log.getEntriesFrom(nextIndex, forwards ? BATCH_SIZE : 1);

    final AppendEntries request = AppendEntries.newBuilder().setTerm(log.currentTerm())
            .setLeaderId(log.self().toString()).setPrevLogIndex(result.lastLogIndex())
            .setPrevLogTerm(result.lastLogTerm()).setCommitIndex(log.commitIndex())
            .addAllEntries(result.entries()).build();

    LOGGER.debug("Sending update to {} prevLogIndex {} prevLogTerm {}", remote, result.lastLogIndex(),
            result.lastLogTerm());
    final ListenableFuture<AppendEntriesResponse> response = client.appendEntries(remote, request);

    final SettableFuture<AppendEntriesResponse> previousResponse = nextResponse;

    Futures.addCallback(response, new FutureCallback<AppendEntriesResponse>() {

        @Override
        public void onSuccess(@Nullable AppendEntriesResponse result) {
            running--;
            updateNextIndex(request, result);
            if (result.getSuccess()) {
                previousResponse.set(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            running--;
            requested = false;
            previousResponse.setException(t);
        }

    });

    nextResponse = SettableFuture.create();

    return response;

}

From source file:com.continuuity.weave.internal.ZKWeaveController.java

@Override
public ListenableFuture<State> stop() {
    final SettableFuture<State> result = SettableFuture.create();
    final ListenableFuture<State> future = super.stop();
    future.addListener(new Runnable() {
        @Override/*from ww  w.  jav a 2s . c  o  m*/
        public void run() {
            logPoller.interrupt();
            try {
                logPoller.join();
            } catch (InterruptedException e) {
                LOG.warn("Joining of log poller thread interrupted.", e);
            }
            Futures.addCallback(kafkaClient.stop(), new FutureCallback<Service.State>() {
                @Override
                public void onSuccess(Service.State state) {
                    try {
                        future.get();
                        result.set(State.TERMINATED);
                    } catch (Exception e) {
                        LOG.error("Failed when stopping local services", e);
                        result.setException(e);
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    result.setException(t);
                }
            });
        }
    }, Threads.SAME_THREAD_EXECUTOR);
    return result;
}

From source file:io.uploader.drive.gui.model.DriveTaskModel.java

public synchronized void start(final Callback<DriveOperations.OperationResult> callback) {
    //if (driveTask == null) {
    //   throw new IllegalStateException () ;
    //}//  w  w  w  .jav  a  2  s.  c  o  m
    Preconditions.checkNotNull(driveTask);
    result = taskFactory.getExecutor().submit(driveTask);
    Futures.addCallback(result, new FutureCallback<DriveOperations.OperationResult>() {

        public void onSuccess(DriveOperations.OperationResult result) {
            logger.info("Task is finished.");
            if (callback != null) {
                callback.onSuccess(result);
            }
        }

        public void onFailure(Throwable thrown) {
            logger.error("Error occurred while task was being performed", thrown);
            if (callback != null) {
                callback.onFailure(thrown);
            }
        }
    });
}

From source file:org.n52.lod.triplestore.AbstractWorkerTripleSink.java

@Override
protected int addRecordsToModel(Map<String, GetRecordByIdResponseDocument> records, final Model m,
        final Report report) {
    final MutableInt counter = new MutableInt(0);
    final long modelSizeBefore = m.size();

    ListeningExecutorService executorService = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(NUM_THREADS));

    for (Entry<String, GetRecordByIdResponseDocument> entry : records.entrySet()) {

        final String id = entry.getKey();
        log.debug("Adding {} to the model", id);

        CallableMapper c = new CallableMapper(this.mapper.replicate(), entry.getValue());
        ListenableFuture<Model> modelFuture = executorService.submit(c);

        Futures.addCallback(modelFuture, new FutureCallback<Model>() {

            @Override/*from   ww  w. j a v a2s. c om*/
            public void onFailure(Throwable t) {
                log.error("Error mapping xml to model", t);
                report.issues.put(id, "Error while adding to model: " + t.getMessage());
            }

            @Override
            public void onSuccess(Model result) {
                log.trace("Adding result to model: {}", result);
                m.add(result);
                log.trace("ADDED result to mode.");

                counter.increment();
                report.added++;
                report.addedIds.add(id);
            }

        });
    }

    executorService.shutdown();
    while (!executorService.isTerminated()) {
        try {
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            log.error("Could not await termination", e);
        }
    }

    log.debug("Added {} of {} records to model {}, which now has size {} (before {})", counter, records.size(),
            m.getClass(), m.size(), modelSizeBefore);
    return counter.intValue();
}

From source file:com.microsoft.office365.starter.FilesFolders.O365FileListModel.java

public void postUploadFileToServer(final O365APIsStart_Application application, final Activity currentActivity,
        final O365FileModel fileToUpload, final SharePointClient fileClient) {
    final Item newFile = new Item();
    newFile.settype("File");
    newFile.setname(fileToUpload.getName());

    ListenableFuture<Item> future = fileClient.getfiles().add(newFile);
    Futures.addCallback(future, new FutureCallback<Item>() {
        @Override/*from  w  w  w .j  a va 2s .  com*/
        public void onFailure(Throwable t) {
            Log.e("Asset", t.getMessage());
            // Notify caller that the Event update operation failed

            OperationResult opResult = new OperationResult("Upload file ",
                    "Failed: " + APIErrorMessageHelper.getErrorMessage(t.getMessage()), "");
            mEventOperationCompleteListener.onOperationComplete(opResult);
        }

        @Override
        public void onSuccess(final Item item) {
            try {
                fileClient.getfiles().getById(item.getid()).asFile()
                        .putContent(fileToUpload.getContents().getBytes()).get();

                currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        application.getFileListViewState().addNewFileToList(item);
                    }
                });
                // Notify caller that the Event update operation is complete
                // and succeeded
                OperationResult opResult = new OperationResult("Upload file to server", "File uploaded", "");
                mEventOperationCompleteListener.onOperationComplete(opResult);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    });

}

From source file:com.microsoft.services.orc.core.BaseOrcContainer.java

@Override
protected ListenableFuture<OrcResponse> oDataExecute(final Request request) {
    final SettableFuture<OrcResponse> result = SettableFuture.create();
    final Logger logger = resolver.getLogger();

    try {//from   www  .  ja v  a2s . co m
        request.getUrl().setBaseUrl(this.url);
        String fullUrl = request.getUrl().toString();

        String executionInfo = String.format("URL: %s - HTTP VERB: %s", fullUrl, request.getVerb());
        logger.log("Start preparing OData execution for " + executionInfo, LogLevel.INFO);

        if (request.getContent() != null) {
            logger.log("With " + request.getContent().length + " bytes of payload", LogLevel.INFO);
        } else if (request.getStreamedContent() != null) {
            logger.log("With stream of bytes for payload", LogLevel.INFO);
        }

        HttpTransport httpTransport = resolver.getHttpTransport();

        String userAgent = resolver.getPlatformUserAgent(this.getClass().getCanonicalName());
        request.addHeader(Constants.USER_AGENT_HEADER, userAgent);
        request.addHeader(Constants.TELEMETRY_HEADER, userAgent);
        if (!request.getHeaders().containsKey(Constants.CONTENT_TYPE_HEADER)) {
            request.addHeader(Constants.CONTENT_TYPE_HEADER, Constants.JSON_CONTENT_TYPE);
        }
        request.addHeader(Constants.ACCEPT_HEADER, Constants.JSON_CONTENT_TYPE);
        request.addHeader(Constants.ODATA_VERSION_HEADER, Constants.ODATA_VERSION);
        request.addHeader(Constants.ODATA_MAXVERSION_HEADER, Constants.ODATA_MAXVERSION);

        if (request.getHeaders() != null) {
            for (String key : request.getHeaders().keySet()) {
                request.addHeader(key, request.getHeaders().get(key));
            }
        }

        boolean credentialsSet = false;

        Credentials cred = resolver.getCredentials();
        if (cred != null) {
            cred.prepareRequest(request);
            credentialsSet = true;
        }

        if (!credentialsSet) {
            logger.log("Executing request without setting credentials", LogLevel.WARNING);
        }

        logger.log("Request Headers: ", LogLevel.VERBOSE);
        for (String key : request.getHeaders().keySet()) {
            logger.log(key + " : " + request.getHeaders().get(key), LogLevel.VERBOSE);
        }

        final ListenableFuture<Response> future = httpTransport.execute(request);
        logger.log("OData request executed", LogLevel.INFO);

        Futures.addCallback(future, new FutureCallback<Response>() {

            @Override
            public void onSuccess(Response response) {
                boolean readBytes = true;
                if (request.getOptions().get(Request.MUST_STREAM_RESPONSE_CONTENT) != null) {
                    readBytes = false;
                }

                OrcResponse orcResponse = new OrcResponseImpl(response);

                try {
                    logger.log("OData response received", LogLevel.INFO);

                    int status = response.getStatus();
                    logger.log("Response Status Code: " + status, LogLevel.INFO);

                    if (readBytes) {
                        logger.log("Reading response data...", LogLevel.VERBOSE);
                        byte[] data = orcResponse.getPayload();
                        logger.log(data.length + " bytes read from response", LogLevel.VERBOSE);

                        try {
                            logger.log("Closing response", LogLevel.VERBOSE);
                            response.close();
                        } catch (Throwable t) {
                            logger.log("Error closing response: " + t.toString(), LogLevel.ERROR);
                            result.setException(t);
                            return;
                        }

                    }

                    if (status < 200 || status > 299) {
                        logger.log("Invalid status code. Processing response content as String",
                                LogLevel.VERBOSE);
                        String responseData = new String(orcResponse.getPayload(), Constants.UTF8_NAME);
                        String message = "Response status: " + response.getStatus() + "\n"
                                + "Response content: " + responseData;
                        logger.log(message, LogLevel.ERROR);
                        result.setException(new OrcException(orcResponse, message));
                        return;
                    }
                    result.set(orcResponse);
                } catch (Throwable t) {
                    logger.log("Unexpected error: " + t.toString(), LogLevel.ERROR);
                    result.setException(new OrcException(orcResponse, t));
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                result.setException(throwable);
            }
        });
    } catch (Throwable t) {
        result.setException(t);
    }
    return result;

}

From source file:eu.point.registry.impl.NodeConnectorRegistryUtils.java

/**
 * The method which writes to the registry a specific entry.
 *
 * @param input The entry to be written in the registry.
 * @see NodeConnectorRegistryEntry//w  w  w . java  2s. c  o  m
 */
public void writeToNodeConnectorRegistry(NodeConnectorRegistryEntry input) {
    LOG.debug("Writing to NodeConnector registry input {}.", input);
    WriteTransaction transaction = db.newWriteOnlyTransaction();
    InstanceIdentifier<NodeConnectorRegistryEntry> iid = toInstanceIdentifier(input);

    transaction.put(LogicalDatastoreType.OPERATIONAL, iid, input);
    CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
    Futures.addCallback(future,
            new LoggingFuturesCallBack<Void>("Failed to write to NodeConnector registry", LOG));
}

From source file:io.crate.operation.collect.JobCollectContext.java

public JobCollectContext(final CollectPhase collectPhase, MapSideDataCollectOperation collectOperation,
        String localNodeId, RamAccountingContext queryPhaseRamAccountingContext, final RowReceiver rowReceiver,
        SharedShardContexts sharedShardContexts) {
    super(collectPhase.phaseId(), LOGGER);
    this.collectPhase = collectPhase;
    this.collectOperation = collectOperation;
    this.queryPhaseRamAccountingContext = queryPhaseRamAccountingContext;
    this.sharedShardContexts = sharedShardContexts;

    listenableRowReceiver = RowReceivers.listenableRowReceiver(rowReceiver);
    Futures.addCallback(listenableRowReceiver.finishFuture(), new FutureCallback<Void>() {
        @Override/*  w  w w .  j  a  v a  2 s  . c o m*/
        public void onSuccess(@Nullable Void result) {
            close();
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            closeDueToFailure(t);
        }
    });
    this.rowReceiver = listenableRowReceiver;
    this.threadPoolName = threadPoolName(collectPhase, localNodeId);
}

From source file:org.opendaylight.bgpcep.pcep.topology.spi.AbstractInstructionExecutor.java

@Override
public void onSuccess(final Instruction insn) {
    if (insn.checkedExecutionStart()) {
        final ListenableFuture<OperationResult> s = invokeOperation();
        Futures.addCallback(s, new InstructionCallback(insn));
    }//from   w  w  w .j av a 2  s  .c  o m
}