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.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//from   ww w .  j av a2 s  .  com
        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  ww  . j a v a2 s. co  m
 * 
 * @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.microsoft.office.integration.test.EventsAsyncTestCase.java

public void testRead() {
    prepareEvent();// ww  w .j  a  v  a2  s.  co  m
    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.hello.impl.HelloWorldImpl.java

private void initializeDataTree(DataBroker db) {
    LOG.info("Preparing to initialize the greeting registry");
    WriteTransaction transaction = db.newWriteOnlyTransaction();
    InstanceIdentifier<GreetingRegistry> iid = InstanceIdentifier.create(GreetingRegistry.class);
    GreetingRegistry greetingRegistry = new GreetingRegistryBuilder().build();
    transaction.put(LogicalDatastoreType.CONFIGURATION, iid, greetingRegistry);
    transaction.put(LogicalDatastoreType.OPERATIONAL, iid, greetingRegistry);
    CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
    Futures.addCallback(future, new LoggingFuturesCallBack<>("Failed to create greeting registry", LOG));
}

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 w  ww  .j a va 2  s .c o  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:eu.point.registry.impl.NodeConnectorRegistryUtils.java

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

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();// www  .ja v a  2s .co  m
    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:org.anhonesteffort.chnlzr.ChnlzrServer.java

@SuppressWarnings("unchecked")
private void run() throws InterruptedException {
    ListenableFuture sourceFuture = sourcePool.submit(source);
    Futures.addCallback(sourceFuture, criticalCallback);

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    try {/*from   w  w w.  j a v a2s  .co  m*/

        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, config.bufferHighWaterMark())
                .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, config.bufferLowWaterMark())
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast("idle state", new IdleStateHandler(0, 0,
                                config.idleStateThresholdMs(), TimeUnit.MILLISECONDS));
                        ch.pipeline().addLast("heartbeat", IdleStateHeartbeatWriter.INSTANCE);
                        ch.pipeline().addLast("encoder", BaseMessageEncoder.INSTANCE);
                        ch.pipeline().addLast("decoder", new BaseMessageDecoder());
                        ch.pipeline().addLast("handler",
                                new ServerHandler(config, resampling, sourceController));
                    }
                });

        ChannelFuture channelFuture = bootstrap.bind(config.serverPort()).sync();
        channelFuture.channel().closeFuture().sync();

    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        sourceFuture.cancel(true);
        sourcePool.shutdownNow();
    }

    System.exit(1);
}

From source file:io.v.android.apps.namespace_browser.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mBaseContext = V.init(this);
    String root = PreferenceManager.getDefaultSharedPreferences(this).getString(PREF_NAMESPACE_GLOB_ROOT,
            DEFAULT_NAMESPACE_GLOB_ROOT);
    View dirView = findViewById(R.id.directory);
    dirView.setPadding( // remove left padding for the root.
            0, dirView.getPaddingTop(), dirView.getPaddingRight(), dirView.getPaddingBottom());
    dirView.setTag(new GlobReply.Entry(new MountEntry(root, ImmutableList.<MountedServer>of(), true, false)));
    TextView nameView = (TextView) dirView.findViewById(R.id.name);
    nameView.setText("/");
    Drawable d = getResources().getDrawable(R.drawable.ic_account_box_black_36dp);
    d.setColorFilter(new LightingColorFilter(Color.BLACK, Color.GRAY));
    Futures.addCallback(BlessingsManager.getBlessings(mBaseContext, this, BLESSINGS_KEY, true),
            new FutureCallback<Blessings>() {
                @Override/*from  w  ww  . j a  v  a2s.  c  o m*/
                public void onSuccess(Blessings result) {
                    android.util.Log.i(TAG, "Success.");
                }

                @Override
                public void onFailure(Throwable t) {
                    android.util.Log.e(TAG, "Couldn't get blessings: " + t.getMessage());
                }
            });
}

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

public ESBulkIndexTask(ClusterService clusterService, Settings settings,
        TransportShardBulkActionDelegate transportShardBulkActionDelegate,
        TransportCreateIndexAction transportCreateIndexAction, ESIndexNode node) {
    this.node = node;
    this.bulkShardProcessor = new BulkShardProcessor(clusterService, settings, transportShardBulkActionDelegate,
            transportCreateIndexAction, node.partitionedTable(), true, this.node.sourceMaps().size());

    if (!node.isBulkRequest()) {
        final SettableFuture<RowCountResult> futureResult = SettableFuture.create();
        resultList = new ArrayList<>(1);
        resultList.add(futureResult);//from  ww w  .j  ava2s .co m

        Futures.addCallback(bulkShardProcessor.result(), new FutureCallback<BitSet>() {
            @Override
            public void onSuccess(@Nullable BitSet result) {
                if (result == null) {
                    futureResult.set(TaskResult.ROW_COUNT_UNKNOWN);
                } else {
                    futureResult.set(new RowCountResult(result.cardinality()));
                }
            }

            @Override
            public void onFailure(@Nonnull Throwable t) {
                futureResult.setException(t);
            }
        });
    } else {
        final int numResults = node.sourceMaps().size();
        resultList = new ArrayList<>(numResults);
        for (int i = 0; i < numResults; i++) {
            resultList.add(SettableFuture.<RowCountResult>create());
        }
        Futures.addCallback(bulkShardProcessor.result(), new FutureCallback<BitSet>() {
            @Override
            public void onSuccess(@Nullable BitSet result) {
                if (result == null) {
                    setAllToFailed(null);
                    return;
                }

                for (int i = 0; i < numResults; i++) {
                    SettableFuture<RowCountResult> future = (SettableFuture<RowCountResult>) resultList.get(i);
                    future.set(result.get(i) ? TaskResult.ONE_ROW : TaskResult.FAILURE);
                }
            }

            private void setAllToFailed(@Nullable Throwable throwable) {
                if (throwable == null) {
                    for (ListenableFuture<RowCountResult> future : resultList) {
                        ((SettableFuture<RowCountResult>) future).set(TaskResult.FAILURE);
                    }
                } else {
                    for (ListenableFuture<RowCountResult> future : resultList) {
                        ((SettableFuture<RowCountResult>) future).set(RowCountResult.error(throwable));
                    }
                }
            }

            @Override
            public void onFailure(@Nonnull Throwable t) {
                setAllToFailed(t);
            }
        });
    }
}