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.yea.remote.netty.server.handle.LoginAuthServerHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    nodeCheck.remove(ctx.channel().remoteAddress().toString());// 
    ctx.close();//  www  .  ja  v  a  2s  .  co  m
    ctx.fireExceptionCaught(cause);
}

From source file:com.zz.learning.netty5.chap12.server.LoginAuthRespHandler.java

License:Apache License

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();/*from   w  ww. j ava2  s  .co m*/
    nodeCheck.remove(ctx.channel().remoteAddress().toString());// 
    clientChannels.remove(ctx.channel().remoteAddress().toString());
    ctx.close();
    ctx.fireExceptionCaught(cause);
}

From source file:de.jackwhite20.cascade.shared.pipeline.handler.PacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {

    int length = byteBuf.readInt();

    // Allow packets with no data
    if (length > 0) {
        byte id = byteBuf.readByte();

        try {/*  w w  w  .j  a  v  a 2  s. c o  m*/
            Packet packet = protocol.create(id);
            packet.read(byteBuf);

            out.add(packet);
        } catch (IllegalStateException e) {
            ctx.fireExceptionCaught(e);
        }
    }
}

From source file:de.jackwhite20.cascade.shared.pipeline.handler.PacketEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, Packet packet, List<Object> out) throws Exception {

    try {/*from w w w  .j  a  va 2s.com*/
        byte id = protocol.findId(packet.getClass());

        ByteBuf byteBuf = ctx.alloc().buffer();
        byteBuf.writeByte(id);
        packet.write(byteBuf);

        out.add(byteBuf);
    } catch (IllegalStateException e) {
        ctx.fireExceptionCaught(e);
    }
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (ignoreException(cause)) {
        // It is safe to ignore the 'connection reset by peer' or
        // 'broken pipe' error after sending close_notify.
        if (logger.isDebugEnabled()) {
            logger.debug("Swallowing a harmless 'connection reset by peer / broken pipe' error that occurred "
                    + "while writing close_notify in response to the peer's close_notify", cause);
        }/*from w  w  w  .  j  a va  2s  .c o m*/

        // Close the connection explicitly just in case the transport
        // did not close the connection automatically.
        if (ctx.channel().isActive()) {
            ctx.close();
        }
    } else {
        ctx.fireExceptionCaught(cause);
    }
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws SSLException {

    final int startOffset = in.readerIndex();
    final int endOffset = in.writerIndex();
    int offset = startOffset;
    int totalLength = 0;

    // If we calculated the length of the current SSL record before, use that information.
    if (packetLength > 0) {
        if (endOffset - startOffset < packetLength) {
            return;
        } else {/*from  w  w  w . j  a v a2 s  .c o  m*/
            offset += packetLength;
            totalLength = packetLength;
            packetLength = 0;
        }
    }

    boolean nonSslRecord = false;

    while (totalLength < OpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) {
        final int readableBytes = endOffset - offset;
        if (readableBytes < 5) {
            break;
        }

        final int packetLength = getEncryptedPacketLength(in, offset);
        if (packetLength == -1) {
            nonSslRecord = true;
            break;
        }

        assert packetLength > 0;

        if (packetLength > readableBytes) {
            // wait until the whole packet can be read
            this.packetLength = packetLength;
            break;
        }

        int newTotalLength = totalLength + packetLength;
        if (newTotalLength > OpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) {
            // Don't read too much.
            break;
        }

        // We have a whole packet.
        // Increment the offset to handle the next packet.
        offset += packetLength;
        totalLength = newTotalLength;
    }

    if (totalLength > 0) {
        // The buffer contains one or more full SSL records.
        // Slice out the whole packet so unwrap will only be called with complete packets.
        // Also directly reset the packetLength. This is needed as unwrap(..) may trigger
        // decode(...) again via:
        // 1) unwrap(..) is called
        // 2) wrap(...) is called from within unwrap(...)
        // 3) wrap(...) calls unwrapLater(...)
        // 4) unwrapLater(...) calls decode(...)
        //
        // See https://github.com/netty/netty/issues/1534

        in.skipBytes(totalLength);
        final ByteBuffer inNetBuf = in.nioBuffer(startOffset, totalLength);
        unwrap(ctx, inNetBuf, totalLength);
        assert !inNetBuf.hasRemaining() || engine.isInboundDone();
    }

    if (nonSslRecord) {
        // Not an SSL/TLS packet
        NotSslRecordException e = new NotSslRecordException(
                "not an SSL/TLS record: " + ByteBufUtil.hexDump(in));
        in.skipBytes(in.readableBytes());
        ctx.fireExceptionCaught(e);
        setHandshakeFailure(e);
    }
}

From source file:dorkbox.network.pipeline.tcp.KryoDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf in, List<Object> out) throws Exception {
    // Make sure if the length field was received,
    // and read the length of the next object from the socket.
    int lengthLength = OptimizeUtilsByteBuf.canReadInt(in);
    int readableBytes = in.readableBytes(); // full length of available bytes.

    if (lengthLength == 0 || readableBytes < 2 || readableBytes < lengthLength) {
        // The length field was not fully received - do nothing (wait for more...)
        // This method will be invoked again when more packets are
        // received and appended to the buffer.
        return;//from   w w w  .j  a v  a 2  s.  co m
    }

    // The length field is in the buffer.

    // save the writerIndex for local access
    int writerIndex = in.writerIndex();

    // Mark the current buffer position before reading the length fields
    // because the whole frame might not be in the buffer yet.
    // We will reset the buffer position to the marked position if
    // there's not enough bytes in the buffer.
    in.markReaderIndex();

    // Read the length field.
    int length = OptimizeUtilsByteBuf.readInt(in, true);
    readableBytes = in.readableBytes(); // have to adjust readable bytes, since we just read an int off the buffer.

    if (length == 0) {
        context.fireExceptionCaught(new IllegalStateException("KryoDecoder had a read length of 0"));
        return;
    }

    // we can't test against a single "max size", since objects can back-up on the buffer.
    // we must ABSOLUTELY follow a "max size" rule when encoding objects, however.

    final NetworkSerializationManager serializationManager = this.serializationManager;

    // Make sure if there's enough bytes in the buffer.
    if (length > readableBytes) {
        // The whole bytes were not received yet - return null.
        // This method will be invoked again when more packets are
        // received and appended to the buffer.

        // Reset to the marked position to read the length field again
        // next time.
        in.resetReaderIndex();

        // wait for the rest of the object to come in.
        // System.err.println(Thread.currentThread().getName() + " waiting for more of the object to arrive");
    }

    // how many objects are on this buffer?
    else if (readableBytes > length) {
        // more than one!
        // read the object off of the buffer. (save parts of the buffer so if it is too big, we can go back to it, and use it later on...)

        // we know we have at least one object
        int objectCount = 1;
        int endOfObjectPosition = in.readerIndex() + length;

        // set us up for the next object.
        in.readerIndex(endOfObjectPosition);

        // how many more objects?? The first time, it can be off, because we already KNOW it's > 0.
        //  (That's how we got here to begin with)
        while (readableBytes > 0) {
            if (OptimizeUtilsByteBuf.canReadInt(in) > 0) {
                length = OptimizeUtilsByteBuf.readInt(in, true);

                if (length <= 0) {
                    // throw new IllegalStateException("Kryo DecoderTCP had a read length of 0");
                    break;
                }

                endOfObjectPosition = in.readerIndex() + length;

                // position the reader to look for the NEXT object
                if (endOfObjectPosition <= writerIndex) {
                    in.readerIndex(endOfObjectPosition);
                    readableBytes = in.readableBytes();
                    objectCount++;
                } else {
                    break;
                }
            } else {
                break;
            }
        }
        // readerIndex is currently at the MAX place it can read data off the buffer.
        // reset it to the spot BEFORE we started reading data from the buffer.
        in.resetReaderIndex();

        // System.err.println("Found " + objectCount + " objects in this buffer.");

        // NOW add each one of the NEW objects to the array!

        for (int i = 0; i < objectCount; i++) {
            length = OptimizeUtilsByteBuf.readInt(in, true); // object LENGTH

            // however many we need to
            Object object;
            try {
                object = readObject(serializationManager, context, in, length);
                out.add(object);
            } catch (Exception ex) {
                context.fireExceptionCaught(new IOException("Unable to deserialize object!", ex));
            }
        }
        // the buffer reader index will be at the correct location, since the read object method advances it.
    } else {
        // exactly one!
        Object object;
        try {
            object = readObject(serializationManager, context, in, length);
            out.add(object);
        } catch (Exception ex) {
            context.fireExceptionCaught(
                    new IOException("Unable to deserialize object for " + this.getClass(), ex));
        }
    }
}

From source file:dorkbox.network.pipeline.tcp.KryoEncoder.java

License:Apache License

@Override
protected void encode(final ChannelHandlerContext context, final Object msg, final ByteBuf out)
        throws Exception {
    // we don't necessarily start at 0!!
    // START at index = 4. This is to make room for the integer placed by the frameEncoder for TCP.
    int startIndex = out.writerIndex() + reservedLengthIndex;

    if (msg != null) {
        out.writerIndex(startIndex);//from   w  ww . j  a  v a  2 s.com

        try {
            writeObject(this.serializationManager, context, msg, out);
            int index = out.writerIndex();

            // now set the frame length
            // (reservedLengthLength) 4 is the reserved space for the integer.
            int length = index - startIndex;

            // specify the header.
            int lengthOfTheLength = OptimizeUtilsByteBuf.intLength(length, true);

            // make it so the location we write out our length is aligned to the end.
            int indexForLength = startIndex - lengthOfTheLength;
            out.writerIndex(indexForLength);

            // do the optimized length thing!
            OptimizeUtilsByteBuf.writeInt(out, length, true);

            // newIndex is actually where we want to start reading the data as well when written to the socket
            out.setIndex(indexForLength, index);
        } catch (Exception ex) {
            context.fireExceptionCaught(
                    new IOException("Unable to serialize object of type: " + msg.getClass().getName(), ex));
        }
    }
}

From source file:io.airlift.drift.transport.netty.codec.ThriftUnframedDecoder.java

License:Apache License

@Override
protected final void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) {
    int frameOffset = buffer.readerIndex();
    TChannelBufferInputTransport transport = new TChannelBufferInputTransport(buffer.retain());
    try {/*w ww  .  ja va  2 s. c  o m*/
        TProtocolReader protocolReader = protocol.createProtocol(transport);

        TMessage message = protocolReader.readMessageBegin();
        TProtocolUtil.skip(protocolReader, TType.STRUCT);
        protocolReader.readMessageEnd();

        int frameLength = buffer.readerIndex() - frameOffset;
        if (frameLength > maxFrameSize) {
            FrameInfo frameInfo = new FrameInfo(message.getName(), message.getType(), message.getSequenceId(),
                    UNFRAMED, protocol, assumeClientsSupportOutOfOrderResponses);
            ctx.fireExceptionCaught(
                    new FrameTooLargeException(Optional.of(frameInfo), frameLength, maxFrameSize));
        }

        out.add(buffer.slice(frameOffset, frameLength).retain());
    } catch (Throwable th) {
        buffer.readerIndex(frameOffset);
    } finally {
        transport.release();
    }
}

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

License:Apache License

private Object decode(ChannelHandlerContext ctx, ByteBuf buffer) {
    int frameOffset = buffer.readerIndex();
    try {//  w ww .ja v a  2 s .  c  o  m
        TTransport transport = new TChannelBufferInputTransport(buffer);
        TProtocolReader protocol = protocolFactory.getProtocol(transport);

        protocol.readMessageBegin();
        TProtocolUtil.skip(protocol, TType.STRUCT);
        protocol.readMessageEnd();

        int frameLength = buffer.readerIndex() - frameOffset;
        if (frameLength > maxFrameSize) {
            ctx.fireExceptionCaught(new TooLongFrameException(
                    "Response message exceeds max size " + maxFrameSize + ": " + frameLength + " - discarded"));
        }

        return buffer.slice(frameOffset, frameLength).retain();
    } catch (Throwable th) {
        buffer.readerIndex(frameOffset);
        return null;
    }
}