private void handleIFormat ( final InformationTransfer msg, ByteBuf out ) { final ByteBuf data = msg.getData (); try { out = out.order ( ByteOrder.LITTLE_ENDIAN ); final int len = data.readableBytes (); if ( len > Constants.APCI_MAX_DATA_LENGTH ) { throw new EncoderException ( String.format ( "Packet too big - %s bytes", len ) ); } out.ensureWritable ( 6 + len ); out.writeByte ( Constants.START_BYTE ); out.writeByte ( 4 + len ); out.writeShort ( msg.getSendSequenceNumber () << 1 ); out.writeShort ( msg.getReceiveSequenceNumber () << 1 ); out.writeBytes ( data ); } finally { ReferenceCountUtil.release ( msg.getData () ); } }
/** * Writes a compressed NBTTagCompound to this buffer */ public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt) { if (nbt == null) { this.writeByte(0); } else { try { CompressedStreamTools.write(nbt, new ByteBufOutputStream(this)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
/** * Writes a compressed NBTTagCompound to this buffer */ public PacketBuffer writeNBTTagCompoundToBuffer(@Nullable NBTTagCompound nbt) { if (nbt == null) { this.writeByte(0); } else { try { CompressedStreamTools.write(nbt, new ByteBufOutputStream(this)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } return this; }
private static <T> void writeEntry(PacketBuffer buf, EntityDataManager.DataEntry<T> entry) throws IOException { DataParameter<T> dataparameter = entry.getKey(); int i = DataSerializers.getSerializerId(dataparameter.getSerializer()); if (i < 0) { throw new EncoderException("Unknown serializer type " + dataparameter.getSerializer()); } else { buf.writeByte(dataparameter.getId()); buf.writeVarIntToBuffer(i); dataparameter.getSerializer().write(buf, entry.getValue()); } }
/** * Reads a compressed NBTTagCompound from this buffer */ @Nullable public NBTTagCompound readNBTTagCompoundFromBuffer() throws IOException { int i = this.readerIndex(); byte b0 = this.readByte(); if (b0 == 0) { return null; } else { this.readerIndex(i); try { return CompressedStreamTools.read(new ByteBufInputStream(this), new NBTSizeTracker(2097152L)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
public static void writeNBTTagCompoundToBuffer(ByteBuf buf, NBTTagCompound tag) { if (tag == null) { buf.writeByte(0); return; } try { CompressedStreamTools.write(tag, new ByteBufOutputStream(buf)); } catch (IOException ioexception) { ModLogger.error("IOException while trying to write a NBTTagCompound to ByteBuf"); throw new EncoderException(ioexception); } }
@Nullable public static NBTTagCompound readNBTTagCompound(MCDataInput input) { byte flag = input.readByte(); if (flag == 0) { return null; } else if (flag == 1) { try { return CompressedStreamTools.read(new DataInputStream(new MCDataInputStream(input)), new NBTSizeTracker(2097152L)); } catch (IOException e) { throw new EncoderException(e); } } else { throw new EncoderException("Invalid flag for readNBTTagCompound. Expected 0 || 1 Got: " + flag + " Possible incorrect read order?"); } }
/** * Decompresses the remaining ByteBuf (after type has been read) using Snappy */ private void decompress() { Inflater inflater = new Inflater(); try { int len = readVarInt(); byte[] out = new byte[len]; inflater.setInput(array(), readerIndex(), readableBytes()); inflater.inflate(out); clear(); writeArray(out); } catch (Exception e) { throw new EncoderException(e); } finally { inflater.end(); } }
/** * Compresses the payload ByteBuf after the type byte */ private void do_compress() { Deflater deflater = new Deflater(); try { readerIndex(1); int len = readableBytes(); deflater.setInput(array(), readerIndex(), len); deflater.finish(); byte[] out = new byte[len]; int clen = deflater.deflate(out); if (clen >= len - 5 || !deflater.finished())//not worth compressing, gets larger { return; } clear(); writeByte(type | 0x80); writeVarInt(len); writeArray(out); } catch (Exception e) { throw new EncoderException(e); } finally { readerIndex(0); deflater.end(); } }
@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; }
@Override public void write(final ChannelHandlerContext ctx, final Object msgObject, final ChannelPromise promise) throws Exception { try { if (acceptOutboundMessage(msgObject)) { DefinedPacket msg = (DefinedPacket) msgObject; try { encode(ctx, msg, null); } finally { ReferenceCountUtil.release(msg); } } else { ctx.write(msgObject, promise); } } catch (EncoderException e) { throw e; } catch (Throwable e2) { throw new EncoderException(e2); } }
@Override protected void encode(ChannelHandlerContext channelHandlerContext, Packet packet, List<Object> list) throws Exception { Class<? extends Packet> packetClass = packet.getClass(); CodecRegistrationEntry registrationEntry = this.networkHandler.getSession().getProtocol().getCodecRegistration(this.side, packetClass); if (registrationEntry == null) { throw new EncoderException("Failed to find a CodecRegistrationEntry for packet: " + packetClass.getName()); } ByteBuf header = channelHandlerContext.alloc().buffer(8); ByteBufUtils.writeVarInt(header, registrationEntry.getOpcode()); ByteBuf contents = channelHandlerContext.alloc().buffer(); contents = registrationEntry.getCodec().encode(contents, packet); list.add(Unpooled.wrappedBuffer(header, contents)); }
@Override protected void encode(ChannelHandlerContext ctx, Message<T> msg, List<Object> out) throws Exception { Schema<T> schema = msg.cachedSchema(); LowCopyProtobufOutput lcpo = new LowCopyProtobufOutput(); schema.writeTo(lcpo, (T) msg); List<ByteBuffer> buffers = lcpo.buffer.finish(); long size = lcpo.buffer.size(); if (size > Integer.MAX_VALUE) { throw new EncoderException("Serialized form was too large, actual size: " + size); } out.add(Unpooled.wrappedBuffer(buffers.toArray(new ByteBuffer[]{}))); }
public static void writeNBTTagCompoundToBuffer(ByteBuf buf, NBTTagCompound tag) { if (tag == null) { buf.writeByte(0); return; } try { CompressedStreamTools.write(tag, new ByteBufOutputStream(buf)); } catch (IOException ioexception) { EnderUtilities.logger.error("IOException while trying to write a NBTTagCompound to ByteBuf"); throw new EncoderException(ioexception); } }
public static void writeTag(ByteBuf to, ProtocolVersion version, NBTTagCompoundWrapper tag) { try { if (isUsingShortLengthNBT(version)) { if (tag.isNull()) { to.writeShort(-1); } else { int writerIndex = to.writerIndex(); //fake length to.writeShort(0); //actual nbt try (OutputStream outputstream = new GZIPOutputStream(new ByteBufOutputStream(to))) { NBTTagCompoundSerializer.writeTag(new DataOutputStream(outputstream), tag); } //now replace fake length with real length to.setShort(writerIndex, to.writerIndex() - writerIndex - Short.BYTES); } } else if (isUsingDirectNBT(version)) { NBTTagCompoundSerializer.writeTag(new ByteBufOutputStream(to), tag); } else { throw new IllegalArgumentException(MessageFormat.format("Dont know how to write nbt of version {0}", version)); } } catch (Throwable ioexception) { throw new EncoderException(ioexception); } }
/** * Decode the variable remaining length as defined in MQTT v3.1 specification * (section 2.1). * * @return the decoded length or -1 if needed more data to decode the length field. */ public static int decodeRemainingLength(ByteBuf in) throws EncoderException { int multiplier = 1; int value = 0; byte digit; do { if (in.readableBytes() < 1) { return -1; } digit = in.readByte(); value += (digit & 0x7F) * multiplier; multiplier *= 128; } while ((digit & 0x80) != 0); if (value > MAX_LENGTH_LIMIT || value < 0) { in.resetReaderIndex(); throw new DecoderException("Remaining Length should in range 0.." + MAX_LENGTH_LIMIT + " found " + value); } return value; }
/** * Encode the value in the format defined in specification as variable length * array. * * @throws EncoderException if the value is not in the specification bounds * [0..268435455]. */ public static ByteBuf encodeRemainingLength(int value) throws EncoderException { if (value > MAX_LENGTH_LIMIT || value < 0) { throw new EncoderException("Remaining Length should in range 0.." + MAX_LENGTH_LIMIT + " found " + value); } ByteBuf encoded = Unpooled.buffer(4); byte digit; do { digit = (byte) (value % 128); value = value / 128; // if there are more digits to encode, set the top bit of this digit if (value > 0) { digit = (byte) (digit | 0x80); } encoded.writeByte(digit); } while (value > 0); return encoded; }
private void encode(ChannelHandlerContext ctx, ByteBuf out, RedisCommand<?, ?, ?> command) { try { out.markWriterIndex(); command.encode(out); } catch (RuntimeException e) { out.resetWriterIndex(); command.completeExceptionally(new EncoderException( "Cannot encode command. Please close the connection as the connection state may be out of sync.", e)); } if (debugEnabled) { logger.debug("{} writing command {}", logPrefix(ctx.channel()), command); if (traceEnabled) { logger.trace("{} Sent: {}", logPrefix(ctx.channel()), out.toString(Charset.defaultCharset()).trim()); } } }
@Test public void shouldPropagateErrorOnEncode() { String id = "key"; ByteBuf content = Unpooled.buffer(); content.release(); // provoke a IllegalReferenceCountException UpsertRequest request = new UpsertRequest(id, content, BUCKET); request.partition((short) 1); TestSubscriber<CouchbaseResponse> ts = TestSubscriber.create(); request.observable().subscribe(ts); try { channel.writeOutbound(request); fail("Expected exception, none thrown."); } catch (EncoderException ex) { assertTrue(ex.getCause() instanceof IllegalReferenceCountException); } List<Throwable> onErrorEvents = ts.getOnErrorEvents(); assertTrue(onErrorEvents.get(0) instanceof RequestCancelledException); assertTrue(onErrorEvents.get(0).getCause() instanceof IllegalReferenceCountException); }
@Nullable public NBTTagCompound j() { int i = this.readerIndex(); byte b0 = this.readByte(); if (b0 == 0) { return null; } else { this.readerIndex(i); try { return NBTCompressedStreamTools.a((DataInput) (new ByteBufInputStream(this)), new NBTReadLimiter(2097152L)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
@Override public void write ( final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise ) throws Exception { logger.trace ( "Write {}", msg ); synchronized ( this ) { if ( msg instanceof DataTransmissionMessage ) { switch ( (DataTransmissionMessage)msg ) { case REQUEST_START: ctx.write ( new UnnumberedControl ( Function.STARTDT_ACT ), promise ); break; case CONFIRM_START: ctx.write ( new UnnumberedControl ( Function.STARTDT_CONFIRM ), promise ); break; case REQUEST_STOP: ctx.write ( new UnnumberedControl ( Function.STOPDT_ACT ), promise ); break; case CONFIRM_STOP: ctx.write ( new UnnumberedControl ( Function.STOPDT_CONFIRM ), promise ); break; default: throw new EncoderException ( String.format ( "Unknown data transmission message: %s", msg ) ); } } else if ( msg == MessageSource.NOTIFY_TOKEN ) { handleMessageSourceUpdates ( ctx ); } else { handleMessageWrite ( ctx, msg, promise ); } } }
/** * Writes a string into the packets buffer * * @param string The string * @return The buffer */ public PacketBuffer writeString(String string) { if(string == null) string = ""; byte[] abyte = string.getBytes(Charsets.UTF_8); if(abyte.length > 32767) { throw new EncoderException("String too big (was " + string.length() + " bytes encoded, slots " + 32767 + ")"); } else { this.writeVarInt(abyte.length); buf.writeBytes(abyte); return this; } }
public PacketBuffer writeString(String string) { byte[] abyte = string.getBytes(Charsets.UTF_8); if (abyte.length > 32767) { throw new EncoderException("String too big (was " + string.length() + " bytes encoded, max " + 32767 + ")"); } else { this.writeVarIntToBuffer(abyte.length); this.writeBytes(abyte); return this; } }
@Nullable /** * Reads a compressed NBTTagCompound from this buffer */ public NBTTagCompound readNBTTagCompoundFromBuffer() throws IOException { int i = this.readerIndex(); byte b0 = this.readByte(); if (b0 == 0) { return null; } else { this.readerIndex(i); try { return CompressedStreamTools.read(new ByteBufInputStream(this), new NBTSizeTracker(2097152L)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
public PacketBuffer writeString(String string) { byte[] abyte = string.getBytes(Charsets.UTF_8); if (abyte.length > 32767) { throw new EncoderException("String too big (was " + abyte.length + " bytes encoded, max " + 32767 + ")"); } else { this.writeVarIntToBuffer(abyte.length); this.writeBytes(abyte); return this; } }
public void toBytes(CompressedDataOutput cdo) throws IOException { if (stack == null || ItemStackTools.isNullStack(stack)) { cdo.writeShort(-1); } else { cdo.writeShort(Item.getIdFromItem(stack.getItem())); cdo.writeVariable(ItemStackTools.getStackSize(stack)); cdo.writeShort(stack.getMetadata()); NBTTagCompound nbttagcompound = null; if (stack.getItem().isDamageable() || stack.getItem().getShareTag()) { nbttagcompound = stack.getTagCompound(); } if (nbttagcompound == null) { cdo.writeByte(0); } else { cdo.writeByte(1); try { CompressedStreamTools.write(nbttagcompound, cdo); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } } cdo.writeBoolean(isCrafting); }
public void toBytes(CompressedDataOutput cdo) throws IOException { if (stack == null) { cdo.writeShort(-1); } else { cdo.writeShort(1); NBTTagCompound nbttagcompound = stack.writeToNBT(new NBTTagCompound()); cdo.writeByte(1); try { CompressedStreamTools.write(nbttagcompound, cdo); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
public PacketDataSerializer writeText(final String s) { final byte[] abyte = s.getBytes(StandardCharsets.UTF_8); if (abyte.length > Short.MAX_VALUE) { throw new EncoderException("String too big (was " + s.length() + " bytes encoded, max " + Short.MAX_VALUE + ")"); } this.writeVarInt(abyte.length); this.writeBytes(abyte); return this; }
public MCDataOutputWrapper writeBoolean(boolean b) { try { dataout.writeBoolean(b); } catch (IOException e) { throw new EncoderException(e); } return this; }