Example usage for io.netty.channel ChannelPromise cancel

List of usage examples for io.netty.channel ChannelPromise cancel

Introduction

In this page you can find the example usage for io.netty.channel ChannelPromise cancel.

Prototype

@Override
boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

If the cancellation was successful it will fail the future with a CancellationException .

Usage

From source file:com.github.milenkovicm.kafka.KafkaTopic.java

License:Apache License

public Future<Void> send(ByteBuf key, int partitionId, ByteBuf message) {

    if (partitionId < 0 || partitionId >= this.partitions.length) {
        throw new RuntimeException("no such partition: " + partitionId);
    }/*from ww  w  .  j a va  2s.  c o  m*/

    AbstractKafkaBroker partition = this.partitions[partitionId];

    if (partition == null) {
        this.release(key, message);
        return this.getDefaultChannelPromise();
    }

    final Channel channel = partition.channel();
    final ChannelPromise channelPromise = this.getChannelPromise(channel);

    if (!channel.isWritable()) {
        if (backoffStrategy.handle(channel, key, message)) {
            channelPromise.cancel(true);
            return channelPromise;
        }
    }

    final ByteBuf messageSet = DataKafkaBroker.createMessageSet(allocator, key, partitionId, message);
    this.release(key, message);

    return channel.writeAndFlush(messageSet, channelPromise);
}

From source file:com.sucy.minenight.nms.PacketHandler.java

License:Open Source License

/**
 * Intercepts an outgoing packet/*ww w .j a v a  2s  .  c o m*/
 *
 * @param ctx     channel context
 * @param msg     packet being sent
 * @param promise sending promise
 *
 * @throws Exception
 */
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg.getClass().getSimpleName().startsWith("PacketPlayOutSpawnEntity")) {
        int id = (Integer) Reflection.getValue(msg, "a");
        NMSEntityBase entity = NMS.getManager().getEntity(id);
        if (entity != null) {
            LineData hologram = entity.getLine().getParent();
            if (!hologram.getVisibility().isVisibleTo(p)) {
                promise.cancel(true);
            }
        }
    }
    super.write(ctx, msg, promise);
}

From source file:com.twitter.http2.HttpStreamEncoder.java

License:Apache License

private ChannelPromise getMessageFuture(final ChannelHandlerContext ctx, final ChannelPromise promise,
        final int streamId, HttpMessage message) {
    if (message instanceof StreamedHttpMessage && !((StreamedHttpMessage) message).getContent().isClosed()) {
        final Pipe<HttpContent> pipe = ((StreamedHttpMessage) message).getContent();

        ChannelPromise writeFuture = ctx.channel().newPromise();
        writeFuture.addListener(new ChannelFutureListener() {
            @Override//  w  w  w .  j  a v a  2s.  c  om
            public void operationComplete(ChannelFuture future) throws Exception {
                // Channel's thread
                // First frame has been written

                if (future.isSuccess()) {
                    pipe.receive().addListener(new ChunkListener(ctx, streamId, pipe, promise));
                } else if (future.isCancelled()) {
                    pipe.close();
                    promise.cancel(true);
                } else {
                    pipe.close();
                    promise.setFailure(future.cause());
                }
            }
        });

        return writeFuture;
    } else {
        return promise;
    }
}

From source file:io.lettuce.core.protocol.ReconnectionHandler.java

License:Apache License

private void reconnect0(CompletableFuture<Channel> result, SocketAddress remoteAddress) {

    ChannelFuture connectFuture = bootstrap.connect(remoteAddress);
    ChannelPromise initFuture = connectFuture.channel().newPromise();

    logger.debug("Reconnecting to Redis at {}", remoteAddress);

    result.whenComplete((c, t) -> {// w w  w . j a  v a2  s.  co m

        if (t instanceof CancellationException) {
            connectFuture.cancel(true);
            initFuture.cancel(true);
        }
    });

    initFuture.addListener((ChannelFuture it) -> {

        if (it.cause() != null) {

            connectFuture.cancel(true);
            close(it.channel());
            result.completeExceptionally(it.cause());
        } else {
            result.complete(connectFuture.channel());
        }
    });

    connectFuture.addListener((ChannelFuture it) -> {

        if (it.cause() != null) {

            initFuture.tryFailure(it.cause());
            return;
        }

        ChannelPipeline pipeline = it.channel().pipeline();
        RedisChannelInitializer channelInitializer = pipeline.get(RedisChannelInitializer.class);

        if (channelInitializer == null) {

            initFuture.tryFailure(new IllegalStateException(
                    "Reconnection attempt without a RedisChannelInitializer in the channel pipeline"));
            return;
        }

        channelInitializer.channelInitialized().whenComplete((state, throwable) -> {

            if (throwable != null) {

                if (isExecutionException(throwable)) {
                    initFuture.tryFailure(throwable);
                    return;
                }

                if (clientOptions.isCancelCommandsOnReconnectFailure()) {
                    connectionFacade.reset();
                }

                if (clientOptions.isSuspendReconnectOnProtocolFailure()) {

                    logger.error("Disabling autoReconnect due to initialization failure", throwable);
                    setReconnectSuspended(true);
                }

                initFuture.tryFailure(throwable);

                return;
            }

            if (logger.isDebugEnabled()) {
                logger.info("Reconnected to {}, Channel {}", remoteAddress,
                        ChannelLogDescriptor.logDescriptor(it.channel()));
            } else {
                logger.info("Reconnected to {}", remoteAddress);
            }

            initFuture.trySuccess();
        });
    });

    Runnable timeoutAction = () -> {
        initFuture.tryFailure(new TimeoutException(
                String.format("Reconnection attempt exceeded timeout of %d %s ", timeout, timeoutUnit)));
    };

    Timeout timeoutHandle = timer.newTimeout(it -> {

        if (connectFuture.isDone() && initFuture.isDone()) {
            return;
        }

        if (reconnectWorkers.isShutdown()) {
            timeoutAction.run();
            return;
        }

        reconnectWorkers.submit(timeoutAction);

    }, this.timeout, timeoutUnit);

    initFuture.addListener(it -> timeoutHandle.cancel());
}