Example usage for com.google.common.util.concurrent FutureCallback FutureCallback

List of usage examples for com.google.common.util.concurrent FutureCallback FutureCallback

Introduction

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

Prototype

FutureCallback

Source Link

Usage

From source file:com.microsoft.services.odata.ODataMediaEntityFetcher.java

public ListenableFuture<byte[]> getContent() {

    final SettableFuture<byte[]> result = SettableFuture.create();

    Request request = getResolver().createRequest();
    request.setVerb(HttpVerb.GET);//from  w  ww  .  j  a  v  a  2s .c o  m
    ODataURL url = request.getUrl();
    url.appendPathComponent("$value");

    ListenableFuture<ODataResponse> future = oDataExecute(request);

    Futures.addCallback(future, new FutureCallback<ODataResponse>() {
        @Override
        public void onSuccess(ODataResponse response) {
            result.set(response.getPayload());
        }

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

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

public void postUpdatedFileContents(final O365APIsStart_Application application, final Activity currentActivity,
        SharePointClient fileClient, final String updatedContents) {
    ListenableFuture<Void> future = fileClient.getfiles().getById(application.getDisplayedFile().getId())
            .asFile().putContent(updatedContents.getBytes());

    Futures.addCallback(future, new FutureCallback<Void>() {
        @Override//from  w  ww. jav a  2 s. c  o  m
        public void onFailure(Throwable t) {
            Log.e("Asset", t.getMessage());
            // Notify caller that the Event update operation failed
            OperationResult opResult = new OperationResult("Post updated file contents",
                    "failed: " + getErrorMessage(t.getMessage()), "");
            mEventOperationCompleteListener.onOperationComplete(opResult);
        }

        @Override
        public void onSuccess(Void v) {
            // Update file contents in model
            O365FileModel fileItem = mApplication.getDisplayedFile();
            fileItem.setContents(currentActivity, updatedContents);
            // Notify caller that the Event update operation is complete and
            // succeeded
            OperationResult opResult = new OperationResult("Post updated file contents",
                    "Posted updated file contents", "FileContentsUpdate");
            mEventOperationCompleteListener.onOperationComplete(opResult);
        }
    });

}

From source file:org.opendaylight.vpnservice.elan.utils.ElanClusterUtils.java

public static void runOnlyInLeaderNode(final String jobKey, final String jobDescription,
        final Callable<List<ListenableFuture<Void>>> dataStoreJob) {
    ListenableFuture<Boolean> checkEntityOwnerFuture = ClusteringUtils.checkNodeEntityOwner(eos,
            HwvtepSouthboundConstants.ELAN_ENTITY_TYPE, HwvtepSouthboundConstants.ELAN_ENTITY_NAME);
    Futures.addCallback(checkEntityOwnerFuture, new FutureCallback<Boolean>() {
        @Override//  www  .j  av  a  2 s . c  o m
        public void onSuccess(Boolean isOwner) {
            if (isOwner) {
                logger.trace("scheduling job {} ", jobDescription);
                dataStoreJobCoordinator.enqueueJob(jobKey, dataStoreJob,
                        SystemPropertyReader.getDataStoreJobCoordinatorMaxRetries());
            } else {
                logger.trace("job is not run as i m not cluster owner desc :{} ", jobDescription);
            }
        }

        @Override
        public void onFailure(Throwable error) {
            logger.error("Failed to identity cluster owner for job " + jobDescription, error);
        }
    });
}

From source file:com.yahoo.yqlplus.engine.internal.java.runtime.TimeoutHandler.java

public <T> ListenableFuture<T> withTimeoutAsync(final Callable<ListenableFuture<T>> callable,
        final Timeout tracker, ListeningExecutorService executor) {
    final SettableFuture<T> result = SettableFuture.create();
    final long remaining = tracker.remainingTicks();
    final TimeUnit units = tracker.getTickUnits();
    final ListenableFuture<ListenableFuture<T>> source = executor.submit(callable);
    final ScheduledFuture<?> scheduledFuture = timers.schedule(new IntermediateTask<>(result, remaining, units),
            remaining, units);/*  ww  w.  j  a  va 2  s . com*/
    Futures.addCallback(source, scoper.continueScope(new FutureCallback<ListenableFuture<T>>() {
        @Override
        public void onSuccess(ListenableFuture<T> next) {
            scheduledFuture.cancel(false);
            try {
                long remaining = tracker.verify();
                final ScheduledFuture<?> remainingFuture = timers
                        .schedule(new TimeoutTask<>(next, result, remaining, units), remaining, units);
                Futures.addCallback(next, scoper.continueScope(new FutureCallback<T>() {
                    @Override
                    public void onSuccess(T out) {
                        remainingFuture.cancel(false);
                        result.set(out);
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        remainingFuture.cancel(false);
                        result.setException(t);
                    }
                }));
            } catch (TimeoutException e) {
                next.cancel(true);
                result.setException(e);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            scheduledFuture.cancel(false);
            result.setException(t);
        }
    }));
    return scoper.scopeCallbacks(result);
}

From source file:com.android.tools.idea.ddms.adb.GetAdbAction.java

@Override
public void actionPerformed(AnActionEvent e) {
    Notifications.Bus/*from  www .jav  a2s  .c om*/
            .notify(new Notification("Android", "ADB", "ADB requested.", NotificationType.INFORMATION));
    Project project = getEventProject(e);
    File adb = project == null ? null : AndroidSdkUtils.getAdb(project);
    if (adb == null) {
        return;
    }

    ListenableFuture<AndroidDebugBridge> bridge = AdbService.getInstance().getDebugBridge(adb);
    Futures.addCallback(bridge, new FutureCallback<AndroidDebugBridge>() {
        @Override
        public void onSuccess(AndroidDebugBridge result) {
            Notifications.Bus
                    .notify(new Notification("Android", "ADB", "ADB obtained", NotificationType.INFORMATION));
        }

        @Override
        public void onFailure(Throwable t) {
            Notifications.Bus.notify(new Notification("Android", "ADB", "ADB error: " + t.toString(),
                    NotificationType.INFORMATION));
        }
    });
}

From source file:de.btobastian.javacordbot.commands.DeleteCommand.java

@Command(aliases = { "+delete",
        "+del" }, description = "Deletes the last <amount> messages of [@user]", usage = "+delete <amount> [@user]", requiredPermissions = "delete")
public String onCommand(DiscordAPI api, String command, String[] args, Message message) {
    if (args.length != 1 && message.getMentions().size() == 0
            || args.length != 2 && message.getMentions().size() == 1) {
        return "Invalid amount of arguments!";
    }/*from  ww w.j a  va  2  s. co  m*/
    int amount = -1;
    try {
        amount = Integer.parseInt(args[0]);
    } catch (NumberFormatException ignored) {
    }

    if (amount < 1) {
        return "The amount must be a number greater than 0!";
    }

    final User fromAuthor = args.length == 1 ? null : message.getMentions().get(0);

    message.getReceiver().getMessageHistory(amount, new FutureCallback<MessageHistory>() {
        @Override
        public void onSuccess(MessageHistory history) {
            for (Message message : history.getMessages()) {
                if (fromAuthor != null && message.getAuthor() == fromAuthor) {
                    message.delete();
                } else if (fromAuthor == null) {
                    message.delete();
                }
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            message.reply("Error: " + throwable.getMessage());
        }
    });
    return null;
}

From source file:org.apache.twill.internal.zookeeper.RewatchOnExpireZKClient.java

@Override
public OperationFuture<Stat> exists(String path, Watcher watcher) {
    if (watcher == null) {
        return super.exists(path, null);
    }//  w  w  w  . j a v a  2  s .  c o m
    final RewatchOnExpireWatcher wrappedWatcher = new RewatchOnExpireWatcher(this, ActionType.EXISTS, path,
            watcher);
    OperationFuture<Stat> result = super.exists(path, wrappedWatcher);
    Futures.addCallback(result, new FutureCallback<Stat>() {
        @Override
        public void onSuccess(Stat result) {
            wrappedWatcher.setLastResult(result);
        }

        @Override
        public void onFailure(Throwable t) {
            // No-op
        }
    });
    return result;
}

From source file:io.crate.operation.join.SinglePagePageableTaskIterable.java

@Override
public ListenableFuture<Void> fetchPage(PageInfo pageInfo) throws NoSuchElementException {
    this.pageInfo(pageInfo);

    final SettableFuture<Void> future = SettableFuture.create();
    Futures.addCallback(currentTaskResult.fetch(pageInfo), new FutureCallback<PageableTaskResult>() {
        @Override/*from w w w  .  j ava 2s.  c om*/
        public void onSuccess(@Nullable PageableTaskResult result) {
            if (result == null) {
                future.setException(new IllegalArgumentException("PageableTaskResult is null"));
            }
            currentTaskResult = result;
            future.set(null);
        }

        @Override
        public void onFailure(Throwable t) {
            future.setException(t);
        }
    });
    return future;
}

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

@Override
protected void setUp() throws Exception {
    super.setUp();
    final ICalendars cals = Me.getCalendars();
    final CountDownLatch cdl = new CountDownLatch(1);
    // an empty iterator will be returned for any entity set unless you call fetch()
    Futures.addCallback(cals.fetchAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            cdl.countDown();/* w  w w. java  2s .  c  om*/
        }

        public void onSuccess(Void result) {
            Iterator<ICalendar> iterator = cals.iterator();
            if (iterator.hasNext()) {
                calendar = iterator.next();
            }
            cdl.countDown();
        }
    });

    cdl.await(60000, TimeUnit.MILLISECONDS);
    if (calendar == null) {
        fail("No calendar found");
    }
}

From source file:org.opendaylight.mdsal.dom.broker.TransactionChainReadTransaction.java

@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    final SettableFuture<Optional<NormalizedNode<?, ?>>> readResult = SettableFuture.create();

    Futures.addCallback(previousWriteTxFuture, new FutureCallback<Void>() {
        @Override//from w  w  w.j a v a 2s  . com
        public void onSuccess(@Nullable final Void result) {
            Futures.addCallback(delegateReadTx.read(store, path),
                    new FutureCallback<Optional<NormalizedNode<?, ?>>>() {

                        @Override
                        public void onSuccess(@Nullable final Optional<NormalizedNode<?, ?>> result) {
                            readResult.set(result);
                        }

                        @Override
                        public void onFailure(final Throwable throwable) {
                            txChain.transactionFailed(TransactionChainReadTransaction.this, throwable);
                            readResult.setException(throwable);
                        }
                    });
        }

        @Override
        public void onFailure(final Throwable throwable) {
            // we don't have to notify txchain about this failure
            // failed write transaction should do this
            readResult.setException(throwable);
        }
    });

    return Futures.makeChecked(readResult, ReadFailedException.MAPPER);
}