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:com.microsoft.filediscovery.ServiceListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    setContentView(R.layout.activity_lists);

    new RetrieveServicesTask(ServiceListActivity.this).execute();

    mApplication = (DiscoveryAPIApplication) getApplication();
    mListView = (ListView) findViewById(R.id.list);

    mListView.setOnItemClickListener(new OnItemClickListener() {
        @Override/*from  www.  j  ava2  s .  c  o  m*/
        public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) {

            final ServiceViewItem serviceItem = (ServiceViewItem) mListView.getItemAtPosition(position);

            if (serviceItem.getSelectable()) {
                try {

                    ListenableFuture<Map<String, Credentials>> future = Authentication.authenticate(
                            ServiceListActivity.this,
                            ((ServiceViewItem) mListView.getItemAtPosition(position)).getResourceId());

                    Futures.addCallback(future, new FutureCallback<Map<String, Credentials>>() {
                        @Override
                        public void onFailure(Throwable t) {
                            Log.e("Asset", t.getMessage());
                        }

                        @Override
                        public void onSuccess(Map<String, Credentials> credentials) {
                            openSelectedService(serviceItem);
                        }
                    });

                } catch (Throwable t) {
                    Log.e("Asset", t.getMessage());
                }
            }
        }
    });
}

From source file:com.spotify.helios.servicescommon.GooglePubSubSender.java

@Override
public void send(final String topic, final byte[] message) {
    final String combinedTopic = topicPrefix + topic;

    if (!healthchecker.isHealthy()) {
        log.warn(//www  .jav a2s.c o m
                "will not publish message to pubsub topic={} as the pubsub client " + "appears to be unhealthy",
                combinedTopic);
        return;
    }

    try {
        Futures.addCallback(
                JdkFutureAdapters.listenInPoolThread(
                        pubsub.publishAsync(combinedTopic, Message.of(ByteArray.copyFrom(message)))),
                new FutureCallback<String>() {
                    @Override
                    public void onSuccess(@Nullable final String ackId) {
                        log.debug("Sent an event to Google PubSub, topic: {}, ack: {}", combinedTopic, ackId);
                    }

                    @Override
                    public void onFailure(final Throwable th) {
                        log.warn("Unable to send an event to Google PubSub, topic: {}", combinedTopic, th);
                    }
                });
    } catch (Exception e) {
        log.warn("Failed to publish Google PubSub message, topic: {}", combinedTopic, e);
    }
}

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

public void testUpdate() {
    counter = new CountDownLatch(1);
    // create contact first
    prepareContact();//w  w  w  . j a  v a 2s.c o m
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        public void onSuccess(Void result) {
            try {
                updateAndCheck();
                // clean up
                removeContact();
            } catch (Throwable t) {
                reportError(t);
            }

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

From source file:com.facebook.presto.operator.ParallelLookupSourceSupplier.java

@Override
public void release() {
    if (referenceCount.decrementAndGet() == 0) {
        // We own the shared lookup sources, so we need to free their memory
        for (ListenableFuture<SharedLookupSource> future : partitions) {
            Futures.addCallback(future, new FutureCallback<SharedLookupSource>() {
                @Override/*from  w w  w.j  av a 2  s.c  o m*/
                public void onSuccess(SharedLookupSource result) {
                    result.freeMemory();
                }

                @Override
                public void onFailure(Throwable t) {
                    // ignored
                }
            });
        }
    }
}

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

/**
 * The method which initializes the registry data tree.
 *//*w w  w  .j a  v a2  s  .  com*/
public void initializeDataTree() {
    LOG.debug("Preparing to initialize the Node registry");
    WriteTransaction transaction = db.newWriteOnlyTransaction();
    InstanceIdentifier<NodeRegistry> iid = InstanceIdentifier.create(NodeRegistry.class);
    NodeRegistry greetingRegistry = new NodeRegistryBuilder().build();
    transaction.put(LogicalDatastoreType.OPERATIONAL, iid, greetingRegistry);
    CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
    Futures.addCallback(future, new LoggingFuturesCallBack<>("Failed to create Node registry", LOG));
}

From source file:com.android.builder.internal.aapt.AbstractProcessExecutionAapt.java

@Override
@NonNull/*from   ww  w  . j  a  va  2  s .c  o  m*/
protected ListenableFuture<Void> makeValidatedPackage(@NonNull AaptPackageConfig config) throws AaptException {
    ProcessInfoBuilder builder = makePackageProcessBuilder(config);

    final ProcessInfo processInfo = builder.createProcess();
    ListenableFuture<ProcessResult> execResult = mProcessExecutor.submit(processInfo, mProcessOutputHandler);

    final SettableFuture<Void> result = SettableFuture.create();
    Futures.addCallback(execResult, new FutureCallback<ProcessResult>() {
        @Override
        public void onSuccess(ProcessResult processResult) {
            try {
                processResult.rethrowFailure().assertNormalExitValue();
                result.set(null);
            } catch (Exception e) {
                result.setException(e);
            }
        }

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

    return result;
}

From source file:com.facebook.swift.service.async.AsyncHttpClient.java

@Test
public void testHttpAsyncClient() throws Exception {
    try (final HttpScribeServer server = new HttpScribeServer();
            ThriftClientManager clientManager = new ThriftClientManager()) {
        server.start();/*from   ww w.  j a v a  2 s .  c  om*/
        final CountDownLatch latch = new CountDownLatch(1);

        // Server was just started, it shouldn't have recorded any messages yet
        assertEquals(server.getLogEntries().size(), 0);

        int serverPort = server.getLocalPort();

        ListenableFuture<AsyncScribe> clientFuture = createHttpClient(AsyncScribe.class, serverPort);
        Futures.addCallback(clientFuture, new FutureCallback<AsyncScribe>() {
            @Override
            public void onSuccess(AsyncScribe client) {
                try {
                    ListenableFuture<ResultCode> methodFuture = client
                            .log(Lists.newArrayList(new LogEntry("testCategory", "testMessage")));

                    // Connected a client, and made an async call against it, but the call shouldn't
                    // be completed right away. Check that it isn't.
                    assertEquals(server.getLogEntries().size(), 0);

                    Futures.addCallback(methodFuture, new FutureCallback<ResultCode>() {
                        @Override
                        public void onSuccess(ResultCode result) {
                            latch.countDown();
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            latch.countDown();
                        }
                    });
                } catch (Throwable th) {
                    onFailure(th);
                }
            }

            @Override
            public void onFailure(Throwable t) {
                latch.countDown();
            }
        });

        latch.await();

        // Now that the latch is clear, client should have connected and the async call completed
        // so check that it did so successfully.
        assertEquals(server.getLogEntries().size(), 1);
    }
}

From source file:com.facebook.buck.artifact_cache.ArtifactUploader.java

public static ListenableFuture<Void> performUploadToArtifactCache(ImmutableSet<RuleKey> ruleKeys,
        ArtifactCache artifactCache, BuckEventBus eventBus, ImmutableMap<String, String> buildMetadata,
        SortedSet<Path> pathsToIncludeInArchive, BuildTarget buildTarget, ProjectFilesystem projectFilesystem,
        long buildTimeMs) {
    NamedTemporaryFile archive;//from  ww  w  .jav  a 2 s  .  c o  m
    try {
        archive = getTemporaryArtifactArchive(buildTarget, projectFilesystem, ruleKeys, eventBus,
                pathsToIncludeInArchive);
    } catch (BuckUncheckedExecutionException e) {
        LOG.error(e.getMessage());
        LOG.debug(e.toString() + "\n" + Throwables.getStackTraceAsString(e));
        return Futures.immediateFuture(null);
    }

    // Store the artifact, including any additional metadata.
    ListenableFuture<Void> storeFuture = artifactCache.store(ArtifactInfo.builder().setRuleKeys(ruleKeys)
            .setMetadata(buildMetadata).setBuildTimeMs(buildTimeMs).build(),
            BorrowablePath.borrowablePath(archive.get()));
    Futures.addCallback(storeFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            onCompletion();
        }

        @Override
        public void onFailure(Throwable t) {
            onCompletion();
            new ErrorLogger(new ErrorLogger.LogImpl() {
                @Override
                public void logUserVisible(String message) {
                }

                @Override
                public void logUserVisibleInternalError(String message) {
                }

                @Override
                public void logVerbose(Throwable e) {
                    LOG.debug(t, "When storing RuleKeys %s to the cache for %s.", ruleKeys, buildTarget);
                }
            }, new HumanReadableExceptionAugmentor(ImmutableMap.of())).logException(t);
        }

        private void onCompletion() {
            try {
                // The archive file may have been borrowed when storing to the cache so only close it
                // if
                // it still exists.
                if (Files.exists(archive.get())) {
                    archive.close();
                }
            } catch (IOException e) {
                new ErrorLogger(new ErrorLogger.LogImpl() {
                    @Override
                    public void logUserVisible(String message) {
                    }

                    @Override
                    public void logUserVisibleInternalError(String message) {
                    }

                    @Override
                    public void logVerbose(Throwable e) {
                        LOG.debug(e, "When deleting temporary archive %s for upload of %s.", archive.get(),
                                buildTarget);
                    }
                }, new HumanReadableExceptionAugmentor(ImmutableMap.of())).logException(e);
            }
        }
    });

    return storeFuture;
}

From source file:com.github.jarlakxen.embedphantomjs.executor.PhantomJSFileExecutor.java

public ListenableFuture<String> execute(final String fileContent, final String... args) {
    try {/* ww w.j a v a 2  s .  co  m*/
        final File tmp = File.createTempFile(RandomStringUtils.randomAlphabetic(10), ".js");
        FileUtils.write(tmp, fileContent);
        ListenableFuture<String> result = execute(tmp, args);

        Futures.addCallback(result, new FutureCallback<String>() {
            public void onSuccess(String explosion) {
                onComplete();
            }

            public void onFailure(Throwable thrown) {
                LOGGER.error("", thrown);
                onComplete();
            }

            public void onComplete() {
                if (tmp != null) {
                    tmp.delete();
                }
            }
        });

        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.javacrumbs.futureconverter.common.test.guava.GuavaConvertedFutureTestHelper.java

@Override
public void addCallbackTo(ListenableFuture<String> convertedFuture) {
    Futures.addCallback(convertedFuture, callback);
    convertedFuture.addListener(new Runnable() {
        @Override/*from  ww  w . j  a  v a  2  s .  c om*/
        public void run() {
            callbackCalled();
        }
    }, MoreExecutors.directExecutor());
}