/**
  * Deserialize an object from a given byte buffer.
  *
  * @param b The bytebuf to deserialize.
  * @return The deserialized object.
  */
 @Override
 public Object deserialize(ByteBuf b, CorfuRuntime rt) {
   int classNameLength = b.readShort();
   byte[] classNameBytes = new byte[classNameLength];
   b.readBytes(classNameBytes, 0, classNameLength);
   String className = new String(classNameBytes);
   if (className.equals("null")) {
     return null;
   } else if (className.equals("CorfuObject")) {
     int SMRClassNameLength = b.readShort();
     byte[] SMRClassNameBytes = new byte[SMRClassNameLength];
     b.readBytes(SMRClassNameBytes, 0, SMRClassNameLength);
     String SMRClassName = new String(SMRClassNameBytes);
     try {
       return rt.getObjectsView()
           .build()
           .setStreamID(new UUID(b.readLong(), b.readLong()))
           .setType(Class.forName(SMRClassName))
           .open();
     } catch (ClassNotFoundException cnfe) {
       log.error("Exception during deserialization!", cnfe);
       throw new RuntimeException(cnfe);
     }
   } else {
     try (ByteBufInputStream bbis = new ByteBufInputStream(b)) {
       try (InputStreamReader r = new InputStreamReader(bbis)) {
         return gson.fromJson(r, Class.forName(className));
       }
     } catch (IOException | ClassNotFoundException ie) {
       log.error("Exception during deserialization!", ie);
       throw new RuntimeException(ie);
     }
   }
 }
 @Override
 public void decodeInto(ByteBuf buffer) {
   long most = buffer.readLong();
   long least = buffer.readLong();
   this.playerUUID = new UUID(most, least);
   this.dim = buffer.readInt();
   this.tag = ByteBufUtils.readTag(buffer);
 }
Example #3
0
  @Override
  public void readSpawnData(ByteBuf buffer) {
    spiderType = EnumSpiderType.byId(buffer.readInt());

    try {
      owner = new UUID(buffer.readLong(), buffer.readLong());
    } catch (IndexOutOfBoundsException e) {
      // Ignore.
    }
  }
    @Override
    public OFFlowStatsEntry readFrom(ByteBuf bb) throws OFParseError {
      int start = bb.readerIndex();
      int length = U16.f(bb.readShort());
      if (length < MINIMUM_LENGTH)
        throw new OFParseError(
            "Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length);
      if (bb.readableBytes() + (bb.readerIndex() - start) < length) {
        // Buffer does not have all data yet
        bb.readerIndex(start);
        return null;
      }
      if (logger.isTraceEnabled()) logger.trace("readFrom - length={}", length);
      TableId tableId = TableId.readByte(bb);
      // pad: 1 bytes
      bb.skipBytes(1);
      long durationSec = U32.f(bb.readInt());
      long durationNsec = U32.f(bb.readInt());
      int priority = U16.f(bb.readShort());
      int idleTimeout = U16.f(bb.readShort());
      int hardTimeout = U16.f(bb.readShort());
      Set<OFFlowModFlags> flags = OFFlowModFlagsSerializerVer14.readFrom(bb);
      int importance = U16.f(bb.readShort());
      // pad: 2 bytes
      bb.skipBytes(2);
      U64 cookie = U64.ofRaw(bb.readLong());
      U64 packetCount = U64.ofRaw(bb.readLong());
      U64 byteCount = U64.ofRaw(bb.readLong());
      Match match = ChannelUtilsVer14.readOFMatch(bb);
      List<OFInstruction> instructions =
          ChannelUtils.readList(bb, length - (bb.readerIndex() - start), OFInstructionVer14.READER);

      OFFlowStatsEntryVer14 flowStatsEntryVer14 =
          new OFFlowStatsEntryVer14(
              tableId,
              durationSec,
              durationNsec,
              priority,
              idleTimeout,
              hardTimeout,
              flags,
              importance,
              cookie,
              packetCount,
              byteCount,
              match,
              instructions);
      if (logger.isTraceEnabled()) logger.trace("readFrom - read={}", flowStatsEntryVer14);
      return flowStatsEntryVer14;
    }
Example #5
0
  @Override
  public void fromBytes(ByteBuf buf) {
    posX = buf.readInt();
    posY = buf.readInt();
    posZ = buf.readInt();
    int size = buf.readInt();

    data = new ArrayList(size);
    for (int i = 0; i < size; i++) {
      byte tag = buf.readByte();
      if (tag == 0x00) {
        data.add(buf.readChar());
      } else if (tag == 0x01) {
        data.add(readString(buf));
      } else if (tag == 0x02) {
        data.add(buf.readFloat());
      } else if (tag == 0x03) {
        data.add(buf.readDouble());
      } else if (tag == 0x04) {
        data.add(buf.readByte());
      } else if (tag == 0x05) {
        data.add(buf.readLong());
      } else {
        data.add(buf.readInt());
      }
    }
  }
  @Override
  protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    // TODO Auto-generated method stub
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
      return null;
    }

    Message message = new Message();
    Header header = new Header();

    header.setSrcCode(in.readInt());
    header.setLength(in.readInt());
    header.setSessionId(in.readLong());
    header.setType(in.readByte());
    header.setPriority(in.readByte());
    int size = in.readInt();
    if (size > 0) {
      Map<String, Object> attch = new HashMap<String, Object>(size);
      int keySize = 0;
      byte[] keyArray = null;
      String key = null;
      for (int i = 0; i < size; i++) {
        keySize = in.readInt();
        keyArray = new byte[keySize];
        in.readBytes(keyArray);
        key = new String(keyArray, "UTF-8");
        attch.put(key, nettyMarshallingDecoder.decode(ctx, in));
      }
      keyArray = null;
      key = null;
      header.setAttachment(attch);
    }
    return message;
  }
Example #7
0
  public NettyMessage decode(ByteBuf in) throws Exception {
    NettyMessage message = new NettyMessage();
    Header header = new Header();
    header.setCrcCode(in.readInt());
    header.setLength(in.readInt());
    header.setSessionID(in.readLong());
    header.setType(in.readByte());
    header.setPriority(in.readByte());

    int size = in.readInt();
    if (size > 0) {
      Map<String, Object> attch = new HashMap<String, Object>(size);
      int keySize = 0;
      byte[] keyArray = null;
      String key = null;
      for (int i = 0; i < size; i++) {
        keySize = in.readInt();
        keyArray = new byte[keySize];
        in.readBytes(keyArray);
        key = new String(keyArray, "UTF-8");
        attch.put(key, marshallingDecoder.decode(in));
      }
      keyArray = null;
      key = null;
      header.setAttachment(attch);
    }
    if (in.readableBytes() > 4) {
      message.setBody(marshallingDecoder.decode(in));
    }
    message.setHeader(header);
    return message;
  }
 @Override
 public void read(ByteBuf buf, ProtocolConstants.Direction direction, int protocolVersion) {
   cursor = readString(buf);
   if (protocolVersion >= ProtocolConstants.MINECRAFT_1_8) {
     if (hasPositon = buf.readBoolean()) {
       position = buf.readLong();
     }
   }
 }
 @Override
 protected void channelRead0(ChannelHandlerContext context, ByteBuf message) throws Exception {
   ByteBuf buffer = getBufferIfSufficient(message, UUID_LENGTH, context);
   if (buffer == null) {
     message.release();
   } else {
     UUID uuid = new UUID(buffer.readLong(), buffer.readLong());
     for (BinaryRequestHandler customHandler : BinaryRequestHandler.EP_NAME.getExtensions()) {
       if (uuid.equals(customHandler.getId())) {
         ChannelPipeline pipeline = context.pipeline();
         pipeline.addLast(customHandler.getInboundHandler());
         ensureThatExceptionHandlerIsLast(pipeline);
         pipeline.remove(this);
         context.fireChannelRead(buffer);
         break;
       }
     }
   }
 }
  @Test
  public void testMemcachedRequestEncoder() {

    MemcachedRequest request = new MemcachedRequest(Opcode.SET, "key1", "value1");

    EmbeddedChannel channel = new EmbeddedChannel(new MemcachedRequestEncoder());

    Assert.assertTrue(channel.writeOutbound(request));

    ByteBuf encoded = (ByteBuf) channel.readOutbound();

    Assert.assertNotNull(encoded);

    Assert.assertEquals(request.magic(), encoded.readByte() & 0xFF);

    Assert.assertEquals(request.opCode(), encoded.readByte() & 0xFF);

    Assert.assertEquals(4, encoded.readShort());

    Assert.assertEquals((byte) 0x08, encoded.readByte() & 0xFF);

    Assert.assertEquals((byte) 0, encoded.readByte() & 0xFF);

    Assert.assertEquals(0, encoded.readShort());
    // 注意发送端发的什么位模式这里就收什么位模式。
    // 其实这里也要注意,如果传的刚好是0x8000,解析出来也要注意符号的问题。主要要弄清java是怎么补位和截断,然后保证传的位模式不要被误解。

    Assert.assertEquals(4 + 6 + 8, encoded.readInt());

    Assert.assertEquals(request.id(), encoded.readInt());

    Assert.assertEquals(request.cas(), encoded.readLong());

    Assert.assertEquals(request.flags(), encoded.readInt());

    Assert.assertEquals(request.expires(), encoded.readInt());

    byte[] data = new byte[encoded.readableBytes()];

    encoded.readBytes(data);

    Assert.assertEquals((request.key() + request.body()).getBytes(CharsetUtil.UTF_8), data);

    Assert.assertFalse(encoded.isReadable());

    Assert.assertFalse(channel.finish());

    Assert.assertNull(channel.readInbound());
  }
Example #11
0
 /** decode stream to object */
 public ResponseSocketBlock decode(ByteBuf buf) throws IOException {
   // * --------------------------------------------------------bytes =13
   // * byte[1]  version                              RSF版本(0x80)
   byte version = buf.readByte();
   // * byte[8]  requestID                            包含的请求ID
   long requestID = buf.readLong();
   // * byte[1]  keepData                             保留区
   buf.skipBytes(1);
   // * byte[3]  contentLength                        内容大小
   buf.skipBytes(3); // .readUnsignedMedium()
   //
   ResponseSocketBlock res = new ResponseSocketBlock();
   res.setVersion(version);
   res.setRequestID(requestID);
   // * --------------------------------------------------------bytes =8
   // * byte[2]  status                               响应状态
   res.setStatus(buf.readShort());
   // * byte[2]  serializeType-(attr-index)           序列化策略
   res.setSerializeType(buf.readShort());
   // * byte[2]  returnType-(attr-index)              返回类型
   res.setReturnType(buf.readShort());
   // * byte[2]  returnData-(attr-index)              返回数据
   res.setReturnData(buf.readShort());
   // * --------------------------------------------------------bytes =1 ~ 1021
   // * byte[1]  optionCount                          选项参数总数
   byte optionCount = buf.readByte();
   for (int i = 0; i < optionCount; i++) {
     // * byte[4]  attr-0-(attr-index,attr-index)   选项参数
     int mergeData = buf.readInt();
     res.addOption(mergeData);
   }
   // * --------------------------------------------------------bytes =6 ~ 8192
   // * byte[2]  attrPool-size (Max = 2047)           池大小
   short attrPoolSize = buf.readShort();
   for (int i = 0; i < attrPoolSize; i++) {
     // * byte[4] att-length                        属性1大小
     int length = buf.readInt();
     res.addPoolData(length);
   }
   // * --------------------------------------------------------bytes =n
   // * dataBody                                      数据内容
   res.fillFrom(buf.readBytes(res.getPoolSize()));
   return res;
 }
    @Override
    public OFBsnSetPktinSuppressionRequest readFrom(ByteBuf bb) throws OFParseError {
      int start = bb.readerIndex();
      // fixed value property version == 3
      byte version = bb.readByte();
      if (version != (byte) 0x3)
        throw new OFParseError("Wrong version: Expected=OFVersion.OF_12(3), got=" + version);
      // fixed value property type == 4
      byte type = bb.readByte();
      if (type != (byte) 0x4)
        throw new OFParseError("Wrong type: Expected=OFType.EXPERIMENTER(4), got=" + type);
      int length = U16.f(bb.readShort());
      if (length != 32) throw new OFParseError("Wrong length: Expected=32(32), got=" + length);
      if (bb.readableBytes() + (bb.readerIndex() - start) < length) {
        // Buffer does not have all data yet
        bb.readerIndex(start);
        return null;
      }
      if (logger.isTraceEnabled()) logger.trace("readFrom - length={}", length);
      long xid = U32.f(bb.readInt());
      // fixed value property experimenter == 0x5c16c7L
      int experimenter = bb.readInt();
      if (experimenter != 0x5c16c7)
        throw new OFParseError(
            "Wrong experimenter: Expected=0x5c16c7L(0x5c16c7L), got=" + experimenter);
      // fixed value property subtype == 0xbL
      int subtype = bb.readInt();
      if (subtype != 0xb)
        throw new OFParseError("Wrong subtype: Expected=0xbL(0xbL), got=" + subtype);
      boolean enabled = (bb.readByte() != 0);
      // pad: 1 bytes
      bb.skipBytes(1);
      int idleTimeout = U16.f(bb.readShort());
      int hardTimeout = U16.f(bb.readShort());
      int priority = U16.f(bb.readShort());
      U64 cookie = U64.ofRaw(bb.readLong());

      OFBsnSetPktinSuppressionRequestVer12 bsnSetPktinSuppressionRequestVer12 =
          new OFBsnSetPktinSuppressionRequestVer12(
              xid, enabled, idleTimeout, hardTimeout, priority, cookie);
      if (logger.isTraceEnabled())
        logger.trace("readFrom - read={}", bsnSetPktinSuppressionRequestVer12);
      return bsnSetPktinSuppressionRequestVer12;
    }
Example #13
0
  public StationFrameData(String ip, ByteBuf data) {
    this.ip = ip;
    byte labelCount = data.readByte();
    if (labelCount <= 0) {
      throw new ClientException(ErrorCode.INVALID_REQUEST, "收到的标签数量为负数:" + labelCount);
    }

    labelInfos = new LabelInfo[labelCount];
    for (int i = 0; i < labelCount; i++) {

      long labelId = data.readLong();
      byte rssi = data.readByte();
      byte power = data.readByte();
      LabelInfo labelInfo = new LabelInfo(labelId, rssi, power);
      labelInfos[i] = labelInfo;
    }

    time = System.currentTimeMillis();
  }
    @Override
    public OFBsnTlvMissPackets readFrom(ByteBuf bb) throws OFParseError {
      int start = bb.readerIndex();
      // fixed value property type == 0xd
      short type = bb.readShort();
      if (type != (short) 0xd) throw new OFParseError("Wrong type: Expected=0xd(0xd), got=" + type);
      int length = U16.f(bb.readShort());
      if (length != 12) throw new OFParseError("Wrong length: Expected=12(12), got=" + length);
      if (bb.readableBytes() + (bb.readerIndex() - start) < length) {
        // Buffer does not have all data yet
        bb.readerIndex(start);
        return null;
      }
      if (logger.isTraceEnabled()) logger.trace("readFrom - length={}", length);
      U64 value = U64.ofRaw(bb.readLong());

      OFBsnTlvMissPacketsVer13 bsnTlvMissPacketsVer13 = new OFBsnTlvMissPacketsVer13(value);
      if (logger.isTraceEnabled()) logger.trace("readFrom - read={}", bsnTlvMissPacketsVer13);
      return bsnTlvMissPacketsVer13;
    }
Example #15
0
    @Override
    public LispMapNotify readFrom(ByteBuf byteBuf) throws LispParseError, LispReaderException {

      if (byteBuf.readerIndex() != 0) {
        return null;
      }

      // skip first three bytes as they represent type and reserved fields
      byteBuf.skipBytes(RESERVED_SKIP_LENGTH);

      // record count -> 8 bits
      byte recordCount = (byte) byteBuf.readUnsignedByte();

      // nonce -> 64 bits
      long nonce = byteBuf.readLong();

      // keyId -> 16 bits
      short keyId = byteBuf.readShort();

      // authenticationDataLength -> 16 bits
      short authLength = byteBuf.readShort();

      // authenticationData -> depends on the authenticationDataLength
      byte[] authData = new byte[authLength];
      byteBuf.readBytes(authData);

      List<LispMapRecord> mapRecords = Lists.newArrayList();
      for (int i = 0; i < recordCount; i++) {
        mapRecords.add(new DefaultLispMapRecord.MapRecordReader().readFrom(byteBuf));
      }

      return new DefaultNotifyBuilder()
          .withRecordCount(recordCount)
          .withNonce(nonce)
          .withKeyId(keyId)
          .withAuthenticationData(authData)
          .withMapRecords(mapRecords)
          .build();
    }
 @Test
 public void testEncode() {
   MockRelayMessage message = new MockRelayMessage();
   message.code(Unsigned16.get(100));
   message.length(Unsigned32.get(36L));
   message.flag(new FlagData(FlagImpl.REQUEST));
   message.hopByHop(Integer64.get(1L));
   message.endToEnd(Integer64.get(2L));
   message.addAttribute(new IgnoredAttribute(new IgnoredData(new byte[] {1, 2, 3, 4})));
   ByteBuf buf = MessageFactory.getInstance().generateByteBuf(message);
   Assert.assertEquals(message.version().get().byteValue(), buf.readUnsignedByte());
   Assert.assertEquals(message.code().get().intValue(), buf.readUnsignedShort());
   assertEquals(64, buf.readUnsignedByte());
   Assert.assertEquals(message.length().get().intValue(), buf.readUnsignedInt());
   assertEquals(message.hopByHop().get().longValue(), buf.readLong());
   assertEquals(message.endToEnd().get().longValue(), buf.readLong());
   assertEquals(0, buf.readUnsignedShort());
   assertEquals(4, buf.readUnsignedInt());
   assertEquals(1, buf.readByte());
   assertEquals(2, buf.readByte());
   assertEquals(3, buf.readByte());
   assertEquals(4, buf.readByte());
 }
Example #17
0
  public boolean decodePayload(final ByteBuf buf)
      throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {
    LOG.debug(
        "About to pass message {} to {}. Buffer to read: {}.",
        message,
        message.senderSocket(),
        buf.readableBytes());
    if (!message.hasContent()) {
      return true;
    }

    // payload comes here
    int size;
    PublicKey receivedPublicKey;
    while (contentTypes.size() > 0) {
      Content content = contentTypes.peek();
      LOG.debug("Parse content: {} in message {}", content, message);
      switch (content) {
        case INTEGER:
          if (buf.readableBytes() < Utils.INTEGER_BYTE_SIZE) {
            return false;
          }
          message.intValue(buf.readInt());
          lastContent = contentTypes.poll();
          break;
        case LONG:
          if (buf.readableBytes() < Utils.LONG_BYTE_SIZE) {
            return false;
          }
          message.longValue(buf.readLong());
          lastContent = contentTypes.poll();
          break;
        case KEY:
          if (buf.readableBytes() < Number160.BYTE_ARRAY_SIZE) {
            return false;
          }
          byte[] me = new byte[Number160.BYTE_ARRAY_SIZE];
          buf.readBytes(me);
          message.key(new Number160(me));
          lastContent = contentTypes.poll();
          break;
        case BLOOM_FILTER:
          if (buf.readableBytes() < Utils.SHORT_BYTE_SIZE) {
            return false;
          }
          size = buf.getUnsignedShort(buf.readerIndex());
          if (buf.readableBytes() < size) {
            return false;
          }
          message.bloomFilter(new SimpleBloomFilter<Number160>(buf));
          lastContent = contentTypes.poll();
          break;
        case SET_NEIGHBORS:
          if (neighborSize == -1 && buf.readableBytes() < Utils.BYTE_BYTE_SIZE) {
            return false;
          }
          if (neighborSize == -1) {
            neighborSize = buf.readUnsignedByte();
          }
          if (neighborSet == null) {
            neighborSet = new NeighborSet(-1, new ArrayList<PeerAddress>(neighborSize));
          }
          for (int i = neighborSet.size(); i < neighborSize; i++) {
            if (buf.readableBytes() < Utils.SHORT_BYTE_SIZE) {
              return false;
            }
            int header = buf.getUnsignedShort(buf.readerIndex());
            size = PeerAddress.size(header);
            if (buf.readableBytes() < size) {
              return false;
            }
            PeerAddress pa = new PeerAddress(buf);
            neighborSet.add(pa);
          }
          message.neighborsSet(neighborSet);
          lastContent = contentTypes.poll();
          neighborSize = -1;
          neighborSet = null;
          break;
        case SET_PEER_SOCKET:
          if (peerSocketAddressSize == -1 && buf.readableBytes() < Utils.BYTE_BYTE_SIZE) {
            return false;
          }
          if (peerSocketAddressSize == -1) {
            peerSocketAddressSize = buf.readUnsignedByte();
          }
          if (peerSocketAddresses == null) {
            peerSocketAddresses = new ArrayList<PeerSocketAddress>(peerSocketAddressSize);
          }
          for (int i = peerSocketAddresses.size(); i < peerSocketAddressSize; i++) {
            if (buf.readableBytes() < Utils.BYTE_BYTE_SIZE) {
              return false;
            }
            int header = buf.getUnsignedByte(buf.readerIndex());
            boolean isIPv4 = header == 0;
            size = PeerSocketAddress.size(isIPv4);
            if (buf.readableBytes() < size + Utils.BYTE_BYTE_SIZE) {
              return false;
            }
            // skip the ipv4/ipv6 header
            buf.skipBytes(1);
            peerSocketAddresses.add(PeerSocketAddress.create(buf, isIPv4));
          }
          message.peerSocketAddresses(peerSocketAddresses);
          lastContent = contentTypes.poll();
          peerSocketAddressSize = -1;
          peerSocketAddresses = null;
          break;
        case SET_KEY640:
          if (keyCollectionSize == -1 && buf.readableBytes() < Utils.INTEGER_BYTE_SIZE) {
            return false;
          }
          if (keyCollectionSize == -1) {
            keyCollectionSize = buf.readInt();
          }
          if (keyCollection == null) {
            keyCollection = new KeyCollection(new ArrayList<Number640>(keyCollectionSize));
          }
          for (int i = keyCollection.size(); i < keyCollectionSize; i++) {
            if (buf.readableBytes()
                < Number160.BYTE_ARRAY_SIZE
                    + Number160.BYTE_ARRAY_SIZE
                    + Number160.BYTE_ARRAY_SIZE
                    + Number160.BYTE_ARRAY_SIZE) {
              return false;
            }
            byte[] me2 = new byte[Number160.BYTE_ARRAY_SIZE];
            buf.readBytes(me2);
            Number160 locationKey = new Number160(me2);
            buf.readBytes(me2);
            Number160 domainKey = new Number160(me2);
            buf.readBytes(me2);
            Number160 contentKey = new Number160(me2);
            buf.readBytes(me2);
            Number160 versionKey = new Number160(me2);
            keyCollection.add(new Number640(locationKey, domainKey, contentKey, versionKey));
          }
          message.keyCollection(keyCollection);
          lastContent = contentTypes.poll();
          keyCollectionSize = -1;
          keyCollection = null;
          break;
        case MAP_KEY640_DATA:
          if (mapSize == -1 && buf.readableBytes() < Utils.INTEGER_BYTE_SIZE) {
            return false;
          }
          if (mapSize == -1) {
            mapSize = buf.readInt();
          }
          if (dataMap == null) {
            dataMap = new DataMap(new TreeMap<Number640, Data>());
          }
          if (data != null) {
            if (!data.decodeBuffer(buf)) {
              return false;
            }
            if (!data.decodeDone(buf, message.publicKey(0), signatureFactory)) {
              return false;
            }
            data = null;
            key = null;
          }
          for (int i = dataMap.size(); i < mapSize; i++) {
            if (key == null) {
              if (buf.readableBytes()
                  < Number160.BYTE_ARRAY_SIZE
                      + Number160.BYTE_ARRAY_SIZE
                      + Number160.BYTE_ARRAY_SIZE
                      + Number160.BYTE_ARRAY_SIZE) {
                return false;
              }
              byte[] me3 = new byte[Number160.BYTE_ARRAY_SIZE];
              buf.readBytes(me3);
              Number160 locationKey = new Number160(me3);
              buf.readBytes(me3);
              Number160 domainKey = new Number160(me3);
              buf.readBytes(me3);
              Number160 contentKey = new Number160(me3);
              buf.readBytes(me3);
              Number160 versionKey = new Number160(me3);
              key = new Number640(locationKey, domainKey, contentKey, versionKey);
            }
            LOG.debug("Key decoded in message {}, remaining {}", message, buf.readableBytes());
            data = Data.decodeHeader(buf, signatureFactory);
            if (data == null) {
              return false;
            }
            LOG.debug("Header decoded in message {}, remaining {}", message, buf.readableBytes());
            dataMap.dataMap().put(key, data);

            if (!data.decodeBuffer(buf)) {
              return false;
            }
            LOG.debug("Buffer decoded in message {}", message);
            if (!data.decodeDone(buf, message.publicKey(0), signatureFactory)) {
              return false;
            }
            LOG.debug("Done decoded in message {}", message);
            // if we have signed the message, set the public key anyway, but only if we indicated so
            inheritPublicKey(message, data);
            data = null;
            key = null;
          }

          message.setDataMap(dataMap);
          lastContent = contentTypes.poll();
          mapSize = -1;
          dataMap = null;
          break;
        case MAP_KEY640_KEYS:
          if (keyMap640KeysSize == -1 && buf.readableBytes() < Utils.INTEGER_BYTE_SIZE) {
            return false;
          }
          if (keyMap640KeysSize == -1) {
            keyMap640KeysSize = buf.readInt();
          }
          if (keyMap640Keys == null) {
            keyMap640Keys = new KeyMap640Keys(new TreeMap<Number640, Collection<Number160>>());
          }

          final int meta =
              Number160.BYTE_ARRAY_SIZE
                  + Number160.BYTE_ARRAY_SIZE
                  + Number160.BYTE_ARRAY_SIZE
                  + Number160.BYTE_ARRAY_SIZE;

          for (int i = keyMap640Keys.size(); i < keyMap640KeysSize; i++) {
            if (buf.readableBytes() < meta + Utils.BYTE_BYTE_SIZE) {
              return false;
            }
            size = buf.getUnsignedByte(buf.readerIndex() + meta);

            if (buf.readableBytes()
                < meta + Utils.BYTE_BYTE_SIZE + (size * Number160.BYTE_ARRAY_SIZE)) {
              return false;
            }
            byte[] me3 = new byte[Number160.BYTE_ARRAY_SIZE];
            buf.readBytes(me3);
            Number160 locationKey = new Number160(me3);
            buf.readBytes(me3);
            Number160 domainKey = new Number160(me3);
            buf.readBytes(me3);
            Number160 contentKey = new Number160(me3);
            buf.readBytes(me3);
            Number160 versionKey = new Number160(me3);

            int numBasedOn = buf.readByte();
            Set<Number160> value = new HashSet<Number160>(numBasedOn);
            for (int j = 0; j < numBasedOn; j++) {
              buf.readBytes(me3);
              Number160 basedOnKey = new Number160(me3);
              value.add(basedOnKey);
            }

            keyMap640Keys.put(new Number640(locationKey, domainKey, contentKey, versionKey), value);
          }

          message.keyMap640Keys(keyMap640Keys);
          lastContent = contentTypes.poll();
          keyMap640KeysSize = -1;
          keyMap640Keys = null;
          break;
        case MAP_KEY640_BYTE:
          if (keyMapByteSize == -1 && buf.readableBytes() < Utils.INTEGER_BYTE_SIZE) {
            return false;
          }
          if (keyMapByteSize == -1) {
            keyMapByteSize = buf.readInt();
          }
          if (keyMapByte == null) {
            keyMapByte = new KeyMapByte(new HashMap<Number640, Byte>(2 * keyMapByteSize));
          }

          for (int i = keyMapByte.size(); i < keyMapByteSize; i++) {
            if (buf.readableBytes()
                < Number160.BYTE_ARRAY_SIZE
                    + Number160.BYTE_ARRAY_SIZE
                    + Number160.BYTE_ARRAY_SIZE
                    + Number160.BYTE_ARRAY_SIZE
                    + 1) {
              return false;
            }
            byte[] me3 = new byte[Number160.BYTE_ARRAY_SIZE];
            buf.readBytes(me3);
            Number160 locationKey = new Number160(me3);
            buf.readBytes(me3);
            Number160 domainKey = new Number160(me3);
            buf.readBytes(me3);
            Number160 contentKey = new Number160(me3);
            buf.readBytes(me3);
            Number160 versionKey = new Number160(me3);
            byte value = buf.readByte();
            keyMapByte.put(new Number640(locationKey, domainKey, contentKey, versionKey), value);
          }

          message.keyMapByte(keyMapByte);
          lastContent = contentTypes.poll();
          keyMapByteSize = -1;
          keyMapByte = null;
          break;
        case BYTE_BUFFER:
          if (bufferSize == -1 && buf.readableBytes() < Utils.INTEGER_BYTE_SIZE) {
            return false;
          }
          if (bufferSize == -1) {
            bufferSize = buf.readInt();
          }
          if (buffer == null) {
            buffer = new DataBuffer();
          }

          final int remaining = bufferSize - bufferTransferred;
          bufferTransferred += buffer.transferFrom(buf, remaining);

          if (bufferTransferred < bufferSize) {
            LOG.debug(
                "Still looking for data. Indicating that its not finished yet. Already Transferred = {}, Size = {}.",
                bufferTransferred,
                bufferSize);
            return false;
          }

          message.buffer(new Buffer(buffer.toByteBuf(), bufferSize));
          lastContent = contentTypes.poll();
          bufferSize = -1;
          bufferTransferred = 0;
          buffer = null;
          break;
        case SET_TRACKER_DATA:
          if (trackerDataSize == -1 && buf.readableBytes() < Utils.BYTE_BYTE_SIZE) {
            return false;
          }
          if (trackerDataSize == -1) {
            trackerDataSize = buf.readUnsignedByte();
          }
          if (trackerData == null) {
            trackerData = new TrackerData(new HashMap<PeerAddress, Data>(2 * trackerDataSize));
          }
          if (currentTrackerData != null) {
            if (!currentTrackerData.decodeBuffer(buf)) {
              return false;
            }
            if (!currentTrackerData.decodeDone(buf, message.publicKey(0), signatureFactory)) {
              return false;
            }
            currentTrackerData = null;
          }
          for (int i = trackerData.size(); i < trackerDataSize; i++) {

            if (buf.readableBytes() < Utils.SHORT_BYTE_SIZE) {
              return false;
            }

            int header = buf.getUnsignedShort(buf.readerIndex());

            size = PeerAddress.size(header);

            if (buf.readableBytes() < size) {
              return false;
            }
            PeerAddress pa = new PeerAddress(buf);

            currentTrackerData = Data.decodeHeader(buf, signatureFactory);
            if (currentTrackerData == null) {
              return false;
            }
            trackerData.peerAddresses().put(pa, currentTrackerData);
            if (message.isSign()) {
              currentTrackerData.publicKey(message.publicKey(0));
            }

            if (!currentTrackerData.decodeBuffer(buf)) {
              return false;
            }
            if (!currentTrackerData.decodeDone(buf, message.publicKey(0), signatureFactory)) {
              return false;
            }
            currentTrackerData = null;
          }

          message.trackerData(trackerData);
          lastContent = contentTypes.poll();
          trackerDataSize = -1;
          trackerData = null;
          break;
        case PUBLIC_KEY: // fall-through
        case PUBLIC_KEY_SIGNATURE:
          receivedPublicKey = signatureFactory.decodePublicKey(buf);
          if (content == Content.PUBLIC_KEY_SIGNATURE) {
            if (receivedPublicKey == PeerBuilder.EMPTY_PUBLIC_KEY) {
              throw new InvalidKeyException("The public key cannot be empty.");
            }
          }
          if (receivedPublicKey == null) {
            return false;
          }

          message.publicKey(receivedPublicKey);
          lastContent = contentTypes.poll();
          break;
        default:
          break;
      }
    }
    LOG.debug("Parsed content in message {}", message);
    if (message.isSign()) {
      size = signatureFactory.signatureSize();
      if (buf.readableBytes() < size) {
        return false;
      }

      SignatureCodec signatureEncode = signatureFactory.signatureCodec(buf);
      message.receivedSignature(signatureEncode);
    }
    return true;
  }
 @Override
 public void fromBytes(ByteBuf buf) {
   pos = BlockPos.fromLong(buf.readLong());
 }
 /**
  * Decodes the input {@link ByteBuf} into a {@link RPCFileReadRequest} object and returns it.
  *
  * @param in the input {@link ByteBuf}
  * @return The decoded RPCFileReadRequest object
  */
 public static RPCFileReadRequest decode(ByteBuf in) {
   long tempUfsFileId = in.readLong();
   long offset = in.readLong();
   long length = in.readLong();
   return new RPCFileReadRequest(tempUfsFileId, offset, length);
 }
  @Override
  public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {

    // Discard all data received if closing handshake was received before.
    if (receivedClosingHandshake) {
      in.skipBytes(actualReadableBytes());
      return null;
    }

    switch (state()) {
      case FRAME_START:
        framePayloadBytesRead = 0;
        framePayloadLength = -1;
        framePayload = null;

        // FIN, RSV, OPCODE
        byte b = in.readByte();
        frameFinalFlag = (b & 0x80) != 0;
        frameRsv = (b & 0x70) >> 4;
        frameOpcode = b & 0x0F;

        if (logger.isDebugEnabled()) {
          logger.debug("Decoding WebSocket Frame opCode={}", frameOpcode);
        }

        // MASK, PAYLOAD LEN 1
        b = in.readByte();
        boolean frameMasked = (b & 0x80) != 0;
        int framePayloadLen1 = b & 0x7F;

        if (frameRsv != 0 && !allowExtensions) {
          protocolViolation(ctx, "RSV != 0 and no extension negotiated, RSV:" + frameRsv);
          return null;
        }

        if (maskedPayload && !frameMasked) {
          protocolViolation(ctx, "unmasked client to server frame");
          return null;
        }
        if (frameOpcode > 7) { // control frame (have MSB in opcode set)

          // control frames MUST NOT be fragmented
          if (!frameFinalFlag) {
            protocolViolation(ctx, "fragmented control frame");
            return null;
          }

          // control frames MUST have payload 125 octets or less
          if (framePayloadLen1 > 125) {
            protocolViolation(ctx, "control frame with payload length > 125 octets");
            return null;
          }

          // check for reserved control frame opcodes
          if (!(frameOpcode == OPCODE_CLOSE
              || frameOpcode == OPCODE_PING
              || frameOpcode == OPCODE_PONG)) {
            protocolViolation(ctx, "control frame using reserved opcode " + frameOpcode);
            return null;
          }

          // close frame : if there is a body, the first two bytes of the
          // body MUST be a 2-byte unsigned integer (in network byte
          // order) representing a getStatus code
          if (frameOpcode == 8 && framePayloadLen1 == 1) {
            protocolViolation(ctx, "received close control frame with payload len 1");
            return null;
          }
        } else { // data frame
          // check for reserved data frame opcodes
          if (!(frameOpcode == OPCODE_CONT
              || frameOpcode == OPCODE_TEXT
              || frameOpcode == OPCODE_BINARY)) {
            protocolViolation(ctx, "data frame using reserved opcode " + frameOpcode);
            return null;
          }

          // check opcode vs message fragmentation state 1/2
          if (fragmentedFramesCount == 0 && frameOpcode == OPCODE_CONT) {
            protocolViolation(ctx, "received continuation data frame outside fragmented message");
            return null;
          }

          // check opcode vs message fragmentation state 2/2
          if (fragmentedFramesCount != 0
              && frameOpcode != OPCODE_CONT
              && frameOpcode != OPCODE_PING) {
            protocolViolation(
                ctx, "received non-continuation data frame while inside fragmented message");
            return null;
          }
        }

        // Read frame payload length
        if (framePayloadLen1 == 126) {
          framePayloadLength = in.readUnsignedShort();
          if (framePayloadLength < 126) {
            protocolViolation(ctx, "invalid data frame length (not using minimal length encoding)");
            return null;
          }
        } else if (framePayloadLen1 == 127) {
          framePayloadLength = in.readLong();
          // TODO: check if it's bigger than 0x7FFFFFFFFFFFFFFF, Maybe
          // just check if it's negative?

          if (framePayloadLength < 65536) {
            protocolViolation(ctx, "invalid data frame length (not using minimal length encoding)");
            return null;
          }
        } else {
          framePayloadLength = framePayloadLen1;
        }

        if (framePayloadLength > maxFramePayloadLength) {
          protocolViolation(
              ctx, "Max frame length of " + maxFramePayloadLength + " has been exceeded.");
          return null;
        }

        if (logger.isDebugEnabled()) {
          logger.debug("Decoding WebSocket Frame length={}", framePayloadLength);
        }

        checkpoint(State.MASKING_KEY);
      case MASKING_KEY:
        if (maskedPayload) {
          maskingKey = in.readBytes(4);
        }
        checkpoint(State.PAYLOAD);
      case PAYLOAD:
        // Sometimes, the payload may not be delivered in 1 nice packet
        // We need to accumulate the data until we have it all
        int rbytes = actualReadableBytes();
        ByteBuf payloadBuffer = null;

        long willHaveReadByteCount = framePayloadBytesRead + rbytes;
        // logger.debug("Frame rbytes=" + rbytes + " willHaveReadByteCount="
        // + willHaveReadByteCount + " framePayloadLength=" +
        // framePayloadLength);
        if (willHaveReadByteCount == framePayloadLength) {
          // We have all our content so proceed to process
          payloadBuffer = ctx.alloc().buffer(rbytes);
          payloadBuffer.writeBytes(in, rbytes);
        } else if (willHaveReadByteCount < framePayloadLength) {

          // We don't have all our content so accumulate payload.
          // Returning null means we will get called back
          if (framePayload == null) {
            framePayload = ctx.alloc().buffer(toFrameLength(framePayloadLength));
          }
          framePayload.writeBytes(in, rbytes);
          framePayloadBytesRead += rbytes;

          // Return null to wait for more bytes to arrive
          return null;
        } else if (willHaveReadByteCount > framePayloadLength) {
          // We have more than what we need so read up to the end of frame
          // Leave the remainder in the buffer for next frame
          if (framePayload == null) {
            framePayload = ctx.alloc().buffer(toFrameLength(framePayloadLength));
          }
          framePayload.writeBytes(in, toFrameLength(framePayloadLength - framePayloadBytesRead));
        }

        // Now we have all the data, the next checkpoint must be the next
        // frame
        checkpoint(State.FRAME_START);

        // Take the data that we have in this packet
        if (framePayload == null) {
          framePayload = payloadBuffer;
        } else if (payloadBuffer != null) {
          framePayload.writeBytes(payloadBuffer);
        }

        // Unmask data if needed
        if (maskedPayload) {
          unmask(framePayload);
        }

        // Processing ping/pong/close frames because they cannot be
        // fragmented
        if (frameOpcode == OPCODE_PING) {
          return new PingWebSocketFrame(frameFinalFlag, frameRsv, framePayload);
        }
        if (frameOpcode == OPCODE_PONG) {
          return new PongWebSocketFrame(frameFinalFlag, frameRsv, framePayload);
        }
        if (frameOpcode == OPCODE_CLOSE) {
          checkCloseFrameBody(ctx, framePayload);
          receivedClosingHandshake = true;
          return new CloseWebSocketFrame(frameFinalFlag, frameRsv, framePayload);
        }

        // Processing for possible fragmented messages for text and binary
        // frames
        String aggregatedText = null;
        if (frameFinalFlag) {
          // Final frame of the sequence. Apparently ping frames are
          // allowed in the middle of a fragmented message
          if (frameOpcode != OPCODE_PING) {
            fragmentedFramesCount = 0;

            // Check text for UTF8 correctness
            if (frameOpcode == OPCODE_TEXT || fragmentedFramesText != null) {
              // Check UTF-8 correctness for this payload
              checkUTF8String(ctx, framePayload);

              // This does a second check to make sure UTF-8
              // correctness for entire text message
              aggregatedText = fragmentedFramesText.toString();

              fragmentedFramesText = null;
            }
          }
        } else {
          // Not final frame so we can expect more frames in the
          // fragmented sequence
          if (fragmentedFramesCount == 0) {
            // First text or binary frame for a fragmented set
            fragmentedFramesText = null;
            if (frameOpcode == OPCODE_TEXT) {
              checkUTF8String(ctx, framePayload);
            }
          } else {
            // Subsequent frames - only check if init frame is text
            if (fragmentedFramesText != null) {
              checkUTF8String(ctx, framePayload);
            }
          }

          // Increment counter
          fragmentedFramesCount++;
        }

        // Return the frame
        if (frameOpcode == OPCODE_TEXT) {
          return new TextWebSocketFrame(frameFinalFlag, frameRsv, framePayload);
        } else if (frameOpcode == OPCODE_BINARY) {
          return new BinaryWebSocketFrame(frameFinalFlag, frameRsv, framePayload);
        } else if (frameOpcode == OPCODE_CONT) {
          return new ContinuationWebSocketFrame(
              frameFinalFlag, frameRsv, framePayload, aggregatedText);
        } else {
          throw new UnsupportedOperationException(
              "Cannot decode web socket frame with opcode: " + frameOpcode);
        }
      case CORRUPT:
        // If we don't keep reading Netty will throw an exception saying
        // we can't return null if no bytes read and state not changed.
        in.readByte();
        return null;
      default:
        throw new Error("Shouldn't reach here.");
    }
  }
Example #21
0
 @Override
 public void fromBytes(ByteBuf buf) {
   uuid = new UUID(buf.readLong(), buf.readLong());
   tags = ByteBufUtils.readTag(buf);
 }
Example #22
0
 public static UUID readUUID(ByteBuf input) {
   return new UUID(input.readLong(), input.readLong());
 }
Example #23
0
  public DimensionInformation(String name, DimensionDescriptor descriptor, ByteBuf buf) {
    this.name = name;
    this.descriptor = descriptor;

    terrainType = NetworkTools.readEnum(buf, TerrainType.values());
    NetworkTools.readEnumCollection(buf, featureTypes, FeatureType.values());
    NetworkTools.readEnumCollection(buf, structureTypes, StructureType.values());
    NetworkTools.readEnumCollection(buf, effectTypes, EffectType.values());

    biomes.clear();
    int size = buf.readInt();
    for (int i = 0; i < size; i++) {
      BiomeGenBase biome = BiomeGenBase.getBiome(buf.readInt());
      if (biome != null) {
        biomes.add(biome);
      } else {
        biomes.add(BiomeGenBase.plains);
      }
    }
    controllerType = NetworkTools.readEnum(buf, ControllerType.values());
    digitString = NetworkTools.readString(buf);

    forcedDimensionSeed = buf.readLong();
    baseSeed = buf.readLong();
    worldVersion = buf.readInt();

    Block block = (Block) Block.blockRegistry.getObjectById(buf.readInt());
    int meta = buf.readInt();
    baseBlockForTerrain = new BlockMeta(block, meta);
    block = (Block) Block.blockRegistry.getObjectById(buf.readInt());
    meta = buf.readInt();
    tendrilBlock = new BlockMeta(block, meta);

    pyramidBlocks = readBlockArrayFromBuf(buf);
    sphereBlocks = readBlockArrayFromBuf(buf);
    hugeSphereBlocks = readBlockArrayFromBuf(buf);
    liquidSphereBlocks = readBlockArrayFromBuf(buf);
    liquidSphereFluids = readFluidArrayFromBuf(buf);
    hugeLiquidSphereBlocks = readBlockArrayFromBuf(buf);
    hugeLiquidSphereFluids = readFluidArrayFromBuf(buf);

    block = (Block) Block.blockRegistry.getObjectById(buf.readInt());
    meta = buf.readInt();
    canyonBlock = new BlockMeta(block, meta);
    fluidForTerrain = (Block) Block.blockRegistry.getObjectById(buf.readInt());

    extraOregen = readBlockArrayFromBuf(buf);

    fluidsForLakes = readFluidArrayFromBuf(buf);

    peaceful = buf.readBoolean();
    noanimals = buf.readBoolean();
    shelter = buf.readBoolean();
    respawnHere = buf.readBoolean();

    celestialAngle = NetworkTools.readFloat(buf);
    timeSpeed = NetworkTools.readFloat(buf);

    probeCounter = buf.readInt();
    actualRfCost = buf.readInt();

    skyDescriptor = new SkyDescriptor.Builder().fromBytes(buf).build();
    calculateCelestialBodyDescriptors();

    weatherDescriptor = new WeatherDescriptor.Builder().fromBytes(buf).build();

    patreon1 = buf.readLong();

    extraMobs.clear();
    size = buf.readInt();
    for (int i = 0; i < size; i++) {
      String className = NetworkTools.readString(buf);
      try {
        Class<? extends EntityLiving> c = (Class<? extends EntityLiving>) Class.forName(className);
        int chance = buf.readInt();
        int minGroup = buf.readInt();
        int maxGroup = buf.readInt();
        int maxLoaded = buf.readInt();
        MobDescriptor mob = new MobDescriptor(null, c, chance, minGroup, maxGroup, maxLoaded);
        extraMobs.add(mob);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }

    size = buf.readInt();
    dimensionTypes = new String[size];
    for (int i = 0; i < size; i++) {
      dimensionTypes[i] = NetworkTools.readString(buf);
    }

    setupBiomeMapping();
  }
Example #24
0
  @Override
  public void decode(ByteBuf buf) {
    id = buf.readLong();
    byte[] bitSetBuf = new byte[8];
    buf.readBytes(bitSetBuf);
    this.bitSet = BitSet.valueOf(bitSetBuf);

    if (bitSet.get(0)) {
      position = readLongVector3(buf);
    }
    if (bitSet.get(1)) {
      orientation = readOrientation(buf);
    }
    if (bitSet.get(2)) {
      velocity = readFloatVector3(buf);
    }
    if (bitSet.get(3)) {
      accel = readFloatVector3(buf);
    }
    if (bitSet.get(4)) {
      extraVel = readFloatVector3(buf);
    }
    if (bitSet.get(5)) {
      lookPitch = buf.readFloat();
    }
    if (bitSet.get(6)) {
      physicsFlags = buf.readUnsignedInt();
    }
    if (bitSet.get(7)) {
      hostileType = buf.readByte();
    }
    if (bitSet.get(8)) {
      entityType = buf.readUnsignedInt();
    }
    if (bitSet.get(9)) {
      currentMode = buf.readByte();
    }
    if (bitSet.get(10)) {
      lastShootTime = buf.readUnsignedInt();
    }
    if (bitSet.get(11)) {
      hitCounter = buf.readUnsignedInt();
    }
    if (bitSet.get(12)) {
      lastHitTime = buf.readUnsignedInt();
    }
    if (bitSet.get(13)) {
      app.decode(buf);
    }
    if (bitSet.get(14)) {
      flags1 = buf.readByte();
      flags2 = buf.readByte();
    }
    if (bitSet.get(15)) {
      rollTime = buf.readUnsignedInt();
    }
    if (bitSet.get(16)) {
      stunTime = buf.readInt();
    }
    if (bitSet.get(17)) {
      slowedTime = buf.readUnsignedInt();
    }
    if (bitSet.get(18)) {
      makeBlueTime = buf.readUnsignedInt();
    }
    if (bitSet.get(19)) {
      speedUpTime = buf.readUnsignedInt();
    }
    if (bitSet.get(20)) {
      slowPatchTime = buf.readFloat();
    }
    if (bitSet.get(21)) {
      classType = buf.readByte();
    }
    if (bitSet.get(22)) {
      specialization = buf.readByte();
    }
    if (bitSet.get(23)) {
      chargedMP = buf.readFloat();
    }
    if (bitSet.get(24)) {
      nu1 = buf.readUnsignedInt();
      nu2 = buf.readUnsignedInt();
      nu3 = buf.readUnsignedInt();
    }
    if (bitSet.get(25)) {
      nu4 = buf.readUnsignedInt();
      nu5 = buf.readUnsignedInt();
      nu6 = buf.readUnsignedInt();
    }
    if (bitSet.get(26)) {
      rayHit = readFloatVector3(buf);
    }
    if (bitSet.get(27)) {
      HP = buf.readFloat();
    }
    if (bitSet.get(28)) {
      MP = buf.readFloat();
    }
    if (bitSet.get(29)) {
      blockPower = buf.readFloat();
    }
    if (bitSet.get(30)) {
      maxHPMultiplier = buf.readFloat();
      shootSpeed = buf.readFloat();
      damageMultiplier = buf.readFloat();
      armorMultiplier = buf.readFloat();
      resistanceMultiplier = buf.readFloat();
    }
    if (bitSet.get(31)) {
      nu7 = buf.readByte();
    }
    if (bitSet.get(32)) {
      nu8 = buf.readByte();
    }
    if (bitSet.get(33)) {
      level = buf.readUnsignedInt();
    }
    if (bitSet.get(34)) {
      currentXP = buf.readUnsignedInt();
    }
    if (bitSet.get(35)) {
      parentOwner = buf.readLong();
    }
    if (bitSet.get(36)) {
      na1 = buf.readUnsignedInt();
      na2 = buf.readUnsignedInt();
    }
    if (bitSet.get(37)) {
      na3 = buf.readByte();
    }
    if (bitSet.get(38)) {
      na4 = buf.readUnsignedInt();
    }
    if (bitSet.get(39)) {
      na5 = buf.readUnsignedInt();
      nu11 = buf.readUnsignedInt();
      nu12 = buf.readUnsignedInt();
    }
    if (bitSet.get(40)) {
      spawnPosition = readLongVector3(buf);
    }
    if (bitSet.get(41)) {
      nu20 = buf.readUnsignedInt();
      nu21 = buf.readUnsignedInt();
      nu22 = buf.readUnsignedInt();
    }
    if (bitSet.get(42)) {
      nu19 = buf.readByte();
    }
    if (bitSet.get(43)) {
      itemData.decode(buf);
    }
    if (bitSet.get(44)) {
      for (int i = 0; i < 13; i++) {
        GItem item = new GItem();
        item.decode(buf);
        equipment[i] = item;
      }
    }
    if (bitSet.get(45)) {
      name = new String(buf.readBytes(16).array(), Charsets.US_ASCII).trim();
    }
    if (bitSet.get(46)) {
      for (int i = 0; i < 11; i++) {
        skills[i] = buf.readUnsignedInt();
      }
    }
    if (bitSet.get(47)) {
      iceBlockFour = buf.readUnsignedInt();
    }

    debugCap = buf.capacity();
    buf.resetReaderIndex();
    buf.resetWriterIndex();
  }
Example #25
0
 public Packet8Stealth(ByteBuf buf) {
   id = buf.readLong();
   this.unknowndata = new byte[32];
   buf.readBytes(unknowndata);
 }
 @Override
 public long readLong() {
   return buffer.readLong();
 }
Example #27
0
 @Override
 public void fromBytes(ByteBuf buffer) {
   this.islandX = buffer.readInt();
   this.islandZ = buffer.readInt();
   this.seed = buffer.readLong();
 }
 @Override
 public long readLong() {
   return a.readLong();
 }
 @Override
 public void read(ByteBuf buf) throws Exception {
   actionId = buf.readByte();
   targetEntityId = buf.readLong();
 }
Example #30
0
  @Override
  @SuppressWarnings("restriction")
  public void decode(ByteBuf buf) {
    id = buf.readLong();
    buf.readBytes(bitmask);
    BitArray bitArray =
        new BitArray(8 * bitmask.length, Bitops.flipBits(bitmask)); // Size in bits, byte[]
    // BitArray bitArray = new BitArray(bitmask);

    if (bitArray.get(0)) {
      posX = buf.readLong();
      posY = buf.readLong();
      posZ = buf.readLong();
    }
    if (bitArray.get(1)) {
      pitch = buf.readFloat();
      roll = buf.readFloat();
      yaw = buf.readFloat();
    }
    if (bitArray.get(2)) {
      velocity.decode(buf);
    }
    if (bitArray.get(3)) {
      accel.decode(buf);
    }
    if (bitArray.get(4)) {
      extraVel.decode(buf);
    }
    if (bitArray.get(5)) {
      lookPitch = buf.readFloat();
    }
    if (bitArray.get(6)) {
      physicsFlags = buf.readUnsignedInt();
    }
    if (bitArray.get(7)) {
      speedFlags = buf.readByte();
    }
    if (bitArray.get(8)) {
      entityType = buf.readUnsignedInt();
    }
    if (bitArray.get(9)) {
      currentMode = buf.readByte();
    }
    if (bitArray.get(10)) {
      lastShootTime = buf.readUnsignedInt();
    }
    if (bitArray.get(11)) {
      hitCounter = buf.readUnsignedInt();
    }
    if (bitArray.get(12)) {
      lastHitTime = buf.readUnsignedInt();
    }
    if (bitArray.get(13)) {
      app.decode(buf);
    }
    if (bitArray.get(14)) {
      flags1 = buf.readByte();
      flags2 = buf.readByte();
    }
    if (bitArray.get(15)) {
      rollTime = buf.readUnsignedInt();
    }
    if (bitArray.get(16)) {
      stunTime = buf.readInt();
    }
    if (bitArray.get(17)) {
      slowedTime = buf.readUnsignedInt();
    }
    if (bitArray.get(18)) {
      makeBlueTime = buf.readUnsignedInt();
    }
    if (bitArray.get(19)) {
      speedUpTime = buf.readUnsignedInt();
    }
    if (bitArray.get(20)) {
      slowPatchTime = buf.readFloat();
    }
    if (bitArray.get(21)) {
      classType = buf.readByte();
    }
    if (bitArray.get(22)) {
      specialization = buf.readByte();
    }
    if (bitArray.get(23)) {
      chargedMP = buf.readFloat();
    }
    if (bitArray.get(24)) {
      nu1 = buf.readUnsignedInt();
      nu2 = buf.readUnsignedInt();
      nu3 = buf.readUnsignedInt();
    }
    if (bitArray.get(25)) {
      nu4 = buf.readUnsignedInt();
      nu5 = buf.readUnsignedInt();
      nu6 = buf.readUnsignedInt();
    }
    if (bitArray.get(26)) {
      rayHit.decode(buf);
    }
    if (bitArray.get(27)) {
      HP = buf.readFloat();
    }
    if (bitArray.get(28)) {
      MP = buf.readFloat();
    }
    if (bitArray.get(29)) {
      blockPower = buf.readFloat();
    }
    if (bitArray.get(30)) {
      maxHPMultiplier = buf.readFloat();
      shootSpeed = buf.readFloat();
      damageMultiplier = buf.readFloat();
      armorMultiplier = buf.readFloat();
      resistanceMultiplier = buf.readFloat();
    }
    if (bitArray.get(31)) {
      nu7 = buf.readByte();
    }
    if (bitArray.get(32)) {
      nu8 = buf.readByte();
    }
    if (bitArray.get(33)) {
      level = buf.readUnsignedInt();
    }
    if (bitArray.get(34)) {
      currentXP = buf.readUnsignedInt();
    }
    if (bitArray.get(35)) {
      parentOwner = buf.readLong();
    }
    if (bitArray.get(36)) {
      na1 = buf.readUnsignedInt();
      na2 = buf.readUnsignedInt();
    }
    if (bitArray.get(37)) {
      na3 = buf.readByte();
    }
    if (bitArray.get(38)) {
      na4 = buf.readUnsignedInt();
    }
    if (bitArray.get(39)) {
      na5 = buf.readUnsignedInt();
      nu11 = buf.readUnsignedInt();
      nu12 = buf.readUnsignedInt();
    }
    if (bitArray.get(40)) {
      nu13 = buf.readUnsignedInt();
      nu14 = buf.readUnsignedInt();
      nu15 = buf.readUnsignedInt();
      nu16 = buf.readUnsignedInt();
      nu17 = buf.readUnsignedInt();
      nu18 = buf.readUnsignedInt();
    }
    if (bitArray.get(41)) {
      nu20 = buf.readUnsignedInt();
      nu21 = buf.readUnsignedInt();
      nu22 = buf.readUnsignedInt();
    }
    if (bitArray.get(42)) {
      nu19 = buf.readByte();
    }
    if (bitArray.get(43)) {
      itemData.decode(buf);
    }
    if (bitArray.get(44)) {
      for (int i = 0; i < 13; i++) {
        GItem item = new GItem();
        item.decode(buf);
        equipment[i] = item;
      }
    }
    if (bitArray.get(45)) {
      name = new String(buf.readBytes(16).array(), Charsets.US_ASCII).trim();
    }
    if (bitArray.get(46)) {
      for (int i = 0; i < 11; i++) {
        skills[i] = buf.readUnsignedInt();
      }
    }
    if (bitArray.get(47)) {
      iceBlockFour = buf.readUnsignedInt();
    }

    debugCap = buf.capacity();
    buf.resetReaderIndex();
    buf.resetWriterIndex();
  }