public void encodeAsByteBuf(ByteBuf var1) {
   var1.writeByte(SUBNEGOTIATION_VERSION.byteValue());
   var1.writeByte(this.username.length());
   var1.writeBytes(this.username.getBytes(CharsetUtil.US_ASCII));
   var1.writeByte(this.password.length());
   var1.writeBytes(this.password.getBytes(CharsetUtil.US_ASCII));
 }
Example #2
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();
    }
  }
  @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()));
  }
Example #4
0
  public ByteBuf encode(NettyMessage msg) throws Exception {
    ByteBuf sendBuf = Unpooled.buffer();
    sendBuf.writeInt((msg.getHeader().getCrcCode()));
    sendBuf.writeInt((msg.getHeader().getLength()));
    sendBuf.writeLong((msg.getHeader().getSessionID()));
    sendBuf.writeByte((msg.getHeader().getType()));
    sendBuf.writeByte((msg.getHeader().getPriority()));
    sendBuf.writeInt((msg.getHeader().getAttachment().size()));
    String key = null;
    byte[] keyArray = null;
    Object value = null;

    for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) {
      key = param.getKey();
      keyArray = key.getBytes("UTF-8");
      sendBuf.writeInt(keyArray.length);
      sendBuf.writeBytes(keyArray);
      value = param.getValue();
      marshallingEncoder.encode(value, sendBuf);
    }
    key = null;
    keyArray = null;
    value = null;
    if (msg.getBody() != null) {
      marshallingEncoder.encode(msg.getBody(), sendBuf);
    } else sendBuf.writeInt(0);
    sendBuf.setInt(4, sendBuf.readableBytes());
    return sendBuf;
  }
 @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!");
 }
 private static void encodeHeader(ByteBuf buf, String header, String value) {
   buf.writeBytes(header.getBytes(CharsetUtil.US_ASCII));
   buf.writeByte(COLON);
   buf.writeByte(SP);
   buf.writeBytes(value.getBytes(CharsetUtil.US_ASCII));
   buf.writeByte(CR);
   buf.writeByte(LF);
 }
Example #7
0
 /**
  * Puts a string into the buffer.
  *
  * @param str The string.
  */
 public void putString(String str) {
   checkByteAccess();
   char[] chars = str.toCharArray();
   for (char c : chars) {
     buffer.writeByte((byte) c);
   }
   buffer.writeByte(0);
 }
Example #8
0
 public ByteBuf encode(ByteBuf buf, BlockChangeMessage message) throws IOException {
   buf.writeInt(message.getX());
   buf.writeByte(message.getY());
   buf.writeInt(message.getZ());
   ByteBufUtils.writeVarInt(buf, message.getType());
   buf.writeByte(message.getMetadata());
   return buf;
 }
 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 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 toBytes(ByteBuf buf) {
   buf.writeInt(x);
   buf.writeInt(y);
   buf.writeInt(z);
   buf.writeByte(orientation);
   buf.writeByte(state);
   buf.writeInt(customName.length());
   buf.writeBytes(customName.getBytes());
   buf.writeInt(owner.length());
   buf.writeBytes(owner.getBytes());
 }
Example #12
0
  @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);
  }
 void write(ByteBuf out) {
   out.writeByte(minX);
   out.writeByte(minY);
   out.writeByte(minZ);
   out.writeByte(maxX);
   out.writeByte(maxY);
   out.writeByte(maxZ);
   out.writeShort(Block.getIdFromBlock(icon_id));
   out.writeByte(icon_md);
   out.writeByte(icon_side);
   quat.write(out);
 }
Example #14
0
 @Override
 public void toBytes(ByteBuf buf) {
   super.toBytes(buf);
   if (mat != null) {
     buf.writeByte(0);
     buf.writeByte(mat.ordinal());
   } else if (enchant >= 0) {
     buf.writeByte(1);
     buf.writeShort(enchant);
   } else {
     buf.writeByte(2);
   }
 }
 private void processUtf8(ByteBuf in, ByteBuf out, boolean jsonpMode) {
   while (in.isReadable()) {
     short value = (short) (in.readByte() & 0xFF);
     if (value >>> 7 == 0) {
       if (jsonpMode && (value == '\\' || value == '\'')) {
         out.writeByte('\\');
       }
       out.writeByte(value);
     } else {
       out.writeByte(((value >>> 6) | 0xC0));
       out.writeByte(((value & 0x3F) | 0x80));
     }
   }
 }
Example #16
0
  @Override
  public void writeBytes(ByteBuf bytes) {
    width = array[0].length;
    height = array.length;

    bytes.writeByte(width);
    bytes.writeByte(height);

    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {
        bytes.writeByte(array[y][x]);
      }
    }
  }
Example #17
0
 @Override
 protected void encode(ChannelHandlerContext ctx, Event event, List<Object> out) throws Exception {
   ByteBuf msg = null;
   if (null != event.getSource()) {
     LOG.trace("Event class: {}", event.getClass());
     ByteBuf buf = ctx.alloc().buffer(1);
     buf.writeByte(event.getType());
     msg = Unpooled.wrappedBuffer(buf, Unpooled.wrappedBuffer(msgPack.write(event.getSource())));
   } else {
     msg = ctx.alloc().buffer(1);
     msg.writeByte(event.getType());
   }
   out.add(msg);
 }
Example #18
0
  @Override
  public void toBytes(ByteBuf buf) {
    buf.writeInt(posX);
    buf.writeInt(posY);
    buf.writeInt(posZ);
    buf.writeInt(data.size());

    for (int i = 0; i < data.size(); i++) {
      Object obj = data.get(i);
      if (obj instanceof Character) {
        buf.writeByte(0x00);
        buf.writeChar((Character) obj);
      } else if (obj instanceof String) {
        buf.writeByte(0x01);
        writeString(buf, (String) obj);
      } else if (obj instanceof Float) {
        buf.writeByte(0x02);
        buf.writeFloat((Float) obj);
      } else if (obj instanceof Double) {
        buf.writeByte(0x03);
        buf.writeDouble((Double) obj);
      } else if (obj instanceof Byte) {
        buf.writeByte(0x04);
        buf.writeByte((Byte) obj);
      } else if (obj instanceof Long) {
        buf.writeByte(0x05);
        buf.writeLong((Long) obj);
      } else {
        buf.writeByte(0x0F);
        buf.writeInt((Integer) obj);
      }
    }
  }
Example #19
0
  @Override
  public void writeData(ByteBuf data) {
    super.writeData(data);

    ByteBuf tmpState = Unpooled.buffer();

    tmpState.writeByte(stateList.size());
    for (StateWithId stateWithId : stateList) {
      tmpState.writeByte(stateWithId.stateId);
      stateWithId.state.writeData(tmpState);
    }

    data.writeInt(tmpState.readableBytes());
    data.writeBytes(tmpState.readBytes(tmpState.readableBytes()));
  }
 @Override
 public void write(ByteBuf bb, OFBsnBwEnableSetRequestVer11 message) {
   // fixed value property version = 2
   bb.writeByte((byte) 0x2);
   // fixed value property type = 4
   bb.writeByte((byte) 0x4);
   // fixed value property length = 20
   bb.writeShort((short) 0x14);
   bb.writeInt(U32.t(message.xid));
   // fixed value property experimenter = 0x5c16c7L
   bb.writeInt(0x5c16c7);
   // fixed value property subtype = 0x12L
   bb.writeInt(0x12);
   bb.writeInt(U32.t(message.enable));
 }
Example #21
0
 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;
 }
Example #22
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);
  }
Example #23
0
 public MsgEchoPeerHandler(final int messageSize) {
   final ByteBuf byteBuf = Unpooled.buffer(messageSize);
   for (int i = 0; i < byteBuf.capacity(); i++) {
     byteBuf.writeByte((byte) i);
   }
   message = new UdtMessage(byteBuf);
 }
  @Override
  protected void encode(ChannelHandlerContext ctx, TransportFrame frame, ByteBuf out)
      throws Exception {
    out.writeByte('E');
    out.writeByte('Q');
    out.writeInt(frame.version().id);
    out.writeLong(frame.request());

    if (frame instanceof StreamableTransportFrame) {
      // message request
      // skip size header
      int sizePos = out.writerIndex();
      out.writerIndex(out.writerIndex() + 4);
      try (StreamOutput output = streamService.output(out)) {
        Streamable message = ((StreamableTransportFrame) frame).message();
        output.writeClass(message.getClass());
        output.writeStreamable(message);
      }
      int size = out.writerIndex() - sizePos - 4;
      out.setInt(sizePos, size);
    } else {
      // ping request
      out.writeInt(0);
    }
  }
 /** Creates a client-side handler. */
 public EchoClientHandler() {
   firstMessage = Unpooled.buffer(EchoClient.SIZE);
   for (int i = 0; i < firstMessage.capacity(); i++) {
     firstMessage.writeByte((byte) i);
   }
   System.out.println(firstMessage.toString());
 }
 @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);
 }
Example #27
0
 public ByteEchoPeerHandler(final int messageSize) {
   super(false);
   message = Unpooled.buffer(messageSize);
   for (int i = 0; i < message.capacity(); i++) {
     message.writeByte((byte) i);
   }
 }
Example #28
0
 public ByteBuf write(ByteBuf buffer) {
   int size = calcPacketSize();
   BufferUtil.writeUB3(buffer, size);
   buffer.writeByte(packetId);
   writeBody(buffer);
   return buffer;
 }
  // api
  public PacketMatterCannon(double x, double y, double z, float dx, float dy, float dz, byte len) {
    float dl = dx * dx + dy * dy + dz * dz;
    float dlz = (float) Math.sqrt(dl);

    this.x = x;
    this.y = y;
    this.z = z;
    this.dx = dx / dlz;
    this.dy = dy / dlz;
    this.dz = dz / dlz;
    this.len = len;

    ByteBuf data = Unpooled.buffer();

    data.writeInt(this.getPacketID());
    data.writeFloat((float) x);
    data.writeFloat((float) y);
    data.writeFloat((float) z);
    data.writeFloat((float) this.dx);
    data.writeFloat((float) this.dy);
    data.writeFloat((float) this.dz);
    data.writeByte(len);

    this.configureWrite(data);
  }
Example #30
0
 protected void writeContent(StompFrame frame, ByteBuf buffer) {
   if (frame instanceof StompContentFrame) {
     ByteBuf content = ((StompContentFrame) frame).content();
     buffer.writeBytes(content);
   }
   buffer.writeByte(NULL);
 }