Search in sources :

Example 1 with EncoderException

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

the class CodecPlayOutUnlockRecipes method encode.

@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutUnlockRecipes message) throws CodecException {
    final ByteBuffer buf = context.byteBufAlloc().buffer();
    if (message instanceof MessagePlayOutUnlockRecipes.Remove) {
        buf.writeVarInt((short) 2);
    } else if (message instanceof MessagePlayOutUnlockRecipes.Add) {
        buf.writeVarInt((short) 1);
    } else if (message instanceof MessagePlayOutUnlockRecipes.Init) {
        buf.writeVarInt((short) 0);
    } else {
        throw new EncoderException();
    }
    buf.writeBoolean(message.hasOpenCraftingBook());
    buf.writeBoolean(message.hasCraftingFilter());
    IntList recipeIds = message.getRecipeIds();
    buf.writeVarInt(recipeIds.size());
    recipeIds.forEach(buf::writeVarInt);
    if (message instanceof MessagePlayOutUnlockRecipes.Init) {
        recipeIds = ((MessagePlayOutUnlockRecipes.Init) message).getRecipeIdsToBeDisplayed();
        buf.writeVarInt(recipeIds.size());
        recipeIds.forEach(buf::writeVarInt);
    }
    return buf;
}
Also used : EncoderException(io.netty.handler.codec.EncoderException) MessagePlayOutUnlockRecipes(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutUnlockRecipes) ByteBuffer(org.lanternpowered.server.network.buffer.ByteBuffer) IntList(it.unimi.dsi.fastutil.ints.IntList)

Example 2 with EncoderException

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

the class CodecPlayOutSetWindowSlot method encode.

@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutSetWindowSlot message) throws CodecException {
    final ByteBuffer buf = context.byteBufAlloc().buffer();
    buf.writeByte((byte) message.getWindow());
    buf.writeShort((short) message.getIndex());
    final Object item = message.getItem();
    if (item instanceof ItemStack) {
        buf.write(Types.ITEM_STACK, (ItemStack) item);
    } else if (item instanceof RawItemStack || item == null) {
        buf.write(Types.RAW_ITEM_STACK, (RawItemStack) item);
    } else {
        throw new EncoderException("Invalid item type:" + item.getClass().getName());
    }
    return buf;
}
Also used : EncoderException(io.netty.handler.codec.EncoderException) RawItemStack(org.lanternpowered.server.network.objects.RawItemStack) RawItemStack(org.lanternpowered.server.network.objects.RawItemStack) ItemStack(org.spongepowered.api.item.inventory.ItemStack) ByteBuffer(org.lanternpowered.server.network.buffer.ByteBuffer)

Example 3 with EncoderException

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

the class MessageCodecHandler method encode.

@Override
protected void encode(ChannelHandlerContext ctx, Message message, List<Object> output) throws Exception {
    final Protocol protocol = this.codecContext.getSession().getProtocol();
    final MessageRegistration<Message> registration = (MessageRegistration<Message>) protocol.outbound().findByMessageType(message.getClass()).orElse(null);
    if (registration == null) {
        throw new EncoderException("Message type (" + message.getClass().getName() + ") is not registered!");
    }
    CodecRegistration codecRegistration = registration.getCodecRegistration().orElse(null);
    if (codecRegistration == null) {
        throw new EncoderException("Message type (" + message.getClass().getName() + ") is not registered to allow encoding!");
    }
    /*
        if (message instanceof MessagePlayOutWorldTime ||
                message instanceof MessageInOutKeepAlive) {
        } else {
            System.out.println(message.getClass().getName());
        }
        */
    final ByteBuf opcode = ctx.alloc().buffer();
    // Write the opcode of the message
    writeVarInt(opcode, codecRegistration.getOpcode());
    final Codec codec = codecRegistration.getCodec();
    final ByteBuffer content;
    try {
        content = codec.encode(this.codecContext, message);
    } finally {
        ReferenceCountUtil.release(message);
    }
    // Add the buffer to the output
    output.add(Unpooled.wrappedBuffer(opcode, ((LanternByteBuffer) content).getDelegate()));
}
Also used : EncoderException(io.netty.handler.codec.EncoderException) Codec(org.lanternpowered.server.network.message.codec.Codec) MessageToMessageCodec(io.netty.handler.codec.MessageToMessageCodec) MessageRegistration(org.lanternpowered.server.network.message.MessageRegistration) HandlerMessage(org.lanternpowered.server.network.message.HandlerMessage) NullMessage(org.lanternpowered.server.network.message.NullMessage) Message(org.lanternpowered.server.network.message.Message) BulkMessage(org.lanternpowered.server.network.message.BulkMessage) CodecRegistration(org.lanternpowered.server.network.message.CodecRegistration) Protocol(org.lanternpowered.server.network.protocol.Protocol) ByteBuf(io.netty.buffer.ByteBuf) ByteBuffer(org.lanternpowered.server.network.buffer.ByteBuffer) LanternByteBuffer(org.lanternpowered.server.network.buffer.LanternByteBuffer) LanternByteBuffer(org.lanternpowered.server.network.buffer.LanternByteBuffer)

Example 4 with EncoderException

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

the class MessageCompressionHandler method encode.

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
    ByteBuf prefixBuf = ctx.alloc().buffer(5);
    ByteBuf contentsBuf;
    if (msg.readableBytes() >= this.compressionThreshold) {
        // Message should be compressed
        int index = msg.readerIndex();
        int length = msg.readableBytes();
        byte[] sourceData = new byte[length];
        msg.readBytes(sourceData);
        this.deflater.setInput(sourceData);
        this.deflater.finish();
        byte[] compressedData = new byte[length];
        int compressedLength = this.deflater.deflate(compressedData);
        this.deflater.reset();
        if (compressedLength == 0) {
            // Compression failed in some weird way
            throw new EncoderException("Failed to compress message of size " + length);
        } else if (compressedLength >= length) {
            // Compression increased the size. threshold is probably too low
            // Send as an uncompressed packet
            writeVarInt(prefixBuf, 0);
            msg.readerIndex(index);
            msg.retain();
            contentsBuf = msg;
        } else {
            // All is well
            writeVarInt(prefixBuf, length);
            contentsBuf = Unpooled.wrappedBuffer(compressedData, 0, compressedLength);
        }
    } else {
        // Message should be sent through
        writeVarInt(prefixBuf, 0);
        msg.retain();
        contentsBuf = msg;
    }
    out.add(Unpooled.wrappedBuffer(prefixBuf, contentsBuf));
}
Also used : EncoderException(io.netty.handler.codec.EncoderException) ByteBuf(io.netty.buffer.ByteBuf)

Example 5 with EncoderException

use of io.netty.handler.codec.EncoderException in project ballerina by ballerina-lang.

the class AbstractHTTPAction method send.

/**
 * Send outbound request through the client connector. If the Content-Type is multipart, check whether the boundary
 * exist. If not get a new boundary string and add it as a parameter to Content-Type, just before sending header
 * info through wire. If a boundary string exist at this point, serialize multipart entity body, else serialize
 * entity body which can either be a message data source or a byte channel.
 *
 * @param dataContext               holds the ballerina context and callback
 * @param outboundRequestMsg        Outbound request that needs to be sent across the wire
 * @param async                     whether a handle should be return
 * @return connector future for this particular request
 * @throws Exception When an error occurs while sending the outbound request via client connector
 */
private void send(DataContext dataContext, HTTPCarbonMessage outboundRequestMsg, boolean async) throws Exception {
    BStruct bConnector = (BStruct) dataContext.context.getRefArgument(0);
    Struct httpClient = BLangConnectorSPIUtil.toStruct(bConnector);
    HttpClientConnector clientConnector = (HttpClientConnector) httpClient.getNativeData(HttpConstants.HTTP_CLIENT);
    String contentType = HttpUtil.getContentTypeFromTransportMessage(outboundRequestMsg);
    String boundaryString = null;
    if (HeaderUtil.isMultipart(contentType)) {
        boundaryString = HttpUtil.addBoundaryIfNotExist(outboundRequestMsg, contentType);
    }
    HttpMessageDataStreamer outboundMsgDataStreamer = new HttpMessageDataStreamer(outboundRequestMsg);
    OutputStream messageOutputStream = outboundMsgDataStreamer.getOutputStream();
    RetryConfig retryConfig = getRetryConfiguration(httpClient);
    HTTPClientConnectorListener httpClientConnectorLister = new HTTPClientConnectorListener(dataContext, retryConfig, outboundRequestMsg, outboundMsgDataStreamer);
    HttpResponseFuture future = clientConnector.send(outboundRequestMsg);
    if (async) {
        future.setResponseHandleListener(httpClientConnectorLister);
    } else {
        future.setHttpConnectorListener(httpClientConnectorLister);
    }
    try {
        if (boundaryString != null) {
            serializeMultiparts(dataContext.context, messageOutputStream, boundaryString);
        } else {
            serializeDataSource(dataContext.context, messageOutputStream);
        }
    } catch (IOException | EncoderException serializerException) {
        // We don't have to do anything here as the client connector will notify
        // the error though the listener
        logger.warn("couldn't serialize the message", serializerException);
    }
}
Also used : EncoderException(io.netty.handler.codec.EncoderException) BStruct(org.ballerinalang.model.values.BStruct) HttpClientConnector(org.wso2.transport.http.netty.contract.HttpClientConnector) RetryConfig(org.ballerinalang.net.http.RetryConfig) HttpMessageDataStreamer(org.wso2.transport.http.netty.message.HttpMessageDataStreamer) OutputStream(java.io.OutputStream) HttpResponseFuture(org.wso2.transport.http.netty.contract.HttpResponseFuture) IOException(java.io.IOException) ResponseCacheControlStruct(org.ballerinalang.net.http.caching.ResponseCacheControlStruct) Struct(org.ballerinalang.connector.api.Struct) BStruct(org.ballerinalang.model.values.BStruct)

Aggregations

EncoderException (io.netty.handler.codec.EncoderException)26 ByteBuffer (org.lanternpowered.server.network.buffer.ByteBuffer)9 ByteBuf (io.netty.buffer.ByteBuf)6 IOException (java.io.IOException)6 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)3 Test (org.junit.jupiter.api.Test)3 Message (org.lanternpowered.server.network.message.Message)3 CodecException (io.netty.handler.codec.CodecException)2 Deflater (java.util.zip.Deflater)2 Inflater (java.util.zip.Inflater)2 MessageRegistration (org.lanternpowered.server.network.message.MessageRegistration)2 Codec (org.lanternpowered.server.network.message.codec.Codec)2 CodecRegistration (com.flowpowered.network.Codec.CodecRegistration)1 ByteBufInputStream (io.netty.buffer.ByteBufInputStream)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)1 DecoderResult (io.netty.handler.codec.DecoderResult)1 LengthFieldPrepender (io.netty.handler.codec.LengthFieldPrepender)1 MessageToMessageCodec (io.netty.handler.codec.MessageToMessageCodec)1 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)1