@Override
    public void write(ByteBuf bb, OFFlowStatsEntryVer10 message) {
      int startIndex = bb.writerIndex();
      // length is length of variable message, will be updated at the end
      int lengthIndex = bb.writerIndex();
      bb.writeShort(U16.t(0));

      message.tableId.writeByte(bb);
      // pad: 1 bytes
      bb.writeZero(1);
      message.match.writeTo(bb);
      bb.writeInt(U32.t(message.durationSec));
      bb.writeInt(U32.t(message.durationNsec));
      bb.writeShort(U16.t(message.priority));
      bb.writeShort(U16.t(message.idleTimeout));
      bb.writeShort(U16.t(message.hardTimeout));
      // pad: 6 bytes
      bb.writeZero(6);
      bb.writeLong(message.cookie.getValue());
      bb.writeLong(message.packetCount.getValue());
      bb.writeLong(message.byteCount.getValue());
      ChannelUtils.writeList(bb, message.actions);

      // update length field
      int length = bb.writerIndex() - startIndex;
      bb.setShort(lengthIndex, length);
    }
 private ByteBuf encodeResponse(ResponseSocketBlock resMsg) {
   ByteBuf bodyBuf = ByteBufAllocator.DEFAULT.heapBuffer();
   //
   // * --------------------------------------------------------bytes =8
   // * byte[2]  status                               响应状态
   bodyBuf.writeShort(resMsg.getStatus());
   // * byte[2]  serializeType-(attr-index)           序列化策略
   bodyBuf.writeShort(resMsg.getSerializeType());
   // * byte[2]  returnType-(attr-index)              返回类型
   bodyBuf.writeShort(resMsg.getReturnType());
   // * byte[2]  returnData-(attr-index)              返回数据
   bodyBuf.writeShort(resMsg.getReturnData());
   // * --------------------------------------------------------bytes =1 ~ 1021
   // * byte[1]  optionCount                          选项参数总数
   int[] optionMapping = resMsg.getOptions();
   bodyBuf.writeByte(optionMapping.length);
   for (int i = 0; i < optionMapping.length; i++) {
     // * byte[4]  ptype-0-(attr-index,attr-index)  选项参数1
     // * byte[4]  ptype-1-(attr-index,attr-index)  选项参数2
     bodyBuf.writeInt(optionMapping[i]);
   }
   // * --------------------------------------------------------bytes =6 ~ 8192
   // * byte[2]  attrPool-size (Max = 2047)           池大小 0x07FF
   int[] poolData = resMsg.getPoolData();
   bodyBuf.writeShort(poolData.length);
   for (int i = 0; i < poolData.length; i++) {
     // * byte[4]  ptype-0-(attr-index,attr-index)  属性1大小
     // * byte[4]  ptype-1-(attr-index,attr-index)  属性2大小
     bodyBuf.writeInt(poolData[i]);
   }
   // * --------------------------------------------------------bytes =n
   // * dataBody                                      数据内容
   resMsg.fillTo(bodyBuf);
   return bodyBuf;
 }
 @Test
 public void testDecode() {
   ByteBuf buffer = Unpooled.buffer();
   // header
   buffer.writeByte(0);
   buffer.writeShort(1);
   buffer.writeByte(Integer.valueOf(240).byteValue());
   buffer.writeInt(44);
   buffer.writeLong(1);
   buffer.writeLong(2);
   // attributes
   buffer.writeShort(4);
   buffer.writeInt(4);
   buffer.writeBytes("luo!".getBytes());
   buffer.writeShort(5);
   buffer.writeInt(4);
   buffer.writeBytes("luo!".getBytes());
   MockRelayMessage message =
       (MockRelayMessage) MessageFactory.getInstance().createMessage(buffer);
   Assert.assertEquals(message.version(), GenericMessage.VERSION);
   Assert.assertEquals(message.length(), Unsigned32.get(44L));
   Assert.assertEquals(message.flag().get().isGroup(), true);
   Assert.assertEquals(message.flag().get().isRequest(), true);
   Assert.assertEquals(message.flag().get().isProxiable(), true);
   Assert.assertEquals(message.flag().get().isError(), true);
   assertEquals(message.code(), Unsigned16.get(1));
   assertEquals(message.hopByHop(), Integer64.get(1L));
   assertEquals(message.endToEnd(), Integer64.get(2L));
   Assert.assertEquals(message.attribute(Unsigned16.get(4)).length(), Unsigned32.get(4L));
   assertEquals(message.attribute(Unsigned16.get(4)).data().get(), "luo!");
   Assert.assertEquals(message.attribute(Unsigned16.get(5)).length(), Unsigned32.get(4L));
   assertEquals(message.attribute(Unsigned16.get(5)).data().get(), "luo!");
 }
 /**
  * Serialize an object into a given byte buffer.
  *
  * @param o The object to serialize.
  * @param b The bytebuf to serialize it into.
  */
 @Override
 public void serialize(Object o, ByteBuf b) {
   String className = o == null ? "null" : o.getClass().getName();
   if (className.contains("$ByteBuddy$")) {
     String SMRClass = className.split("\\$")[0];
     className = "CorfuObject";
     byte[] classNameBytes = className.getBytes();
     b.writeShort(classNameBytes.length);
     b.writeBytes(classNameBytes);
     byte[] SMRClassNameBytes = SMRClass.getBytes();
     b.writeShort(SMRClassNameBytes.length);
     b.writeBytes(SMRClassNameBytes);
     UUID id = ((ICorfuObject) o).getStreamID();
     log.trace("Serializing a CorfuObject of type {} as a stream pointer to {}", SMRClass, id);
     b.writeLong(id.getMostSignificantBits());
     b.writeLong(id.getLeastSignificantBits());
   } else {
     byte[] classNameBytes = className.getBytes();
     b.writeShort(classNameBytes.length);
     b.writeBytes(classNameBytes);
     if (o == null) {
       return;
     }
     try (ByteBufOutputStream bbos = new ByteBufOutputStream(b)) {
       try (OutputStreamWriter osw = new OutputStreamWriter(bbos)) {
         gson.toJson(o, o.getClass(), osw);
       }
     } catch (IOException ie) {
       log.error("Exception during serialization!", ie);
     }
   }
 }
 @Override
 public void write(ByteBuf bb, OFBsnTlvStatusVer13 message) {
   // fixed value property type = 0x61
   bb.writeShort((short) 0x61);
   // fixed value property length = 5
   bb.writeShort((short) 0x5);
   OFBsnStatusSerializerVer13.writeTo(bb, message.value);
 }
 @Override
 public void write(ByteBuf bb, OFBsnTlvMissPacketsVer13 message) {
   // fixed value property type = 0xd
   bb.writeShort((short) 0xd);
   // fixed value property length = 12
   bb.writeShort((short) 0xc);
   bb.writeLong(message.value.getValue());
 }
 @Override
 public void write(ByteBuf bb, OFActionCopyTtlInVer11 message) {
   // fixed value property type = 12
   bb.writeShort((short) 0xc);
   // fixed value property length = 8
   bb.writeShort((short) 0x8);
   // pad: 4 bytes
   bb.writeZero(4);
 }
 public void writeData(ByteBuf data) {
   data.writeByte(getDataTypeID());
   data.writeShort(id);
   data.writeShort(getDataFlags());
   data.writeByte(getDataSides());
   data.writeFloat(dX);
   data.writeFloat(dY);
   data.writeFloat(dZ);
 }
 @Override
 public void write(ByteBuf bb, OFActionSetDlSrcVer10 message) {
   // fixed value property type = 4
   bb.writeShort((short) 0x4);
   // fixed value property length = 16
   bb.writeShort((short) 0x10);
   message.dlAddr.write6Bytes(bb);
   // pad: 6 bytes
   bb.writeZero(6);
 }
 @Override
 public void write(ByteBuf bb, OFInstructionIdBsnAutoNegotiationVer13 message) {
   // fixed value property type = 65535
   bb.writeShort((short) 0xffff);
   // fixed value property length = 12
   bb.writeShort((short) 0xc);
   // fixed value property experimenter = 0x5c16c7L
   bb.writeInt(0x5c16c7);
   // fixed value property subtype = 0xbL
   bb.writeInt(0xb);
 }
  @Override
  protected void encode(
      ChannelHandlerContext channelHandlerContext, ByteBuf responseBuf, ByteBuf fullResponse)
      throws Exception {

    fullResponse.writeByte(NetConst.NET_HEAD1); // 头
    fullResponse.writeShort(responseBuf.readableBytes() + 3); // 2 for 包号 | 3 for token ,foot
    fullResponse.writeBytes(responseBuf);

    fullResponse.writeShort(NetConst.NET_TOKEN);
    fullResponse.writeByte(NetConst.NET_FOOT);
  }
Beispiel #12
0
  public static void writeItemstack(ItemStack item, ByteBuf out) {
    if (item == null || item.id == 0) {
      out.writeShort(-1);
      return;
    }

    out.writeShort(item.id);
    out.writeByte(item.count);
    out.writeShort(item.data);

    out.writeShort(-1); // TODO NBT data length.
    // out.writeBytes(null); Data byte array.
  }
  @Override
  public void toBytes(final ByteBuf stream) {
    if (this.embeddedPacket != null) {
      // Write the id
      short id = NetworkHandler.getPacketID(this.embeddedPacket);
      stream.writeShort(id);

      // Call embedded
      this.embeddedPacket.toBytes(stream);
    } else {
      // Write -1
      stream.writeShort(-1);
    }
  }
 @Override
 public void write(ByteBuf bb, OFMeterFeaturesStatsReplyVer14 message) {
   // fixed value property version = 5
   bb.writeByte((byte) 0x5);
   // fixed value property type = 19
   bb.writeByte((byte) 0x13);
   // fixed value property length = 32
   bb.writeShort((short) 0x20);
   bb.writeInt(U32.t(message.xid));
   // fixed value property statsType = 11
   bb.writeShort((short) 0xb);
   OFStatsReplyFlagsSerializerVer14.writeTo(bb, message.flags);
   // pad: 4 bytes
   bb.writeZero(4);
   message.features.writeTo(bb);
 }
 private static void writeLengthField(int version, ByteBuf buffer, int length) {
   if (version < 3) {
     buffer.writeShort(length);
   } else {
     buffer.writeInt(length);
   }
 }
 /**
  * Writes unsigned 16-bit short integer <code>value</code> if not null, otherwise writes zeros to
  * the <code>output</code> ByteBuf. ByteBuf's writerIndex is increased by 2.
  *
  * @param value Integer value to be written to the output.
  * @param output ByteBuf, where value or zeros are written.
  */
 public static void writeUnsignedShort(final Integer value, final ByteBuf output) {
   if (value != null) {
     output.writeShort(value.shortValue());
   } else {
     output.writeZero(SHORT_BYTES_LENGTH);
   }
 }
 /**
  * Writes 16-bit short <code>value</code> if not null, otherwise writes zeros to the <code>output
  * </code> ByteBuf. ByteBuf's writerIndex is increased by 2.
  *
  * @param value Short value to be written to the output.
  * @param output ByteBuf, where value or zeros are written.
  */
 public static void writeShort(final Short value, final ByteBuf output) {
   if (value != null) {
     output.writeShort(value);
   } else {
     output.writeZero(SHORT_BYTES_LENGTH);
   }
 }
Beispiel #18
0
  @Override
  protected void encode(ChannelHandlerContext chc, SubscribeMessage message, ByteBuf out) {
    if (message.subscriptions().isEmpty()) {
      throw new IllegalArgumentException("Found a subscribe message with empty topics");
    }

    if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) {
      throw new IllegalArgumentException(
          "Expected a message with QOS 1, found " + message.getQos());
    }

    ByteBuf variableHeaderBuff = chc.alloc().buffer(4);
    ByteBuf buff = null;
    try {
      variableHeaderBuff.writeShort(message.getMessageID());
      for (SubscribeMessage.Couple c : message.subscriptions()) {
        variableHeaderBuff.writeBytes(Utils.encodeString(c.topicFilter));
        variableHeaderBuff.writeByte(c.qos);
      }

      int variableHeaderSize = variableHeaderBuff.readableBytes();
      byte flags = Utils.encodeFlags(message);
      buff = chc.alloc().buffer(2 + variableHeaderSize);

      buff.writeByte(AbstractMessage.SUBSCRIBE << 4 | flags);
      buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
      buff.writeBytes(variableHeaderBuff);

      out.writeBytes(buff);
    } finally {
      variableHeaderBuff.release();
      buff.release();
    }
  }
Beispiel #19
0
  @Override
  protected void encode(ChannelHandlerContext ctx, OnDemandResponse response, List<Object> out) {
    FileDescriptor descriptor = response.getFileDescriptor();
    int fileSize = response.getFileSize();
    int chunkId = response.getChunkId();
    ByteBuf chunkData = response.getChunkData();

    ByteBuf buffer = ctx.alloc().buffer(6 + chunkData.readableBytes());
    buffer.writeByte(descriptor.getType() - 1);
    buffer.writeShort(descriptor.getFile());
    buffer.writeShort(fileSize);
    buffer.writeByte(chunkId);
    buffer.writeBytes(chunkData);

    out.add(buffer);
  }
  @Override
  protected void encode(ChannelHandlerContext ctx, GamePacket msg, List<Object> out) {
    PacketType type = msg.getType();
    int headerLength = 1;
    int payloadLength = msg.getLength();

    if (type == PacketType.VARIABLE_BYTE) {
      headerLength++;
      if (payloadLength >= 256) {
        throw new IllegalStateException("Payload too long for variable byte packet");
      }
    } else if (type == PacketType.VARIABLE_SHORT) {
      headerLength += 2;
      if (payloadLength >= 65536) {
        throw new IllegalStateException("Payload too long for variable short packet");
      }
    }

    ByteBuf buffer = Unpooled.buffer(headerLength + payloadLength);
    buffer.writeByte((msg.getOpcode() + random.nextInt()) & 0xFF);

    if (type == PacketType.VARIABLE_BYTE) {
      buffer.writeByte(payloadLength);
    } else if (type == PacketType.VARIABLE_SHORT) {
      buffer.writeShort(payloadLength);
    }

    out.add(buffer.writeBytes(msg.getPayload()));
  }
Beispiel #21
0
 /**
  * Puts a smart into the buffer.
  *
  * @param value The value.
  */
 public void putSmart(int value) {
   checkByteAccess();
   if (value < 128) {
     buffer.writeByte(value);
   } else {
     buffer.writeShort(value);
   }
 }
 @Override
 public void write(ByteBuf bb, OFPortStatsRequestVer13 message) {
   // fixed value property version = 4
   bb.writeByte((byte) 0x4);
   // fixed value property type = 18
   bb.writeByte((byte) 0x12);
   // fixed value property length = 24
   bb.writeShort((short) 0x18);
   bb.writeInt(U32.t(message.xid));
   // fixed value property statsType = 4
   bb.writeShort((short) 0x4);
   OFStatsRequestFlagsSerializerVer13.writeTo(bb, message.flags);
   // pad: 4 bytes
   bb.writeZero(4);
   message.portNo.write4Bytes(bb);
   // pad: 4 bytes
   bb.writeZero(4);
 }
 @Override
 public void marshallMessage(ByteBuf cb) {
   cb.writeInt(slaveServerId);
   MysqlAPIUtils.putLengthCodedString(cb, reportHost, true /* codeNullasZero */);
   MysqlAPIUtils.putLengthCodedString(cb, reportUser, true /* codeNullasZero */);
   MysqlAPIUtils.putLengthCodedString(cb, reportPassword, true /* codeNullasZero */);
   cb.writeShort(reportPort);
   cb.writeZero(8);
 }
Beispiel #24
0
  public static void writeVarShort(ByteBuf buf, int toWrite) {
    int low = toWrite & 0x7FFF;
    int high = (toWrite & 0x7F8000) >> 15;

    if (high != 0) low = low | 0x8000;

    buf.writeShort(low);

    if (high != 0) buf.writeByte(high);
  }
 @Override
 public void serialize(FlowRemovedMessage message, ByteBuf outBuffer) {
   ByteBufUtils.writeOFHeader(MESSAGE_TYPE, message, outBuffer, EncodeConstants.EMPTY_LENGTH);
   outBuffer.writeLong(message.getCookie().longValue());
   outBuffer.writeShort(message.getPriority());
   outBuffer.writeByte(message.getReason().getIntValue());
   outBuffer.writeByte(message.getTableId().getValue().byteValue());
   outBuffer.writeInt(message.getDurationSec().intValue());
   outBuffer.writeInt(message.getDurationNsec().intValue());
   outBuffer.writeShort(message.getIdleTimeout());
   outBuffer.writeShort(message.getHardTimeout());
   outBuffer.writeLong(message.getPacketCount().longValue());
   outBuffer.writeLong(message.getByteCount().longValue());
   OFSerializer<Match> matchSerializer =
       registry.<Match, OFSerializer<Match>>getSerializer(
           new MessageTypeKey<>(message.getVersion(), Match.class));
   matchSerializer.serialize(message.getMatch(), outBuffer);
   ByteBufUtils.updateOFHeaderLength(outBuffer);
 }
  @Override
  public void encode(ByteBuf buf) {
    Codec.writeVarInt32(buf, this.entityId);

    buf.writeInt((int) this.location.getX() * 32);
    buf.writeInt((int) this.location.getY() * 32);
    buf.writeInt((int) this.location.getZ() * 32);

    buf.writeShort((int) this.count);
  }
 @Override
 public void write(ByteBuf out) {
   out.writeInt(worldId);
   out.writeInt(chunk.xPosition);
   out.writeInt(chunk.zPosition);
   out.writeInt(pos.x);
   out.writeShort(pos.y);
   out.writeInt(pos.z);
   out.writeBytes(chunk.getBiomeArray());
 }
  private void initHeaderQos(ByteBuf buff, int messageID, AbstractMessage.QOSType... qoss)
      throws IllegalAccessException {
    buff.clear()
        .writeByte(AbstractMessage.SUBACK << 4)
        .writeBytes(Utils.encodeRemainingLength(2 + qoss.length));

    buff.writeShort(messageID);
    for (AbstractMessage.QOSType qos : qoss) {
      buff.writeByte(qos.ordinal());
    }
  }
  @Override
  public ByteBuf encode() {
    ByteBuf buf = Unpooled.buffer(calculateLength());
    buf.writeByte(getFunctionCode());
    buf.writeByte(byteCount);

    for (int i = 0; i < registers.length; i++) {
      buf.writeShort(registers[i]);
    }

    return buf;
  }
    @Override
    public void write(ByteBuf bb, OFFlowModFailedErrorMsgVer10 message) {
      int startIndex = bb.writerIndex();
      // fixed value property version = 1
      bb.writeByte((byte) 0x1);
      // fixed value property type = 1
      bb.writeByte((byte) 0x1);
      // length is length of variable message, will be updated at the end
      int lengthIndex = bb.writerIndex();
      bb.writeShort(U16.t(0));

      bb.writeInt(U32.t(message.xid));
      // fixed value property errType = 3
      bb.writeShort((short) 0x3);
      OFFlowModFailedCodeSerializerVer10.writeTo(bb, message.code);
      message.data.writeTo(bb);

      // update length field
      int length = bb.writerIndex() - startIndex;
      bb.setShort(lengthIndex, length);
    }