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:io.crate.operation.join.CollectingPageableTaskIterable.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 a  v  a 2 s  .c o  m*/
        public void onSuccess(@Nullable PageableTaskResult result) {
            if (result == null) {
                future.setException(new IllegalArgumentException("PageableTaskResult is null"));
            } else {
                pages.add(result.page());
                future.set(null);
            }
        }

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

From source file:org.opendaylight.bier.driver.common.util.DataWriter.java

public static <T extends DataObject> CheckedFuture<Void, TransactionCommitFailedException> operate(
        OperateType type, DataBroker dataBroker, final int tries, InstanceIdentifier<T> path, T data) {

    final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
    switch (type) {
    case CREATE:/*from ww w. j a v  a 2  s  .  co m*/
    case REPLACE:
        writeTransaction.put(LogicalDatastoreType.CONFIGURATION, path, data, true);
        break;
    case MERGE:
        writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, path, data, true);
        break;
    case DELETE:
        writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, path);
        break;
    default:
        break;

    }

    final CheckedFuture<Void, TransactionCommitFailedException> submitResult = writeTransaction.submit();
    Futures.addCallback(submitResult, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
        }

        @Override
        public void onFailure(final Throwable throwable) {
            operateFail(throwable, type, dataBroker, path, data, tries);
        }
    });

    return submitResult;

}

From source file:org.apache.pulsar.connect.cassandra.CassandraSink.java

@Override
public CompletableFuture<Void> write(Message<KeyValue<K, V>> tuple) {
    BoundStatement bound = statement.bind(tuple.getData().getKey(), tuple.getData().getValue());
    ResultSetFuture future = session.executeAsync(bound);
    CompletableFuture<Void> completable = new CompletableFuture<Void>();
    Futures.addCallback(future, new FutureCallback<ResultSet>() {
        @Override/* w w  w.  j av  a2  s . c  o  m*/
        public void onSuccess(ResultSet result) {
            completable.complete(null);
        }

        @Override
        public void onFailure(Throwable t) {
            completable.completeExceptionally(t);
        }
    });
    return completable;
}

From source file:com.microsoft.assetmanagement.files.SharepointListsClientWithFiles.java

/**
 * Gets the file.//from w w w.ja  v  a2s. com
 * 
 * @param listName
 *            the list name
 * @param itemId
 *            the item id
 * @param fileClient
 *            the file Client
 * @return the file
 */
public ListenableFuture<DocumentLibraryItem> getFileFromDocumentLibrary(final String listName,
        final String itemId, final FileClient fileClient) {

    final SettableFuture<DocumentLibraryItem> result = SettableFuture.create();
    ListenableFuture<SPFile> picture = getSPFileFromPictureLibrary(listName, itemId);

    Futures.addCallback(picture, new FutureCallback<SPFile>() {
        @Override
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(SPFile spFile) {
            // TODO:Review if we can use chaining.
            ListenableFuture<byte[]> file = fileClient.getFile(spFile.getData("Name").toString(), listName);
            Futures.addCallback(file, new FutureCallback<byte[]>() {
                @Override
                public void onFailure(Throwable t) {
                    result.setException(t);
                };

                @Override
                public void onSuccess(byte[] payload) {
                    result.set(new DocumentLibraryItem(payload, itemId));
                }
            });
        }
    });

    return result;
}

From source file:com.example.suharshs.vango.RunKeyActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_run_key);

    Intent intent = getIntent();/*from  ww  w  .j  a  v  a 2s  . c o m*/
    final String key = intent.getStringExtra(MainActivity.EXTRA_KEY);

    TextView textView = (TextView) findViewById(R.id.text_run_key_status);
    textView.setText(String.format("Running go function keyed by '%s'", key));

    mOutput = (TextView) findViewById(R.id.text_run_key_output);

    if (savedInstanceState != null) {
        mLines = (String[]) savedInstanceState.getCharSequenceArray(OUTPUT_DATA);
        mNextLine = savedInstanceState.getInt(OUTPUT_NEXT);
        write(null); // force a redraw of the output TextView.
        if (savedInstanceState.getBoolean(STARTED)) {
            return;
        }
    }

    final VContext ctx = V.init(this,
            new Options().set(OptionDefs.LOG_VLEVEL, 0).set(OptionDefs.LOG_VMODULE, "*=0"));
    try {
        mRemoteInspectors = new RemoteInspectors(ctx);
    } catch (VException e) {
        Log.e(TAG, "Failed to enable remote inspection: " + e.toString());
    }
    synchronized (this) {
        mLines = new String[10];
        mNextLine = 0;
    }
    Futures.addCallback(BlessingsManager.getBlessings(ctx, this, BLESSINGS_KEY, true),
            new FutureCallback<Blessings>() {
                @Override
                public void onSuccess(Blessings b) {
                    Log.v(TAG, "Received blessings " + b.toString());
                    AsyncTask.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                (new Vango()).run(ctx, key, RunKeyActivity.this);
                            } catch (Exception e) {
                                write(e.toString());
                            }
                        }
                    });
                }

                @Override
                public void onFailure(Throwable t) {
                    Log.d(TAG, "Failed to get blessings", t);
                }
            });
}

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(// w w w. j a  va  2s.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.acme.callbacks.advanced.AddBridgeOnHiveMQStart.java

/**
 * This method is called from HiveMQ, and the custom behaviour has to be implemented in here.
 * If some preconditions are not met to successfully operate, a {@link com.dcsquare.hivemq.spi.callback.exception.BrokerUnableToStartException}
 * should be thrown.//from  ww  w. j  av  a2s. co  m
 *
 * @throws com.dcsquare.hivemq.spi.callback.exception.BrokerUnableToStartException If the exception is thrown, HiveMQ will be stopped.
 */
@Override
public void onBrokerStart() throws BrokerUnableToStartException {
    log.info("Adding Bridge to MQTT Dashboard");
    final Bridge bridge = createBridge();

    // Start bridge with Bridge Manager Service dynamically
    final ListenableFuture<Void> future = bridgeManagerService.startBridge(bridge);

    Futures.addCallback(future, new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            log.info("Bridge started successfully");
        }

        @Override
        public void onFailure(Throwable t) {
            log.info("Bridge failed to start");
        }
    });

}

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

public void testRead() {
    prepareEvent();//from   w w  w .j  a  v a2s  .c  om
    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 {
                readAndCheck();
                removeEvent();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });

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

From source file:org.opendaylight.openflowplugin.impl.connection.listener.HandshakeListenerImpl.java

@Override
public void onHandshakeSuccessfull(GetFeaturesOutput featureOutput, Short version) {
    LOG.debug("handshake succeeded: {}", connectionContext.getConnectionAdapter().getRemoteAddress());
    closeHandshakeContext();//  ww  w. j a v  a  2 s.c  om
    connectionContext.changeStateToWorking();
    connectionContext.setFeatures(featureOutput);
    connectionContext.setNodeId(InventoryDataServiceUtil.nodeIdFromDatapathId(featureOutput.getDatapathId()));

    // fire barrier in order to sweep all handshake and posthandshake messages before continue
    final ListenableFuture<RpcResult<BarrierOutput>> barrier = fireBarrier(version, 0L);
    Futures.addCallback(barrier, new FutureCallback<RpcResult<BarrierOutput>>() {
        @Override
        public void onSuccess(@Nullable final RpcResult<BarrierOutput> result) {
            LOG.debug("succeeded by getting sweep barrier after posthandshake for device {}",
                    connectionContext.getNodeId());
            try {
                deviceConnectedHandler.deviceConnected(connectionContext);
                SessionStatistics.countEvent(connectionContext.getNodeId().toString(),
                        SessionStatistics.ConnectionStatus.CONNECTION_CREATED);
            } catch (Exception e) {
                LOG.info("ConnectionContext initial processing failed: {}", e.getMessage());
                SessionStatistics.countEvent(connectionContext.getNodeId().toString(),
                        SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_OFP);
                connectionContext.closeConnection(false);
            }
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.info("failed to get sweep barrier after posthandshake for device {}",
                    connectionContext.getNodeId());
            connectionContext.closeConnection(false);
        }
    });
}

From source file:io.airlift.http.server.AsyncResponseHandler.java

private static <T> FutureCallback<T> toFutureCallback(final AsyncResponse asyncResponse) {
    return new FutureCallback<T>() {
        @Override//w  w  w .jav a 2 s  . c  om
        public void onSuccess(T value) {
            checkArgument(!(value instanceof Response.ResponseBuilder),
                    "Value is a ResponseBuilder. Did you forget to call build?");
            asyncResponse.resume(value);
        }

        @Override
        public void onFailure(Throwable t) {
            asyncResponse.resume(t);
        }
    };
}