Example usage for io.netty.channel ChannelHandlerContext executor

List of usage examples for io.netty.channel ChannelHandlerContext executor

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext executor.

Prototype

EventExecutor executor();

Source Link

Document

Returns the EventExecutor which is used to execute an arbitrary task.

Usage

From source file:io.airlift.drift.transport.netty.ThriftClientHandler.java

License:Apache License

private void sendMessage(ChannelHandlerContext context, ThriftRequest thriftRequest, ChannelPromise promise)
        throws Exception {
    // todo ONEWAY_SEQUENCE_ID is a header protocol thing... make sure this works with framed and unframed
    int sequenceId = thriftRequest.isOneway() ? ONEWAY_SEQUENCE_ID : this.sequenceId.incrementAndGet();
    RequestHandler requestHandler = new RequestHandler(thriftRequest, sequenceId);

    // register timeout
    requestHandler.registerRequestTimeout(context.executor());

    // write request
    ByteBuf requestBuffer = requestHandler.encodeRequest(context.alloc());

    // register request if we are expecting a response
    if (!thriftRequest.isOneway()) {
        if (pendingRequests.putIfAbsent(sequenceId, requestHandler) != null) {
            requestHandler.onChannelError(
                    new TTransportException("Another request with the same sequenceId is already in progress"));
        }/*from  w  ww  .  j a  v a  2 s  .c  om*/
    }

    try {
        ChannelFuture sendFuture = context.write(requestBuffer, promise);
        sendFuture.addListener(future -> messageSent(context, sendFuture, requestHandler));
    } catch (Throwable t) {
        onError(context, t);
    }
}

From source file:io.aos.netty5.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final SocksRequest message) throws Exception {
    if (message instanceof Socks4CmdRequest) {
        final Socks4CmdRequest request = (Socks4CmdRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new GenericFutureListener<Future<Channel>>() {
            @Override//from  w  ww. j  a  va  2  s.co m
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.SUCCESS))
                            .addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(ChannelFuture channelFuture) {
                                    ctx.pipeline().remove(SocksServerConnectHandler.this);
                                    outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                    ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                                }
                            });
                } else {
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CmdRequest) {
        final Socks5CmdRequest request = (Socks5CmdRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new GenericFutureListener<Future<Channel>>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ctx.channel()
                            .writeAndFlush(
                                    new Socks5CmdResponse(Socks5CmdStatus.SUCCESS, request.addressType()))
                            .addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(ChannelFuture channelFuture) {
                                    ctx.pipeline().remove(SocksServerConnectHandler.this);
                                    outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                    ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                                }
                            });
                } else {
                    ctx.channel().writeAndFlush(
                            new Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:io.codis.nedis.handler.RedisDuplexHandler.java

License:Apache License

private void scheduleTimeoutTask(ChannelHandlerContext ctx) {
    if (timeoutNs > 0 && timeoutTask == null) {
        timeoutTask = ctx.executor().schedule(new TimeoutTask(ctx), timeoutNs, TimeUnit.NANOSECONDS);
    }//from ww  w  .  j  a  v a2  s.c  o  m
}

From source file:io.grpc.alts.internal.TsiFrameHandler.java

License:Apache License

@Override
@SuppressWarnings("FutureReturnValueIgnored") // for aggregatePromise.doneAllocatingPromises
public void flush(final ChannelHandlerContext ctx) throws GeneralSecurityException {
    if (pendingUnprotectedWrites == null || pendingUnprotectedWrites.isEmpty()) {
        // Return early if there's nothing to write. Otherwise protector.protectFlush() below may
        // not check for "no-data" and go on writing the 0-byte "data" to the socket with the
        // protection framing.
        return;/* www . j  a v a 2  s.  co  m*/
    }
    // Flushes can happen after close, but only when there are no pending writes.
    checkState(protector != null, "flush() called after close()");
    final ProtectedPromise aggregatePromise = new ProtectedPromise(ctx.channel(), ctx.executor(),
            pendingUnprotectedWrites.size());
    List<ByteBuf> bufs = new ArrayList<>(pendingUnprotectedWrites.size());

    // Drain the unprotected writes.
    while (!pendingUnprotectedWrites.isEmpty()) {
        ByteBuf in = (ByteBuf) pendingUnprotectedWrites.current();
        bufs.add(in.retain());
        // Remove and release the buffer and add its promise to the aggregate.
        aggregatePromise.addUnprotectedPromise(pendingUnprotectedWrites.remove());
    }

    final class ProtectedFrameWriteFlusher implements Consumer<ByteBuf> {

        @Override
        public void accept(ByteBuf byteBuf) {
            ctx.writeAndFlush(byteBuf, aggregatePromise.newPromise());
        }
    }

    protector.protectFlush(bufs, new ProtectedFrameWriteFlusher(), ctx.alloc());
    // We're done writing, start the flow of promise events.
    aggregatePromise.doneAllocatingPromises();
}

From source file:io.grpc.netty.MaxConnectionIdleManager.java

License:Apache License

/** A {@link NettyServerHandler} was added to the transport. */
void start(ChannelHandlerContext ctx) {
    start(ctx, ctx.executor());
}

From source file:io.grpc.netty.NettyHandlerTestBase.java

License:Apache License

protected final ChannelHandlerContext newMockContext() {
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    EventLoop eventLoop = mock(EventLoop.class);
    when(ctx.executor()).thenReturn(eventLoop);
    when(ctx.channel()).thenReturn(channel);
    return ctx;//  w  ww . j  av a  2s . com
}

From source file:io.grpc.netty.NettyServerHandler.java

License:Apache License

@Override
public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
    serverWriteQueue = new WriteQueue(ctx.channel());

    // init max connection age monitor
    if (maxConnectionAgeInNanos != MAX_CONNECTION_AGE_NANOS_DISABLED) {
        maxConnectionAgeMonitor = ctx.executor().schedule(new LogExceptionRunnable(new Runnable() {
            @Override//from w w  w  . ja v a 2  s  .c o m
            public void run() {
                if (gracefulShutdown == null) {
                    gracefulShutdown = new GracefulShutdown("max_age", maxConnectionAgeGraceInNanos);
                    gracefulShutdown.start(ctx);
                    ctx.flush();
                }
            }
        }), maxConnectionAgeInNanos, TimeUnit.NANOSECONDS);
    }

    if (maxConnectionIdleManager != null) {
        maxConnectionIdleManager.start(ctx);
    }

    if (keepAliveTimeInNanos != SERVER_KEEPALIVE_TIME_NANOS_DISABLED) {
        keepAliveManager = new KeepAliveManager(new KeepAlivePinger(ctx), ctx.executor(), keepAliveTimeInNanos,
                keepAliveTimeoutInNanos, true /* keepAliveDuringTransportIdle */);
        keepAliveManager.onTransportStarted();
    }

    if (transportTracer != null) {
        assert encoder().connection().equals(decoder().connection());
        final Http2Connection connection = encoder().connection();
        transportTracer.setFlowControlWindowReader(new TransportTracer.FlowControlReader() {
            private final Http2FlowController local = connection.local().flowController();
            private final Http2FlowController remote = connection.remote().flowController();

            @Override
            public TransportTracer.FlowControlWindows read() {
                assert ctx.executor().inEventLoop();
                return new TransportTracer.FlowControlWindows(local.windowSize(connection.connectionStream()),
                        remote.windowSize(connection.connectionStream()));
            }
        });
    }

    super.handlerAdded(ctx);
}

From source file:io.hekate.network.netty.NettyServerClient.java

License:Apache License

private void write(Object msg, NetworkSendCallback<Object> onSend, ChannelHandlerContext localCtx) {
    if (!validateMessageType(msg, onSend)) {
        return;//from   w  ww. j  av a  2  s  .com
    }

    if (debug) {
        log.debug("Sending to client [to={}, message={}]", address(), msg);
    }

    if (metrics != null) {
        metrics.onMessageEnqueue();
    }

    Channel channel = localCtx.channel();

    // Prepare deferred message.
    DeferredMessage deferredMsg;

    boolean failed = false;

    // Maybe pre-encode message.
    if (codec.isStateful()) {
        deferredMsg = new DeferredMessage(msg, channel);
    } else {
        if (trace) {
            log.trace("Pre-encoding message [to={}, message={}]", address(), msg);
        }

        try {
            ByteBuf buf = NetworkProtocolCodec.preEncode(msg, codec, localCtx.alloc());

            deferredMsg = new DeferredEncodedMessage(buf, msg, channel);
        } catch (CodecException e) {
            deferredMsg = fail(msg, channel, e);

            failed = true;
        }
    }

    deferredMsg.addListener(result -> {
        if (metrics != null) {
            metrics.onMessageDequeue();
        }

        if (result.isSuccess()) {
            // Successful operation.
            if (debug) {
                log.debug("Done sending to client [to={}, message={}]", address(), msg);
            }

            if (metrics != null) {
                metrics.onMessageSent();
            }
        } else {
            // Failed operation.
            if (debug) {
                log.debug("Failed to send to client [to={}, message={}]", address(), msg, result.cause());
            }

            // Notify channel pipeline on error (ignore if channel is already closed).
            if (channel.isOpen()) {
                channel.pipeline().fireExceptionCaught(result.cause());
            }
        }

        // Notify user callback.
        if (onSend != null) {
            try {
                Throwable mayBeError = NettyErrorUtils.unwrap(result.cause());

                onSend.onComplete(msg, mayBeError);
            } catch (Throwable t) {
                if (log.isErrorEnabled()) {
                    log.error("Failed to notify network message callback [message={}]", msg, t);
                }
            }
        }
    });

    // Enqueue write operation.
    if (!failed) {
        writeQueue.enqueue(deferredMsg, localCtx.executor());
    }
}

From source file:io.moquette.server.netty.AutoFlushHandler.java

License:Open Source License

private void initialize(ChannelHandlerContext ctx) {
    // Avoid the case where destroy() is called before scheduling timeouts.
    // See: https://github.com/netty/netty/issues/143
    switch (state) {
    case 1://  w  w w  .ja  va2 s  .c  o  m
    case 2:
        return;
    }

    state = 1;

    EventExecutor loop = ctx.executor();

    lastWriteTime = System.nanoTime();
    writerIdleTimeout = loop.schedule(new WriterIdleTimeoutTask(ctx), writerIdleTimeNanos,
            TimeUnit.NANOSECONDS);
}

From source file:io.netty.example.http2.tiles.Http1RequestHandler.java

License:Apache License

@Override
protected void sendResponse(final ChannelHandlerContext ctx, String streamId, int latency,
        final FullHttpResponse response, final FullHttpRequest request) {
    HttpUtil.setContentLength(response, response.content().readableBytes());
    ctx.executor().schedule(new Runnable() {
        @Override//from   w w w .ja v  a 2 s . com
        public void run() {
            if (isKeepAlive(request)) {
                if (request.protocolVersion().equals(HTTP_1_0)) {
                    response.headers().set(CONNECTION, KEEP_ALIVE);
                }
                ctx.writeAndFlush(response);
            } else {
                // Tell the client we're going to close the connection.
                response.headers().set(CONNECTION, CLOSE);
                ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }, latency, TimeUnit.MILLISECONDS);
}