Example usage for io.netty.channel ChannelHandlerContext channel

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

Introduction

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

Prototype

Channel channel();

Source Link

Document

Return the Channel which is bound to the ChannelHandlerContext .

Usage

From source file:com.ebay.jetstream.messaging.transport.netty.serializer.NettyObjectEncoder.java

License:MIT License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

    Attribute<Boolean> attr = ctx.channel().attr(EventProducer.m_kskey);

    Boolean enableKryo = attr.get();

    if ((enableKryo != null) && (enableKryo == true))
        ctx.write(msg, promise);//from w w  w .  j  av  a 2s .  c  om
    else
        super.write(ctx, msg, promise);

}

From source file:com.eightkdata.mongowp.mongoserver.decoder.BaseMessageDecoder.java

License:Open Source License

/**
 * Method that constructs a RequestBaseMessage object based on a correctly-positioned ByteBuf.
 * This method modifies the internal state of the ByteBuf.
 * It expects the ByteBuf to be positioned just before the start of the requestId field.
 * After running, the method will leave the ByteBuf positioned just after the responseTo field,
 * i.e., just before reading the opCode.
 *
 * @param channelHandlerContext//  w  ww  . j a va2s.  c  om
 * @param byteBuf
 * @return
 */
public static RequestBaseMessage decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) {
    InetSocketAddress socketAddress = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();

    return new RequestBaseMessage(socketAddress.getAddress(), socketAddress.getPort(), byteBuf.readInt());
}

From source file:com.eightkdata.mongowp.server.wp.RequestMessageObjectHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    try {// w  w  w .  ja  va 2s  .  co m
        LOGGER.info("Connection established from " + ctx.channel().remoteAddress());
    } catch (Exception e) {
        LOGGER.debug("Exception raised while logging connection", e);
    }

    requestProcessor.onChannelActive(ctx);

    super.channelActive(ctx);
}

From source file:com.eightkdata.mongowp.server.wp.RequestMessageObjectHandler.java

License:Open Source License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    try {//from ww w .j  av a  2 s .  co  m
        LOGGER.info("Connection finished from " + ctx.channel().remoteAddress());
    } catch (Exception e) {
        LOGGER.debug("Exception raised while logging disconnection", e);
    }

    super.channelInactive(ctx);

    requestProcessor.onChannelInactive(ctx);
}

From source file:com.emin.igwmp.skm.core.netty.handler.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override/*  w  w  w.  j  av  a  2 s.  co m*/
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.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 DefaultSocks4CommandResponse(Socks4CommandStatus.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.dstAddr(), request.dstPort()).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 DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS,
                                    request.dstAddrType(), request.dstAddr(), request.dstPort()));

                    responseFuture.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 DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    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.dstAddr(), request.dstPort()).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 DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.emin.igwmp.skm.core.netty.handler.SocksServerHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    super.channelInactive(ctx);
    LogUtils.I(":" + ctx.channel().remoteAddress() + "  :" + ctx.name());
}

From source file:com.emin.igwmp.skm.core.netty.handler.SocksServerHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);
    try {//w  ww  . j ava  2 s.c om
        LogUtils.I(":" + ctx.channel().remoteAddress() + "  :" + ctx.name());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.emin.igwmp.skm.core.netty.handler.SocksServerHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleStateEvent event = (IdleStateEvent) evt;
        if (event.state().equals(IdleState.READER_IDLE)) {
            ///*from   w w  w .ja  va  2 s.c o m*/
        } else if (event.state().equals(IdleState.WRITER_IDLE)) {
            //
        } else if (event.state().equals(IdleState.ALL_IDLE)) {
            // ??
            String heart = Convert.Encode(new AssembleHeart().Assemble("", null));
            ctx.channel().writeAndFlush(heart);
        }
    }
    super.userEventTriggered(ctx, evt);
}

From source file:com.emin.igwmp.skm.core.netty.handler.SocksServerHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {

    throwable.printStackTrace();//from   w ww .  j  av  a  2  s  .co  m
    SocksServerUtils.closeOnFlush(ctx.channel());
}

From source file:com.eucalyptus.util.async.AsyncRequestHandler.java

License:Open Source License

private void messageReceived(final ChannelHandlerContext ctx, final Object message) {
    try {//w  w w .  j  av a 2 s.  c  o m
        if (message instanceof IoMessage) {
            final IoMessage response = (IoMessage) message;
            try {
                final R msg = (R) response.getMessage();
                if (!msg.get_return(true)) {
                    this.teardown(new FailedRequestException("Cluster response includes _return=false", msg));
                } else {
                    logMessage(response);
                    this.response.set(msg);
                    if (HttpHeaders.isKeepAlive(((IoMessage) message).getHttpMessage())) {
                        releaseChannel(ctx.channel());
                    } else {
                        closeAndReleaseChannel(ctx.channel());
                    }
                }
            } catch (final Exception e1) {
                LOG.error(e1, e1);
                this.teardown(e1);
            }
        } else if (message == null) {
            final NoResponseException ex = new NoResponseException("Channel received a null response.",
                    this.request.get());
            LOG.error(ex, ex);
            this.teardown(ex);
        } else {
            final UnknownMessageTypeException ex = new UnknownMessageTypeException(
                    "Channel received a unknown response type: " + message.getClass().getCanonicalName(),
                    this.request.get(), message);
            LOG.error(ex, ex);
            this.teardown(ex);
        }
    } catch (final Exception t) {
        LOG.error(t, t);
        this.teardown(t);
    } finally {
        if (message instanceof IoMessage) {
            ((IoMessage) message).getHttpMessage().release();
        }
    }
}