Search in sources :

Example 11 with CodecException

use of io.netty.handler.codec.CodecException in project netty by netty.

the class DeflateEncoder method compressContent.

private ByteBuf compressContent(ChannelHandlerContext ctx, WebSocketFrame msg) {
    if (encoder == null) {
        encoder = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, compressionLevel, windowSize, 8));
    }
    encoder.writeOutbound(msg.content().retain());
    CompositeByteBuf fullCompressedContent = ctx.alloc().compositeBuffer();
    for (; ; ) {
        ByteBuf partCompressedContent = encoder.readOutbound();
        if (partCompressedContent == null) {
            break;
        }
        if (!partCompressedContent.isReadable()) {
            partCompressedContent.release();
            continue;
        }
        fullCompressedContent.addComponent(true, partCompressedContent);
    }
    if (fullCompressedContent.numComponents() <= 0) {
        fullCompressedContent.release();
        throw new CodecException("cannot read compressed buffer");
    }
    if (msg.isFinalFragment() && noContext) {
        cleanup();
    }
    ByteBuf compressedContent;
    if (removeFrameTail(msg)) {
        int realLength = fullCompressedContent.readableBytes() - FRAME_TAIL.readableBytes();
        compressedContent = fullCompressedContent.slice(0, realLength);
    } else {
        compressedContent = fullCompressedContent;
    }
    return compressedContent;
}
Also used : CompositeByteBuf(io.netty.buffer.CompositeByteBuf) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) CodecException(io.netty.handler.codec.CodecException) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf)

Example 12 with CodecException

use of io.netty.handler.codec.CodecException in project LanternServer by LanternPowered.

the class CodecPlayOutEffect method encode.

@Override
public ByteBuffer encode(CodecContext context, Message message) throws CodecException {
    final ByteBuffer buf = context.byteBufAlloc().buffer();
    if (message instanceof MessagePlayOutEffect) {
        final MessagePlayOutEffect message1 = (MessagePlayOutEffect) message;
        buf.writeInteger(message1.getType());
        buf.write(Types.VECTOR_3_I, message1.getPosition());
        buf.writeInteger(message1.getData());
        buf.writeBoolean(message1.isBroadcast());
    } else if (message instanceof MessagePlayOutRecord) {
        final MessagePlayOutRecord message1 = (MessagePlayOutRecord) message;
        buf.writeInteger(1010);
        buf.write(Types.VECTOR_3_I, message1.getPosition());
        buf.writeInteger(message1.getRecord().map(type -> 2256 + ((LanternRecordType) type).getInternalId()).orElse(0));
        buf.writeBoolean(false);
    } else {
        throw new EncoderException("Unsupported message type: " + message.getClass().getName());
    }
    return buf;
}
Also used : EncoderException(io.netty.handler.codec.EncoderException) CodecException(io.netty.handler.codec.CodecException) Codec(org.lanternpowered.server.network.message.codec.Codec) MessagePlayOutRecord(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutRecord) LanternRecordType(org.lanternpowered.server.data.type.record.LanternRecordType) MessagePlayOutEffect(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutEffect) ByteBuffer(org.lanternpowered.server.network.buffer.ByteBuffer) Types(org.lanternpowered.server.network.buffer.objects.Types) CodecContext(org.lanternpowered.server.network.message.codec.CodecContext) Message(org.lanternpowered.server.network.message.Message) EncoderException(io.netty.handler.codec.EncoderException) MessagePlayOutEffect(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutEffect) MessagePlayOutRecord(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutRecord) ByteBuffer(org.lanternpowered.server.network.buffer.ByteBuffer)

Example 13 with CodecException

use of io.netty.handler.codec.CodecException in project LanternServer by LanternPowered.

the class LanternByteBuffer method readLimitedDataView.

@Nullable
@Override
public DataView readLimitedDataView(int maximumDepth, int maxBytes) {
    final int index = this.buf.readerIndex();
    if (this.buf.readByte() == 0) {
        return null;
    }
    this.buf.readerIndex(index);
    try {
        try (NbtDataContainerInputStream input = new NbtDataContainerInputStream(new LimitInputStream(new ByteBufInputStream(this.buf), maxBytes), false, maximumDepth)) {
            return input.read();
        }
    } catch (IOException e) {
        throw new CodecException(e);
    }
}
Also used : NbtDataContainerInputStream(org.lanternpowered.server.data.persistence.nbt.NbtDataContainerInputStream) CodecException(io.netty.handler.codec.CodecException) LimitInputStream(org.lanternpowered.server.util.io.LimitInputStream) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) IOException(java.io.IOException) Nullable(javax.annotation.Nullable)

Example 14 with CodecException

use of io.netty.handler.codec.CodecException in project netty by netty.

the class HttpContentDecoder method decode.

@Override
protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
    try {
        if (msg instanceof HttpResponse && ((HttpResponse) msg).status().code() == 100) {
            if (!(msg instanceof LastHttpContent)) {
                continueResponse = true;
            }
            // 100-continue response must be passed through.
            out.add(ReferenceCountUtil.retain(msg));
            return;
        }
        if (continueResponse) {
            if (msg instanceof LastHttpContent) {
                continueResponse = false;
            }
            // 100-continue response must be passed through.
            out.add(ReferenceCountUtil.retain(msg));
            return;
        }
        if (msg instanceof HttpMessage) {
            cleanup();
            final HttpMessage message = (HttpMessage) msg;
            final HttpHeaders headers = message.headers();
            // Determine the content encoding.
            String contentEncoding = headers.get(HttpHeaderNames.CONTENT_ENCODING);
            if (contentEncoding != null) {
                contentEncoding = contentEncoding.trim();
            } else {
                String transferEncoding = headers.get(HttpHeaderNames.TRANSFER_ENCODING);
                if (transferEncoding != null) {
                    int idx = transferEncoding.indexOf(",");
                    if (idx != -1) {
                        contentEncoding = transferEncoding.substring(0, idx).trim();
                    } else {
                        contentEncoding = transferEncoding.trim();
                    }
                } else {
                    contentEncoding = IDENTITY;
                }
            }
            decoder = newContentDecoder(contentEncoding);
            if (decoder == null) {
                if (message instanceof HttpContent) {
                    ((HttpContent) message).retain();
                }
                out.add(message);
                return;
            }
            // Otherwise, rely on LastHttpContent message.
            if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
                headers.remove(HttpHeaderNames.CONTENT_LENGTH);
                headers.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
            }
            // Either it is already chunked or EOF terminated.
            // See https://github.com/netty/netty/issues/5892
            // set new content encoding,
            CharSequence targetContentEncoding = getTargetContentEncoding(contentEncoding);
            if (HttpHeaderValues.IDENTITY.contentEquals(targetContentEncoding)) {
                // Do NOT set the 'Content-Encoding' header if the target encoding is 'identity'
                // as per: https://tools.ietf.org/html/rfc2616#section-14.11
                headers.remove(HttpHeaderNames.CONTENT_ENCODING);
            } else {
                headers.set(HttpHeaderNames.CONTENT_ENCODING, targetContentEncoding);
            }
            if (message instanceof HttpContent) {
                // If message is a full request or response object (headers + data), don't copy data part into out.
                // Output headers only; data part will be decoded below.
                // Note: "copy" object must not be an instance of LastHttpContent class,
                // as this would (erroneously) indicate the end of the HttpMessage to other handlers.
                HttpMessage copy;
                if (message instanceof HttpRequest) {
                    // HttpRequest or FullHttpRequest
                    HttpRequest r = (HttpRequest) message;
                    copy = new DefaultHttpRequest(r.protocolVersion(), r.method(), r.uri());
                } else if (message instanceof HttpResponse) {
                    // HttpResponse or FullHttpResponse
                    HttpResponse r = (HttpResponse) message;
                    copy = new DefaultHttpResponse(r.protocolVersion(), r.status());
                } else {
                    throw new CodecException("Object of class " + message.getClass().getName() + " is not an HttpRequest or HttpResponse");
                }
                copy.headers().set(message.headers());
                copy.setDecoderResult(message.decoderResult());
                out.add(copy);
            } else {
                out.add(message);
            }
        }
        if (msg instanceof HttpContent) {
            final HttpContent c = (HttpContent) msg;
            if (decoder == null) {
                out.add(c.retain());
            } else {
                decodeContent(c, out);
            }
        }
    } finally {
        needRead = out.isEmpty();
    }
}
Also used : CodecException(io.netty.handler.codec.CodecException)

Example 15 with CodecException

use of io.netty.handler.codec.CodecException in project netty by netty.

the class HttpContentDecoderTest method testCleanupThrows.

@Test
public void testCleanupThrows() {
    HttpContentDecoder decoder = new HttpContentDecoder() {

        @Override
        protected EmbeddedChannel newContentDecoder(String contentEncoding) throws Exception {
            return new EmbeddedChannel(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    ctx.fireExceptionCaught(new DecoderException());
                    ctx.fireChannelInactive();
                }
            });
        }
    };
    final AtomicBoolean channelInactiveCalled = new AtomicBoolean();
    EmbeddedChannel channel = new EmbeddedChannel(decoder, new ChannelInboundHandlerAdapter() {

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            assertTrue(channelInactiveCalled.compareAndSet(false, true));
            super.channelInactive(ctx);
        }
    });
    assertTrue(channel.writeInbound(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/")));
    HttpContent content = new DefaultHttpContent(Unpooled.buffer().writeZero(10));
    assertTrue(channel.writeInbound(content));
    assertEquals(1, content.refCnt());
    try {
        channel.finishAndReleaseAll();
        fail();
    } catch (CodecException expected) {
    // expected
    }
    assertTrue(channelInactiveCalled.get());
    assertEquals(0, content.refCnt());
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CodecException(io.netty.handler.codec.CodecException) DecoderException(io.netty.handler.codec.DecoderException) DecoderException(io.netty.handler.codec.DecoderException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CodecException(io.netty.handler.codec.CodecException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Aggregations

CodecException (io.netty.handler.codec.CodecException)19 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)7 ByteBuf (io.netty.buffer.ByteBuf)6 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)4 Test (org.junit.jupiter.api.Test)4 BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame)3 ContinuationWebSocketFrame (io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame)3 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2 PrematureChannelClosureException (io.netty.handler.codec.PrematureChannelClosureException)2 HttpResponse (io.netty.handler.codec.http.HttpResponse)2 WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)2 ByteBuffer (org.lanternpowered.server.network.buffer.ByteBuffer)2 Message (org.lanternpowered.server.network.message.Message)2 MessagePlayInOutChannelPayload (org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayInOutChannelPayload)2 Vector3i (com.flowpowered.math.vector.Vector3i)1 JsonArray (com.google.gson.JsonArray)1 JsonObject (com.google.gson.JsonObject)1 ByteBufInputStream (io.netty.buffer.ByteBufInputStream)1