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.basho.riak.client.core.netty.RiakResponseHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    // On any exception in the pipeline we explitly close the context here 
    // so the channel doesn't get reused by the ConnectionPool. 
    listener.onException(ctx.channel(), cause);
    ctx.close();/*from  w w  w .  ja v  a  2 s .c  o  m*/
}

From source file:com.basho.riak.client.core.netty.RiakSecurityDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext chc, ByteBuf in, List<Object> out) throws Exception {
    // Make sure we have 4 bytes
    if (in.readableBytes() >= 4) {
        in.markReaderIndex();//from  ww  w. j a  va2 s .com
        int length = in.readInt();

        // See if we have the full frame.
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
        } else {
            byte code = in.readByte();
            byte[] protobuf = new byte[length - 1];
            in.readBytes(protobuf);

            switch (state) {
            case TLS_WAIT:
                switch (code) {
                case RiakMessageCodes.MSG_StartTls:
                    logger.debug("Received MSG_RpbStartTls reply");
                    // change state
                    this.state = State.SSL_WAIT;
                    // insert SSLHandler
                    SslHandler sslHandler = new SslHandler(sslEngine);
                    // get promise
                    Future<Channel> hsFuture = sslHandler.handshakeFuture();
                    // register callback
                    hsFuture.addListener(new SslListener());
                    // Add handler
                    chc.channel().pipeline().addFirst(Constants.SSL_HANDLER, sslHandler);
                    break;
                case RiakMessageCodes.MSG_ErrorResp:
                    logger.debug("Received MSG_ErrorResp reply to startTls");
                    promise.tryFailure((riakErrorToException(protobuf)));
                    break;
                default:
                    promise.tryFailure(
                            new RiakResponseException(0, "Invalid return code during StartTLS; " + code));
                }
                break;
            case AUTH_WAIT:
                chc.channel().pipeline().remove(this);
                switch (code) {
                case RiakMessageCodes.MSG_AuthResp:
                    logger.debug("Received MSG_RpbAuthResp reply");
                    promise.trySuccess(null);
                    break;
                case RiakMessageCodes.MSG_ErrorResp:
                    logger.debug("Received MSG_ErrorResp reply to auth");
                    promise.tryFailure(riakErrorToException(protobuf));
                    break;
                default:
                    promise.tryFailure(
                            new RiakResponseException(0, "Invalid return code during Auth; " + code));
                }
                break;
            default:
                // WTF?
                logger.error("Received message while not in TLS_WAIT or AUTH_WAIT");
                promise.tryFailure(
                        new IllegalStateException("Received message while not in TLS_WAIT or AUTH_WAIT"));
            }
        }
    }
}

From source file:com.basho.riak.client.core.netty.RiakSecurityDecoder.java

License:Apache License

private void init(ChannelHandlerContext ctx) {
    state = State.TLS_WAIT;/*from   w ww  . jav a2s . com*/
    promise = new DefaultPromise<Void>(ctx.executor());
    promiseLatch.countDown();
    ctx.channel().writeAndFlush(new RiakMessage(RiakMessageCodes.MSG_StartTls, new byte[0]));

}

From source file:com.basho.riak.client.core.netty.RiakSecurityDecoder.java

License:Apache License

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    logger.debug("MyStartTlsDecoder Handler Added");
    if (ctx.channel().isActive()) {
        init(ctx);/*from  www .j a  va 2s  .  c o  m*/
    }
}

From source file:com.bloom.zerofs.rest.ConnectionStatsHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    logger.trace("Channel Active " + ctx.channel().remoteAddress());
    metrics.connectionsConnectedCount.inc();
    openConnections.incrementAndGet();//  ww  w  .  j av  a  2  s  .  co  m
    super.channelActive(ctx);
}

From source file:com.bloom.zerofs.rest.ConnectionStatsHandler.java

License:Open Source License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    logger.trace("Channel Inactive " + ctx.channel().remoteAddress());
    metrics.connectionsDisconnectedCount.inc();
    openConnections.decrementAndGet();//  w ww.j  a v a 2 s . com
    super.channelInactive(ctx);
}

From source file:com.bloom.zerofs.rest.HealthCheckHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
    logger.trace("Reading on channel {}", ctx.channel());
    boolean forwardObj = false;
    if (obj instanceof HttpRequest) {
        if (request == null && ((HttpRequest) obj).getUri().equals(healthCheckUri)) {
            nettyMetrics.healthCheckRequestRate.mark();
            startTimeInMs = System.currentTimeMillis();
            logger.trace("Handling health check request while in state " + restServerState.isServiceUp());
            request = (HttpRequest) obj;
            if (restServerState.isServiceUp()) {
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                        Unpooled.wrappedBuffer(GOOD));
                HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request));
                HttpHeaders.setContentLength(response, GOOD.length);
            } else {
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                        HttpResponseStatus.SERVICE_UNAVAILABLE, Unpooled.wrappedBuffer(BAD));
                HttpHeaders.setKeepAlive(response, false);
                HttpHeaders.setContentLength(response, BAD.length);
            }/*from   w  ww. j a v a2s  .co  m*/
            nettyMetrics.healthCheckRequestProcessingTimeInMs
                    .update(System.currentTimeMillis() - startTimeInMs);
        } else {
            // Rest server could be down even if not for health check request. We intentionally don't take any action in this
            // handler for such cases and leave it to the downstream handlers to handle it
            forwardObj = true;
        }
    }
    if (obj instanceof LastHttpContent) {
        if (response != null) {
            // response was created when we received the request with health check uri
            ChannelFuture future = ctx.writeAndFlush(response);
            if (!HttpHeaders.isKeepAlive(response)) {
                future.addListener(ChannelFutureListener.CLOSE);
            }
            request = null;
            response = null;
            nettyMetrics.healthCheckRequestRoundTripTimeInMs.update(System.currentTimeMillis() - startTimeInMs);
        } else {
            // request was not for health check uri
            forwardObj = true;
        }
    } else if (request == null) {
        // http Content which is not LastHttpContent is not intended for this handler
        forwardObj = true;
    }
    if (forwardObj) {
        super.channelRead(ctx, obj);
    } else {
        ReferenceCountUtil.release(obj);
    }
}

From source file:com.bloom.zerofs.rest.HealthCheckHandler.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (!restServerState.isServiceUp()) {
        if (msg instanceof LastHttpContent) {
            // Start closing client channels after we've completed writing to them (even if they are keep-alive)
            logger.info("Health check request handler closing connection " + ctx.channel()
                    + " since in shutdown mode.");
            promise.addListener(ChannelFutureListener.CLOSE);
            nettyMetrics.healthCheckHandlerChannelCloseOnWriteCount.inc();
        }/*  ww  w. j  a v a  2  s  .com*/
    }
    super.write(ctx, msg, promise);
}

From source file:com.bloom.zerofs.rest.PublicAccessLogHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
    logger.trace("Reading on channel {}", ctx.channel());
    long startTimeInMs = System.currentTimeMillis();
    if (obj instanceof HttpRequest) {
        nettyMetrics.publicAccessLogRequestRate.mark();
        if (request != null) {
            logDurations();/*from   w  ww  . ja  va  2 s .  c  om*/
            logMessage.append(" : Received request while another request in progress. Resetting log message.");
            logger.error(logMessage.toString());
        }
        reset();
        requestArrivalTimeInMs = System.currentTimeMillis();
        request = (HttpRequest) obj;
        logMessage.append(ctx.channel().remoteAddress()).append(" ");
        logMessage.append(request.getMethod().toString()).append(" ");
        logMessage.append(request.getUri()).append(", ");
        logHeaders("Request", request, publicAccessLogger.getRequestHeaders());
        logMessage.append(", ");
    } else if (obj instanceof LastHttpContent) {
        requestLastChunkArrivalTimeInMs = System.currentTimeMillis();
    } else if (!(obj instanceof HttpContent)) {
        logger.error("Receiving request (messageReceived) that is not of type HttpRequest or HttpContent. "
                + "Receiving request from " + ctx.channel().remoteAddress() + ". " + "Request is of type "
                + obj.getClass() + ". " + "No action being taken other than logging this unexpected state.");
    }
    nettyMetrics.publicAccessLogRequestProcessingTimeInMs.update(System.currentTimeMillis() - startTimeInMs);
    super.channelRead(ctx, obj);
}

From source file:com.bloom.zerofs.rest.PublicAccessLogHandler.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    long startTimeInMs = System.currentTimeMillis();
    boolean shouldReset = msg instanceof LastHttpContent;
    if (request != null) {
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;
            logHeaders("Response", response, publicAccessLogger.getResponseHeaders());
            logMessage.append(", ");
            logMessage.append("status=").append(response.getStatus().code());
            logMessage.append(", ");
            if (HttpHeaders.isTransferEncodingChunked(response)) {
                responseFirstChunkStartTimeInMs = System.currentTimeMillis();
            } else {
                shouldReset = true;//from  w  ww.j  av  a2 s. c  o m
            }
        } else if (!(msg instanceof HttpContent)) {
            logger.error(
                    "Sending response that is not of type HttpResponse or HttpContent. Sending response to "
                            + ctx.channel().remoteAddress() + ". Request is of type " + msg.getClass()
                            + ". No action being taken other than logging this unexpected state.");
        }
        if (shouldReset) {
            logDurations();
            publicAccessLogger.logInfo(logMessage.toString());
            reset();
        }
    }
    nettyMetrics.publicAccessLogResponseProcessingTimeInMs.update(System.currentTimeMillis() - startTimeInMs);
    super.write(ctx, msg, promise);
}