@Test public void testDeserialize() throws Exception { ByteBuf buf = Unpooled.buffer(16); buf.writeInt(0); buf.writeInt(1); buf.writeLong(2); buf.writeLong(3); buf.writeInt(4); buf.writeInt(3); buf.writeInt(-1); buf.writeInt(-2); buf.writeInt(-3); serverDenseIntRow.deserialize(buf); assertEquals(serverDenseIntRow.getRowId(), 0); assertEquals(serverDenseIntRow.getClock(), 1); assertEquals(serverDenseIntRow.getStartCol(), 2); assertEquals(serverDenseIntRow.getEndCol(), 3); assertEquals(serverDenseIntRow.getRowVersion(), 4); assertEquals(serverDenseIntRow.getData().get(0), -1, 0.0); assertEquals(serverDenseIntRow.getData().get(1), -2, 0.0); assertEquals(serverDenseIntRow.getData().get(2), -3, 0.0); }
@Timed void startBodyParse(ByteBuf in) throws UnknownFetchItemTypeException, IOException { skipControlCharacters(in); char c = ((char) in.readUnsignedByte()); //String bodySection = ""; At some point we will need to actually store the body section that is being parsed below if (c != '[') { // This is effectively BODYSTRUCTURE which is not yet supported lineParser.parse(in); checkpoint(State.RESET); throw new UnknownFetchItemTypeException("BODYSTRUCTURE"); } else { c = ((char) in.readUnsignedByte()); while (c != ']') { // Skip characters within "[]" c = ((char) in.readUnsignedByte()); } } checkpoint(State.FETCH_BODY); }
/** * <b>一定要 {@link ByteBuf#release()} */ public static ByteBuf encode(RemotingCommand cmd) { int reqId = cmd.getOpaque(); byte[] body = cmd.getBody(); HashMap<String, String> msgs = cmd.getExtFields(); byte[] append = JsonUtil.toBytes(msgs); int initialCapacity = 4 + 4 // total size+reqId + 4 + body.length // body + 4 + append.length;// apend ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(initialCapacity); buf.writeInt(initialCapacity); buf.writeInt(reqId); buf.writeInt(body.length); buf.writeBytes(body); buf.writeInt(append.length); buf.writeBytes(append); return buf; }
@SuppressWarnings("unchecked") @Override public void fromBytes(ByteBuf buf) { short len = buf.readShort(); byte[] compressedBody = new byte[len]; for (short i = 0; i < len; i++) { compressedBody[i] = buf.readByte(); } try { ObjectInputStream obj = new ObjectInputStream(new GZIPInputStream(new ByteArrayInputStream(compressedBody))); values = (Map<String, Object>) obj.readObject(); obj.close(); } catch (Exception e) { Throwables.propagate(e); } }
public static String getJson(Object msg) { String json; try { ByteBuf buf = (ByteBuf) msg; byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); json = new String(bytes); } finally { ReferenceCountUtil.release(msg); } return json; }
public void setData(ByteBuf buff) { if (data == null) { data = getByteBuf(); } data.writeBytes(buff); }
@Override public void encode ( final ProtocolOptions options, final ByteBuf out ) { EncodeHelper.encodeHeader ( this, options, this.values.size (), this.header, out ); this.startAddress.encode ( options, out ); for ( final Value<Float> value : this.values ) { TypeHelper.encodeFloatValue ( options, out, value, false ); } }
@Override public void toBytes(ByteBuf buf) { buf.writeByte(windowId); buf.writeByte(tank); NBTTagCompound fluidNbt = fluid == null ? null : fluid.writeToNBT(new NBTTagCompound()); ByteBufUtils.writeTag(buf, fluidNbt); }
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 8) { return; } short dataLen = in.getShort(in.readerIndex() + 6); if (in.readableBytes() < dataLen) { return; } ByteBuf msg = in.readRetainedSlice(8 + dataLen); out.add(msg); }
public RtMessageBuilder add(RtTag tag, RtMessage msg) { checkNotNull(tag, "tag must be non-null"); checkNotNull(msg, "msg must be non-null"); ByteBuf encoded = RtWire.toWire(msg, allocator); return add(tag, encoded); }
/** * 缓存可读数据中的非完整帧,拼接为完整帧后,执行正常操作 * * @param msg 可读数据 * @return 缓存为完整帧 */ private boolean cacheRemainByte(ByteBuf msg) { while (msg.isReadable()) { bytes[index] = msg.readByte(); index++; if (index >= 13) { index = 0; return true; } } return false; }
private static void encode(String portal, int rowCount, ByteBuf out) { int pos = out.writerIndex(); out.writeByte(EXECUTE); out.writeInt(0); if (portal != null) { out.writeCharSequence(portal, StandardCharsets.UTF_8); } out.writeByte(0); out.writeInt(rowCount); // Zero denotes "no limit" maybe for ReadStream<Row> out.setInt(pos + 1, out.writerIndex() - pos - 1); }
public static void writeValue(ByteBuffer bytes, ByteBuf cb) { if (bytes == null) { cb.writeInt(-1); return; } int remaining = bytes.remaining(); cb.writeInt(remaining); if (remaining > 0) cb.writeBytes(bytes.duplicate()); }
private void testBuffers(ByteBuf[] buffers, SerializedField.Builder[] fields) { int i = 0; for (SerializedField.Builder field : fields) { i += fieldBuffersCount(field, buffers, i, buffers.length); } while (i < buffers.length && buffers[i].readableBytes() == 0) { ++ i; } assertEquals(buffers.length, i); for (ByteBuf byteBuf : buffers) { byteBuf.release(); } }
@Override protected void channelRead0(ChannelHandlerContext ctx, FrameMajor msg) throws Exception { FrameMajorHeader head = msg.getHead(); ByteBuf byteBuf = msg.getData(); while (byteBuf.readableBytes() >= FrameSetting.SUB_FRAME_HEAD_LENGTH) { int subMsgId = byteBuf.readByte() & 0xFF; byte[] data = new byte[byteBuf.readShort()]; byteBuf.readBytes(data); server.decodeAndHuntMessage(head, subMsgId, data, ctx.channel()); } }
private void updateFloatSparse(RowType updateRowType, int size, ByteBuf dataBuf, ServerSparseFloatRow row) { switch (updateRowType) { case T_FLOAT_DENSE: updateFloatDenseToFloatSparse(size, dataBuf, row); break; case T_FLOAT_SPARSE: updateFloatSparseToFloatSparse(size, dataBuf, row); break; default: break; } }
@Override public void serialize(ByteBuf buf) { super.serialize(buf); if (rowIndexes != null) { int size = rowIndexes.size(); buf.writeInt(size); for (int i = 0; i < size; i++) { buf.writeInt(rowIndexes.get(i)); } } }
@Override public void toBytes(ByteBuf buf) { buf.writeInt(this.tile.getWorld().provider.getDimension()); buf.writeLong(this.tile.getPos().toLong()); buf.writeInt(this.color); }
@Override public void write( ByteBuf buf ) throws IOException { writeVarInt( entityId, buf ); writeUUID( uuid, buf ); writeVarInt( type, buf ); writeDoubles( buf, x, y, z ); writeBytes( buf, toAngle( yaw ), toAngle( pitch ), toAngle( headPitch ) ); writeShorts( buf, velX, velY, velZ ); entityMetaData.write( buf ); }
private static ByteBuf encodePublishMessage( ByteBufAllocator byteBufAllocator, MqttPublishMessage message) { MqttFixedHeader mqttFixedHeader = message.fixedHeader(); MqttPublishVariableHeader variableHeader = message.variableHeader(); ByteBuf payload = message.payload().duplicate(); String topicName = variableHeader.topicName(); byte[] topicNameBytes = encodeStringUtf8(topicName); int variableHeaderBufferSize = 2 + topicNameBytes.length + (mqttFixedHeader.qosLevel().value() > 0 ? 2 : 0); int payloadBufferSize = payload.readableBytes(); int variablePartSize = variableHeaderBufferSize + payloadBufferSize; int fixedHeaderBufferSize = 1 + getVariableLengthInt(variablePartSize); ByteBuf buf = byteBufAllocator.buffer(fixedHeaderBufferSize + variablePartSize); buf.writeByte(getFixedHeaderByte1(mqttFixedHeader)); writeVariableLengthInt(buf, variablePartSize); buf.writeShort(topicNameBytes.length); buf.writeBytes(topicNameBytes); if (mqttFixedHeader.qosLevel().value() > 0) { buf.writeShort(variableHeader.messageId()); } buf.writeBytes(payload); return buf; }
@Override public List<Object> encode(ByteBufAllocator alloc) { byte cmd = cmd(); int length = FastdfsConstants.FDFS_GROUP_LEN + fileId.pathBytes().length; ByteBuf buf = alloc.buffer(length + FastdfsConstants.FDFS_HEAD_LEN); buf.writeLong(length); buf.writeByte(cmd); buf.writeByte(FastdfsConstants.ERRNO_OK); FastdfsUtils.writeFixLength(buf, fileId.group(), FastdfsConstants.FDFS_GROUP_LEN); ByteBufUtil.writeUtf8(buf, fileId.path()); return Collections.singletonList(buf); }
@Override public void serialize(ByteBuf buf) { super.serialize(buf); if (rowSplit != null) { buf.writeInt(rowSplit.getRowType().getNumber()); rowSplit.serialize(buf); } }
protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception { int i = p_encode_2_.readableBytes(); PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_); if (i < this.treshold) { packetbuffer.writeVarIntToBuffer(0); packetbuffer.writeBytes(p_encode_2_); } else { byte[] abyte = new byte[i]; p_encode_2_.readBytes(abyte); packetbuffer.writeVarIntToBuffer(abyte.length); this.deflater.setInput(abyte, 0, i); this.deflater.finish(); while (!this.deflater.finished()) { int j = this.deflater.deflate(this.buffer); packetbuffer.writeBytes((byte[])this.buffer, 0, j); } this.deflater.reset(); } }
@Override public void success(final Ack ack, final ByteBuf buf) { if (!ack.getOk()) { logger.warn("Remote node {} responded negative on {} request for fragment {} with {}.", endpoint, signal, value, ack); } }
@Override public ResourcePackClientResponsePacket decode(ByteBuf buf) { ResourcePackClientResponsePacket packet = new ResourcePackClientResponsePacket(); packet.setResponse(buf.readByte()); int length = buf.readUnsignedShortLE(); String[] downloading = new String[length]; for (int i=0; i<downloading.length; i++) { downloading[0] = ByteBufUtils.readString(buf); } packet.setDownloading(downloading); return packet; }
@Override public void write( ByteBuf buf ) throws IOException { writeVarInt( action.ordinal(), buf ); writeVarInt( players.size(), buf ); for ( PlayerItem player : players ) { writeUUID( player.uuid, buf ); switch ( action ) { case ADD_PLAYER: writeString( player.name, buf ); writeVarInt( 0, buf ); writeVarInt( player.gameMode.getValue(), buf ); writeVarInt( player.ping, buf ); buf.writeBoolean( player.displayName != null ); if ( player.displayName != null ) { writeString( Flex.getGson().toJson( player.displayName ), buf ); } break; case UPDATE_GAMEMODE: writeVarInt( player.gameMode.getValue(), buf ); break; case UPDATE_PING: writeVarInt( player.ping, buf ); break; case UPDATE_DISPLAY_NAME: buf.writeBoolean( player.displayName != null ); if ( player.displayName != null ) { writeString( Flex.getGson().toJson( player.displayName ), buf ); } break; case REMOVE_PLAYER: // nothing here, but intellij fucks me off when I dont handle this case so here is a pretty useful comment break; } } }
private ByteBuf list(ByteBuf bytes, int start, int length) { final String[] raw = new String[length]; for(int i = 0; i < length; i++) { raw[i] = Byte.toString(bytes.getByte(start + i)); } list("byte", raw); return bytes; }
@Override public void deserialize(ByteBuf buf) { int dim = buf.readInt(); int length = buf.readInt(); Int2IntOpenHashMap data = new Int2IntOpenHashMap(length); IntStream.range(0,length).forEach(i-> data.put(buf.readInt(), buf.readInt())); this.dim = dim; this.hashMap = data; }
/** * 채널로부터 수신된 버퍼에서 data를 발신측에서 보낸 순서대로 Decode하고 <br> * MessageHandler로(pipeline에서 다음 핸들러) 전달할 {@link NetoInboundByteMessage}를 {@link NetoInboundByteMessageBuilder} 를 통해 생성하여 반환한다. * * @param commandCode 커맨드코드 * @param buff 채널로부터 수신되는 버퍼 * @param charset 캐릭터셋 * @return MessageHandler로 전달 시킬 NetoInboundByteMessage */ protected NetoInboundByteMessage decodeData(int commandCode, ByteBuf buff, Charset charset) { NetoInboundByteMessage decodeMessage = null; try { decodeMessage = inboundByteMessageBuilder.create(commandCode, buff); decodeMessage.buildMessage(charset); } catch (Exception e) { decodeMessage = new NetoUnknownInboundByteMessage(e.getMessage(), buff); } return decodeMessage; }
protected static List<InformationEntry<Short>> parseEntries ( final ProtocolOptions options, final byte length, final ByteBuf data, final boolean withTimestamp ) { final List<InformationEntry<Short>> values = new ArrayList<> ( length ); for ( int i = 0; i < length; i++ ) { final InformationObjectAddress address = InformationObjectAddress.parse ( options, data ); final Value<Short> value = TypeHelper.parseScaledValue ( options, data, withTimestamp ); values.add ( new InformationEntry<> ( address, value ) ); } return values; }
protected void cipher(ByteBuf p_150504_1_, ByteBuf p_150504_2_) throws ShortBufferException { int i = p_150504_1_.readableBytes(); byte[] abyte = this.func_150502_a(p_150504_1_); int j = this.cipher.getOutputSize(i); if (this.field_150506_c.length < j) { this.field_150506_c = new byte[j]; } p_150504_2_.writeBytes((byte[])this.field_150506_c, 0, this.cipher.update(abyte, 0, i, this.field_150506_c)); }
@Override public void serialize(ByteBuf buf) { buf.writeInt(matrixId); buf.writeBoolean(updateClock); if (partKey != null) { partKey.serialize(buf); } }
@Override public void toBytes(ByteBuf buf) { buf.writeShort(value); buf.writeBoolean(reload); buf.writeShort(newAmmo); buf.writeBoolean(hand == EnumHand.MAIN_HAND); }
@Override public void readSpawnData(ByteBuf additionalData) // read it on the client { this.ownerX = additionalData.readDouble(); this.ownerY = additionalData.readDouble(); this.ownerZ = additionalData.readDouble(); }
/** * 对于业务层直接发送的bytebuf实例将其转换为websocket消息 */ @Override protected void encode(ChannelHandlerContext paramChannelHandlerContext, ByteBuf paramOUTBOUND_IN, List<Object> paramList) throws Exception { paramList.add(new BinaryWebSocketFrame(paramOUTBOUND_IN)); paramOUTBOUND_IN.retain(); }
private static Result<MqttSubAckPayload> decodeSubackPayload( ByteBuf buffer, int bytesRemainingInVariablePart) { final List<Integer> grantedQos = new ArrayList<Integer>(); int numberOfBytesConsumed = 0; while (numberOfBytesConsumed < bytesRemainingInVariablePart) { int qos = buffer.readUnsignedByte() & 0x03; numberOfBytesConsumed++; grantedQos.add(qos); } return new Result<MqttSubAckPayload>(new MqttSubAckPayload(grantedQos), numberOfBytesConsumed); }
@Override public void toBytes(ByteBuf buf) { buf.writeInt(this.entityID); buf.writeBoolean(this.hasArmorUpgrade); buf.writeBoolean(this.hasWeaponUpgrade); buf.writeBoolean(this.hasRidingUpgrade); buf.writeBoolean(this.hasPlatingUpgrade); buf.writeBoolean(this.hasCommunicationUpgrade); }
@Override public OptionalInt extractResponseSequenceId(ByteBuf buffer) { if (buffer.readableBytes() < HEADER_SEQUENCE_ID_OFFSET + Integer.BYTES) { return OptionalInt.empty(); } return OptionalInt.of(buffer.getInt(buffer.readerIndex() + HEADER_SEQUENCE_ID_OFFSET)); }
@Override public void toBytes(ByteBuf buf) { buf.writeInt(this.x); buf.writeInt(this.y); buf.writeInt(this.z); buf.writeInt(generationTimer); buf.writeInt(generationTimerDefault); buf.writeLong(energy); }