Example usage for io.netty.channel ChannelHandlerContext fireExceptionCaught

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

Introduction

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

Prototype

@Override
    ChannelHandlerContext fireExceptionCaught(Throwable cause);

Source Link

Usage

From source file:com.linkedin.r2.transport.http.client.Http2AlpnHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    LOG.error("Application level protocol negotiation failed", cause);
    _alpnPromise.setFailure(cause);//from   w  w  w  .  j a  va 2  s  .co m
    ctx.fireExceptionCaught(cause);
}

From source file:com.linkedin.r2.transport.http.client.Http2UpgradeHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    LOG.error("HTTP/2 clear text upgrade failed", cause);
    _upgradePromise.setFailure(cause);//www .j  a v  a 2  s  .  co  m
    ctx.fireExceptionCaught(cause);
}

From source file:com.linkedin.r2.transport.http.client.RAPResponseDecoder.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpResponse) {
        HttpResponse m = (HttpResponse) msg;
        _shouldCloseConnection = !HttpUtil.isKeepAlive(m);

        if (HttpUtil.is100ContinueExpected(m)) {
            ctx.writeAndFlush(CONTINUE).addListener(new ChannelFutureListener() {
                @Override//w w  w .j a va  2  s .  co m
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    }
                }
            });
        }
        if (!m.decoderResult().isSuccess()) {
            ctx.fireExceptionCaught(m.decoderResult().cause());
            return;
        }
        // remove chunked encoding.
        if (HttpUtil.isTransferEncodingChunked(m)) {
            HttpUtil.setTransferEncodingChunked(m, false);
        }

        Timeout<None> timeout = ctx.channel().attr(TIMEOUT_ATTR_KEY).getAndRemove();
        if (timeout == null) {
            LOG.debug("dropped a response after channel inactive or exception had happened.");
            return;
        }

        final TimeoutBufferedWriter writer = new TimeoutBufferedWriter(ctx, _maxContentLength,
                BUFFER_HIGH_WATER_MARK, BUFFER_LOW_WATER_MARK, timeout);
        EntityStream entityStream = EntityStreams.newEntityStream(writer);
        _chunkedMessageWriter = writer;
        StreamResponseBuilder builder = new StreamResponseBuilder();
        builder.setStatus(m.status().code());

        for (Map.Entry<String, String> e : m.headers()) {
            String key = e.getKey();
            String value = e.getValue();
            if (key.equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) {
                builder.addCookie(value);
            } else {
                builder.unsafeAddHeaderValue(key, value);
            }
        }

        ctx.fireChannelRead(builder.build(entityStream));
    } else if (msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        TimeoutBufferedWriter currentWriter = _chunkedMessageWriter;
        // Sanity check
        if (currentWriter == null) {
            throw new IllegalStateException("received " + HttpContent.class.getSimpleName() + " without "
                    + HttpResponse.class.getSimpleName());
        }

        if (!chunk.decoderResult().isSuccess()) {
            this.exceptionCaught(ctx, chunk.decoderResult().cause());
        }

        currentWriter.processHttpChunk(chunk);

        if (chunk instanceof LastHttpContent) {
            _chunkedMessageWriter = null;
            if (_shouldCloseConnection) {
                ctx.fireChannelRead(ChannelPoolStreamHandler.CHANNEL_DESTROY_SIGNAL);
            } else {
                ctx.fireChannelRead(ChannelPoolStreamHandler.CHANNEL_RELEASE_SIGNAL);
            }
        }
    } else {
        // something must be wrong, but let's proceed so that
        // handler after us has a chance to process it.
        ctx.fireChannelRead(msg);
    }
}

From source file:com.linkedin.r2.transport.http.client.RAPResponseDecoder.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    Timeout<None> timeout = ctx.channel().attr(TIMEOUT_ATTR_KEY).getAndRemove();
    if (timeout != null) {
        timeout.getItem();/* w w  w  .j  av a  2s .  c om*/
    }
    if (_chunkedMessageWriter != null) {
        _chunkedMessageWriter.fail(cause);
        _chunkedMessageWriter = null;
    }
    ctx.fireExceptionCaught(cause);
}

From source file:com.linkedin.r2.transport.http.client.RAPResponseHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    TransportCallback<RestResponse> callback = ctx.channel().attr(CALLBACK_ATTR_KEY).getAndRemove();
    if (callback != null) {
        LOG.debug(ctx.channel().remoteAddress() + ": exception on active channel", cause);
        callback.onResponse(TransportResponseImpl.<RestResponse>error(HttpNettyClient.toException(cause),
                Collections.<String, String>emptyMap()));
    } else {/*  w  ww .j  a  v  a2s .  co  m*/
        LOG.debug(ctx.channel().remoteAddress() + ": exception on idle channel", cause);
    }
    ctx.fireExceptionCaught(cause);
}

From source file:com.linkedin.r2.transport.http.client.RAPStreamResponseHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    TransportCallback<StreamResponse> callback = ctx.channel().attr(CALLBACK_ATTR_KEY).getAndRemove();
    if (callback != null) {
        LOG.debug(ctx.channel().remoteAddress() + ": exception on active channel", cause);
        callback.onResponse(TransportResponseImpl.<StreamResponse>error(
                HttpNettyStreamClient.toException(cause), Collections.<String, String>emptyMap()));
    } else {/*w w w  .  j  a va  2  s  .  c o m*/
        LOG.debug(ctx.channel().remoteAddress() + ": exception on potentially active channel", cause);
    }
    ctx.fireExceptionCaught(cause);
}

From source file:com.lubbo.core.network.netty.ChannelProcessor.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    logger.error("netty exception occur!remoteAddress=" + ctx.channel().remoteAddress(), cause);
    ctx.fireExceptionCaught(cause);
}

From source file:com.mastfrog.acteur.server.HttpObjectAggregator.java

License:Open Source License

@Override
protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
    FullHttpMessage currentMessage = this.currentMessage;

    if (msg instanceof HttpMessage) {
        tooLongFrameFound = false;/* www. j a v a  2 s .  c om*/
        assert currentMessage == null;

        HttpMessage m = (HttpMessage) msg;

        // Handle the 'Expect: 100-continue' header if necessary.
        // TODO: Respond with 413 Request Entity Too Large
        //   and discard the traffic or close the connection.
        //       No need to notify the upstream handlers - just log.
        //       If decoding a response, just throw an exception.
        if (is100ContinueExpected(m)) {
            ByteBuf buf = CONTINUE_LINE.duplicate();
            buf.retain();
            ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    }
                }
            });
        }

        if (!m.getDecoderResult().isSuccess()) {
            removeTransferEncodingChunked(m);
            out.add(toFullMessage(m));
            this.currentMessage = null;
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest header = (HttpRequest) msg;
            this.currentMessage = currentMessage = new DefaultFullHttpRequest(header.getProtocolVersion(),
                    header.getMethod(), header.getUri(),
                    Unpooled.compositeBuffer(maxCumulationBufferComponents));
        } else if (msg instanceof HttpResponse) {
            HttpResponse header = (HttpResponse) msg;
            this.currentMessage = currentMessage = new DefaultFullHttpResponse(header.getProtocolVersion(),
                    header.getStatus(), Unpooled.compositeBuffer(maxCumulationBufferComponents));
        } else {
            throw new Error();
        }

        currentMessage.headers().set(m.headers());

        // A streamed message - initialize the cumulative buffer, and wait for incoming chunks.
        removeTransferEncodingChunked(currentMessage);
    } else if (msg instanceof HttpContent) {
        if (tooLongFrameFound) {
            if (msg instanceof LastHttpContent) {
                this.currentMessage = null;
            }
            // already detect the too long frame so just discard the content
            return;
        }
        assert currentMessage != null;

        // Merge the received chunk into the content of the current message.
        HttpContent chunk = (HttpContent) msg;
        CompositeByteBuf content = (CompositeByteBuf) currentMessage.content();

        if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) {
            tooLongFrameFound = true;

            // release current message to prevent leaks
            currentMessage.release();
            this.currentMessage = null;

            throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes.");
        }

        // Append the content of the chunk
        if (chunk.content().isReadable()) {
            chunk.retain();
            content.addComponent(chunk.content());
            content.writerIndex(content.writerIndex() + chunk.content().readableBytes());
        }

        final boolean last;
        if (!chunk.getDecoderResult().isSuccess()) {
            currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
            last = true;
        } else {
            last = chunk instanceof LastHttpContent;
        }

        if (last) {
            this.currentMessage = null;

            // Merge trailing headers into the message.
            if (chunk instanceof LastHttpContent) {
                LastHttpContent trailer = (LastHttpContent) chunk;
                currentMessage.headers().add(trailer.trailingHeaders());
            }

            // Set the 'Content-Length' header.
            currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
                    String.valueOf(content.readableBytes()));

            // All done
            out.add(currentMessage);
        }
    } else {
        throw new Error();
    }
}

From source file:com.tesora.dve.db.mysql.portal.MSPCommandHandler.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof MSPMessage)) {
        ctx.fireChannelRead(msg); //not for us, maybe someone further in the stack can handle it.
        return;/*w ww .j  a va  2  s  .c  o  m*/
    }

    final SSConnection ssCon = ctx.channel().attr(ConnectionHandlerAdapter.SSCON_KEY).get();
    try {

        //we start the timer here, outside the submit/callable, so that we include any delay in submission/execution around the thread pool.
        final Timer frontendRequest = timingService.startSubTimer(TimingDesc.FRONTEND_ROUND_TRIP);

        final MSPMessage mspMessage = (MSPMessage) msg;
        final byte theMessageType = mspMessage.getMysqlMessageType();

        clientExecutorService.submit(new Callable<Void>() {
            public Void call() throws Exception {
                ssCon.executeInContext(new Callable<Void>() {
                    public Void call() {
                        //bind the frontend timer to this thread, so that new sub-timers on this thread (planning, backend, etc ) will be children of the frontend request timer.
                        timingService.attachTimerOnThread(frontendRequest);
                        try {
                            MSPAction mspAction = instanceExecutor[theMessageType];
                            //TODO:need to get load data to play nice, this special casing violates the MSPAction abstraction and the copy/regex runs for every statement, even though 'load data' is uncommon. -sgossard
                            if (mspMessage instanceof MSPComQueryRequestMessage
                                    && (isLoadDataStmt((MSPComQueryRequestMessage) mspMessage))) {
                                MSPComQueryRequestMessage queryMessage = (MSPComQueryRequestMessage) mspMessage;
                                executeLoadDataStatement(clientExecutorService, ctx, ssCon, queryMessage);
                            } else {
                                mspAction.execute(clientExecutorService, ctx, ssCon, mspMessage);
                            }
                        } catch (Throwable t) {
                            ctx.fireExceptionCaught(t);
                        } finally {
                            ReferenceCountUtil.release(mspMessage);//we processed the message, so we are responsible for cleaning it up.
                            frontendRequest.end();
                            timingService.detachTimerOnThread();
                        }
                        return null;
                    }
                });
                return null;
            }
        });
    } finally {
    }
}

From source file:com.yea.remote.netty.client.handle.LoginAuthClientHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.channel().close();/*from  www.ja va2s  .c o m*/
    ctx.close();
    ctx.fireExceptionCaught(cause);
}