Java Code Examples for io.netty.buffer.ByteBuf.readerIndex()

The following are Jave code examples for showing how to use readerIndex() of the io.netty.buffer.ByteBuf class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: L2J-Global   File: Crypt.java   Source Code and License Vote up 6 votes
@Override
public void encrypt(ByteBuf buf)
{
	if (!_isEnabled)
	{
		_isEnabled = true;
		onPacketSent(buf);
		return;
	}
	
	onPacketSent(buf);
	
	int a = 0;
	while (buf.isReadable())
	{
		final int b = buf.readByte() & 0xFF;
		a = b ^ _outKey[(buf.readerIndex() - 1) & 15] ^ a;
		buf.setByte(buf.readerIndex() - 1, a);
	}
	
	shiftKey(_outKey, buf.writerIndex());
}
 
Example 2
Project: Mods   File: TF2Message.java   Source Code and License Vote up 6 votes
@Override
public void fromBytes(ByteBuf buf) {
	entityID = buf.readInt();
	type = buf.readByte();
	if (type == 0)
		intValue = buf.readInt();
	else if (type == 1)
		floatValue = buf.readFloat();
	else if (type == 2)
		byteValue = buf.readByte();
	else if (type == 3) {
		int stringLength = buf.readByte();
		stringValue = buf.toString(buf.readerIndex(), stringLength, StandardCharsets.UTF_8);
		buf.readerIndex(buf.readerIndex() + stringLength);
	}
	// value=buf.readInt();
	name = buf.toString(buf.readerIndex(), buf.readableBytes(), StandardCharsets.UTF_8);
}
 
Example 3
Project: proxyee-down   File: ByteUtil.java   Source Code and License Vote up 6 votes
public static int findText(ByteBuf byteBuf, String str) {
  byte[] text = stringToBytes(str);
  int matchIndex = 0;
  for (int i = byteBuf.readerIndex(); i < byteBuf.readableBytes(); i++) {
    for (int j = matchIndex; j < text.length; j++) {
      if (byteBuf.getByte(i) == text[j]) {
        matchIndex = j + 1;
        if (matchIndex == text.length) {
          return i;
        }
      } else {
        matchIndex = 0;
      }
      break;
    }
  }
  return -1;
}
 
Example 4
Project: simulacron   File: ByteBufCodec.java   Source Code and License Vote up 5 votes
@Override
public String readString(ByteBuf source) {
  int len = readUnsignedShort(source);
  String str = source.toString(source.readerIndex(), len, CharsetUtil.UTF_8);
  source.readerIndex(source.readerIndex() + len);
  return str;
}
 
Example 5
Project: NioImapClient   File: NumberParser.java   Source Code and License Vote up 5 votes
public long parse(ByteBuf in) {
  seq = sequenceRef.get();

  seq.reset();
  size = 0;
  int i = in.forEachByte(this);
  in.readerIndex(i);

  Long result = Long.parseLong(seq.toString());
  seq = null;

  return result;
}
 
Example 6
Project: wecard-server   File: ProtobufDecoder.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
    final byte[] array;
    final int offset;
    final int length = msg.readableBytes();
    if (msg.hasArray()) {
        array = msg.array();
        offset = msg.arrayOffset() + msg.readerIndex();
    } else {
        array = new byte[length];
        msg.getBytes(msg.readerIndex(), array, 0, length);
        offset = 0;
    }

    if (extensionRegistry == null) {
        if (HAS_PARSER) {
            out.add(prototype.getParserForType().parseFrom(array, offset, length));
        } else {
            out.add(prototype.newBuilderForType().mergeFrom(array, offset, length).build());
        }
    } else {
        if (HAS_PARSER) {
            out.add(prototype.getParserForType().parseFrom(array, offset, length, extensionRegistry));
        } else {
            out.add(prototype.newBuilderForType().mergeFrom(array, offset, length, extensionRegistry).build());
        }
    }
}
 
Example 7
Project: LibraSock   File: LibraMessage.java   Source Code and License Vote up 5 votes
/**
 * 解码
 * 
 * @param in
 * @return
 * @throws Exception
 */
public static LibraMessage decode(ByteBuf in) throws Exception {
	LibraMessage message = new LibraMessage();
	message.setHead(LibraHead.decode(in));
	short bodyLength = in.readShort();// 消息体的长度
	if (bodyLength != in.readableBytes()) {
		LibraLog.error("LibraMessage.decode is error! params:bodyLength:" + bodyLength + "\treadableLength:" + in.readableBytes());
		return null;
	}
	ByteBuf bodyByteBuf = in.readBytes(in.readableBytes());
	byte[] array;
	// 反序列化数据的起始点
	int offset;
	// 可读的数据字节长度
	int readableLen = bodyByteBuf.readableBytes();
	// 分为包含数组数据和不包含数组数据两种形式
	if (bodyByteBuf.hasArray()) {
		array = bodyByteBuf.array();
		offset = bodyByteBuf.arrayOffset() + bodyByteBuf.readerIndex();
	} else {
		array = new byte[readableLen];
		bodyByteBuf.getBytes(bodyByteBuf.readerIndex(), array, 0, readableLen);
		offset = 0;
	}
	// 反序列化
	message.setBody(decodeBody(message.getHead().getProtocolID(), array, offset, readableLen));
	return message;
}
 
Example 8
Project: minebox   File: TransmissionPhase.java   Source Code and License Vote up 5 votes
private void checkReadLength(OperationParameters operationParameters, ByteBuf data) {
    final int actuallyRead = data.writerIndex() - data.readerIndex();
    if (actuallyRead != operationParameters.cmdLength) {

        LOGGER.error("responding to from {} length {} handle {}", operationParameters.cmdOffset, actuallyRead, operationParameters.cmdHandle);
        final String msg = "i messed up and tried to return the wrong about of read data.. " +
                "from " + operationParameters.cmdOffset +
                " length " + actuallyRead +
                " requested " + operationParameters.cmdLength +
                " handle " + operationParameters.cmdHandle;
        throw new IllegalStateException(msg);
    }
}
 
Example 9
Project: NioImapClient   File: AllBytesParser.java   Source Code and License Vote up 5 votes
@Override
public String parse(ByteBuf buffer) {
  AppendableCharSequence sequence = sequenceReference.get();

  int readerIndex = buffer.readerIndex();
  try {
    super.parse(buffer);
  } catch (Signal e) {
    e.expect(REPLAYING_SIGNAL);
    buffer.readerIndex(readerIndex + size);
    return sequence.toString();
  }

  return sequence.toString();
}
 
Example 10
Project: NioImapClient   File: BaseStringParser.java   Source Code and License Vote up 5 votes
public String parse(ByteBuf buffer) {
  seq = sequenceReference.get();

  seq.reset();
  size = 0;
  int i = buffer.forEachByte(this);
  buffer.readerIndex(i + 1);

  String result = seq.toString();
  seq = null;

  return result;
}
 
Example 11
Project: NioImapClient   File: ResponseDecoder.java   Source Code and License Vote up 5 votes
private UntaggedSearchResponse parseSearch(ByteBuf in) {
  List<Long> ids = new ArrayList<>();
  for (; ; ) {
    char c = ((char) in.readUnsignedByte());
    in.readerIndex(in.readerIndex() - 1);
    if (c == HttpConstants.CR || c == HttpConstants.LF) {
      lineParser.parse(in);
      break;
    }

    ids.add(Long.parseLong(atomOrStringParser.parse(in)));
  }

  return new UntaggedSearchResponse(ids);
}
 
Example 12
Project: reactive-pg-client   File: MessageDecoder.java   Source Code and License Vote up 4 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
  while (true) {
    if (in.readableBytes() < 5) {
      break;
    }
    int beginIdx = in.readerIndex();
    byte id = in.getByte(beginIdx);
    int length = in.getInt(beginIdx + 1);
    int endIdx = beginIdx + length + 1;
    final int writerIndex = in.writerIndex();
    if (writerIndex < endIdx) {
      break;
    }
    try {
      in.setIndex(beginIdx + 5, endIdx);
      switch (id) {
        case READY_FOR_QUERY: {
          decodeReadyForQuery(in, out);
          break;
        }
        case DATA_ROW: {
          decodeDataRow(in);
          break;
        }
        case COMMAND_COMPLETE: {
          decodeCommandComplete(in, out);
          break;
        }
        case BIND_COMPLETE: {
          decodeBindComplete(out);
          break;
        }
        default: {
          decodeMessage(id, in ,out);
        }
      }
    } finally {
      in.setIndex(endIdx, writerIndex);
    }
  }
}
 
Example 13
Project: reactive-pg-client   File: DataType.java   Source Code and License Vote up 4 votes
public T decodeText(int len, ByteBuf buff) {
  // Default to null
  buff.readerIndex(buff.readerIndex() + len);
  return null;
}
 
Example 14
Project: reactive-pg-client   File: DataType.java   Source Code and License Vote up 4 votes
public T decodeBinary(int len, ByteBuf buff) {
  // Default to null
  buff.readerIndex(buff.readerIndex() + len);
  return null;
}
 
Example 15
Project: NioImapClient   File: BufferedBodyParser.java   Source Code and License Vote up 4 votes
@Override
public Optional<byte[]> parse(ByteBuf in) {
  for (;;) {
    switch (state) {
      case START:
        char c = ((char) in.readUnsignedByte());
        if (c == '{') {
          in.readerIndex(in.readerIndex() - 1);
          expectedSize = sizeParser.parse(in);
          state = State.SKIP_CRLF;
          return Optional.empty();
        } else if (Character.isWhitespace(c)) {
          continue;
        } else {
          in.readerIndex(in.readerIndex() - 1);
          state = State.PARSE_STRING;
          continue;
        }
      case SKIP_CRLF:
        in.readBytes(2);
        state = State.PARSE_SIZE;
        continue;
      case PARSE_STRING:
        return Optional.of(stringParser.parse(in).getBytes(StandardCharsets.UTF_8));
      case PARSE_SIZE:
        if (buf == null) {
          buf = PooledByteBufAllocator.DEFAULT.buffer(expectedSize);
        }

        pos = in.readerIndex();
        try {
          while (size < expectedSize) {
            buf.writeByte((char) in.readUnsignedByte());
            inc();
          }
        } catch (Signal e) {
          e.expect(REPLAYING_SIGNAL);
          in.readerIndex(pos);
          return Optional.empty();
        }

        byte[] result = new byte[buf.readableBytes()];
        buf.getBytes(buf.readerIndex(), result);
        reset();

        return Optional.of(result);
    }
  }

}
 
Example 16
Project: Mods   File: TF2Message.java   Source Code and License Vote up 4 votes
@Override
public void fromBytes(ByteBuf buf) {
	int stringLength = buf.readByte();
	value = buf.toString(buf.readerIndex(), stringLength, StandardCharsets.UTF_8);
	buf.readerIndex(buf.readerIndex() + stringLength);
}
 
Example 17
Project: NioSmtpClient   File: Utf8SmtpResponseDecoder.java   Source Code and License Vote up 4 votes
@Override
protected SmtpResponse decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
  ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);
  if (frame == null) {
    // No full line received yet.
    return null;
  }
  try {
    final int readable = frame.readableBytes();
    final int readerIndex = frame.readerIndex();
    if (readable < 3) {
      throw newDecoderException(buffer, readerIndex, readable);
    }
    final int code = parseCode(frame);
    final int separator = frame.readByte();
    final CharSequence detail = frame.isReadable() ? frame.toString(CharsetUtil.UTF_8) : null;

    List<CharSequence> details = this.details;

    switch (separator) {
      case ' ':
        // Marks the end of a response.
        this.details = null;
        if (details != null) {
          if (detail != null) {
            details.add(detail);
          }
        } else {
          details = Collections.singletonList(detail);
        }
        return new DefaultSmtpResponse(code, details.toArray(new CharSequence[0]));
      case '-':
        // Multi-line response.
        if (detail != null) {
          if (details == null) {
            // Using initial capacity as it is very unlikely that we will receive a multi-line response
            // with more then 3 lines.
            this.details = details = new ArrayList<>(4);
          }
          details.add(detail);
        }
        break;
      default:
        throw newDecoderException(buffer, readerIndex, readable);
    }
  } finally {
    frame.release();
  }
  return null;
}
 
Example 18
Project: netto_rpc   File: NettoFrameDecoder.java   Source Code and License Vote up 4 votes
@SuppressWarnings("unused")
@Override
   protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
       // 1.判断in.readerIndex
       int idx = in.readerIndex();
       int wrtIdx = in.writerIndex();

       if (wrtIdx > maxRequestSize) {
           // buffer size exceeded maxObjectLength; discarding the complete
           // buffer.
           in.skipBytes(in.readableBytes());
           throw new TooLongFrameException(
                   "object length exceeds " + maxRequestSize + ": " + wrtIdx + " bytes discarded");
       }

       for (; idx < wrtIdx; idx++) {
           byte c = in.getByte(idx);
           if (Character.isWhitespace(c)) {
               in.skipBytes(1);
           } else {
               break;
           }
       }

       if (in.readableBytes() >= NettoFrame.HEADER_LENGTH) {
           byte[] headerInfo = new byte[NettoFrame.HEADER_LENGTH];
           Arrays.fill(headerInfo, (byte) ' ');

           in.getBytes(in.readerIndex(), headerInfo);
           String headerStr = new String(headerInfo, "UTF-8");
           if (headerStr.startsWith(NettoFrame.NETTO_HEADER_START)) {

               try {
                   String headerInfoContent = headerStr.substring(NettoFrame.NETTO_HEADER_START.length());
                   String[] headerSections = headerInfoContent.split("/");
                   if (headerSections.length == 3) {
                       String version = headerSections[0];
                       String headerContentSizeAsString = headerSections[1].trim();
                       String bodySizeAsString = headerSections[2].trim();
                       int headerContentSize = Integer.parseInt(headerContentSizeAsString);
                       int bodySize = Integer.parseInt(bodySizeAsString);
                       if (in.readableBytes() >= bodySize + headerContentSize + NettoFrame.HEADER_LENGTH) {
                           ByteBuf headerContent = in.retainedSlice(NettoFrame.HEADER_LENGTH, headerContentSize);
                           ByteBuf body = in.retainedSlice(NettoFrame.HEADER_LENGTH + headerContentSize, bodySize);
                           NettoFrame nettoMessage = new NettoFrame();
                           nettoMessage.setBodySize(bodySize);
                           nettoMessage.setBody(body);
                           nettoMessage.setHeaderContent(headerContent);
                           nettoMessage.setHeaderContentSize(headerContentSize);
                           out.add(nettoMessage);
                           in.readerIndex(NettoFrame.HEADER_LENGTH + headerContentSize + bodySize);
                       }
                   } else {
                       in.skipBytes(in.readableBytes());
                       throw new NettoDecoderException("header parse error:" + headerStr);
                   }
               } catch (Throwable t) {
                   logger.error("decode error:"+headerStr,t);
                   in.skipBytes(in.readableBytes());
                   throw new NettoDecoderException("decode error:" + headerStr);
                   
               }

           } else {

               in.skipBytes(in.readableBytes());
               throw new NettoDecoderException("header start error:" + headerStr);
           }

       }

   }
 
Example 19
Project: athena   File: JsonRpcReaderUtil.java   Source Code and License Vote up 4 votes
/**
 * Decode the bytes to Json object.
 * @param in input of bytes
 * @param out ouput of Json object list
 * @param jrContext context for the last decoding process
 * @throws IOException IOException
 * @throws JsonParseException JsonParseException
 */
public static void readToJsonNode(ByteBuf in, List<Object> out, JsonReadContext jrContext)
        throws JsonParseException, IOException {
    int lastReadBytes = jrContext.getLastReadBytes();
    if (lastReadBytes == 0) {
        if (in.readableBytes() < 4) {
            return;
        }
        checkEncoding(in);
    }

    int i = lastReadBytes + in.readerIndex();
    Stack<Byte> bufStack = jrContext.getBufStack();
    for (; i < in.writerIndex(); i++) {
        byte b = in.getByte(i);
        switch (b) {
        case '{':
            if (!isDoubleQuote(bufStack)) {
                bufStack.push(b);
                jrContext.setStartMatch(true);
            }
            break;
        case '}':
            if (!isDoubleQuote(bufStack)) {
                bufStack.pop();
            }
            break;
        case '"':
            if (in.getByte(i - 1) != '\\') {
                if (!bufStack.isEmpty() && bufStack.peek() != '"') {
                    bufStack.push(b);
                } else {
                    bufStack.pop();
                }
            }
            break;
        default:
            break;
        }

        if (jrContext.isStartMatch() && bufStack.isEmpty()) {
            ByteBuf buf = in.readSlice(i - in.readerIndex() + 1);
            JsonParser jf = new MappingJsonFactory().createParser(new ByteBufInputStream(buf));
            JsonNode jsonNode = jf.readValueAsTree();
            out.add(jsonNode);
            lastReadBytes = 0;
            jrContext.setLastReadBytes(lastReadBytes);
            break;
        }
    }

    if (i >= in.writerIndex()) {
        lastReadBytes = in.readableBytes();
        jrContext.setLastReadBytes(lastReadBytes);
    }
}
 
Example 20
Project: waterrower-core   File: ByteUtils.java   Source Code and License Vote up 2 votes
/**
 * Returns the data of the buffer as String for debug purposes.
 *
 * @param buffer The byte buffer.
 * @return The data of the buffer as String.
 */
public static String bufferToString(ByteBuf buffer) {
    return "ByteBuf[index=" + buffer.readerIndex() + ",bytes=" + buffer.readableBytes() + "]";
}