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

The following are Jave code examples for showing how to use getByte() 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: dremio-oss   File: DremioStringUtils.java   Source Code and License Vote up 6 votes
/**
 * Parses a hex encoded binary string and write to an output buffer.
 *
 * This function does not modify  the {@code readerIndex} and {@code writerIndex}
 * of the byte buffer.
 *
 * @return Index in the byte buffer just after the last written byte.
 */
public static int parseBinaryString(ByteBuf str, int strStart, int strEnd, ByteBuf out) {
  int dstEnd = 0;
  for (int i = strStart; i < strEnd; i++) {
    byte b = str.getByte(i);
    if (b == '\\'
        && strEnd > i+3
        && (str.getByte(i+1) == 'x' || str.getByte(i+1) == 'X')) {
      // ok, take next 2 hex digits.
      byte hd1 = str.getByte(i+2);
      byte hd2 = str.getByte(i+3);
      if (isHexDigit(hd1) && isHexDigit(hd2)) { // [a-fA-F0-9]
        // turn hex ASCII digit -> number
        b = (byte) ((toBinaryFromHex(hd1) << 4) + toBinaryFromHex(hd2));
        i += 3; // skip 3
      }
    }
    out.setByte(dstEnd++, b);
  }
  return dstEnd;
}
 
Example 2
Project: dremio-oss   File: DremioStringUtils.java   Source Code and License Vote up 6 votes
public static int parseBinaryStringNoFormat(ByteBuf str, int strStart, int strEnd, ByteBuf out) {
  int dstEnd = 0;

  if(((strStart - strEnd) % 2) != 0){
    throw UserException.functionError().message("Failure parsing hex string, length was not a multiple of two.").build(logger);
  }
  for (int i = strStart; i < strEnd; i+=2) {
    byte b1 = str.getByte(i);
    byte b2 = str.getByte(i+1);
    if(isHexDigit(b1) && isHexDigit(b2)){
      byte finalByte = (byte) ((toBinaryFromHex(b1) << 4) + toBinaryFromHex(b2));
      out.setByte(dstEnd++, finalByte);
    }else{
      throw UserException.functionError().message("Failure parsing hex string, one or more bytes was not a valid hex value.").build(logger);
    }
  }
  return dstEnd;
}
 
Example 3
Project: QDrill   File: DrillStringUtils.java   Source Code and License Vote up 6 votes
/**
 * In-place parsing of a hex encoded binary string.
 *
 * This function does not modify  the {@code readerIndex} and {@code writerIndex}
 * of the byte buffer.
 *
 * @return Index in the byte buffer just after the last written byte.
 */
public static int parseBinaryString(ByteBuf str, int strStart, int strEnd) {
  int length = (strEnd - strStart);
  int dstEnd = strStart;
  for (int i = strStart; i < length ; i++) {
    byte b = str.getByte(i);
    if (b == '\\'
        && length > i+3
        && (str.getByte(i+1) == 'x' || str.getByte(i+1) == 'X')) {
      // ok, take next 2 hex digits.
      byte hd1 = str.getByte(i+2);
      byte hd2 = str.getByte(i+3);
      if (isHexDigit(hd1) && isHexDigit(hd2)) { // [a-fA-F0-9]
        // turn hex ASCII digit -> number
        b = (byte) ((toBinaryFromHex(hd1) << 4) + toBinaryFromHex(hd2));
        i += 3; // skip 3
      }
    }
    str.setByte(dstEnd++, b);
  }
  return dstEnd;
}
 
Example 4
Project: reactive-pg-client   File: InitiateSslHandler.java   Source Code and License Vote up 6 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  // This must be a single byte buffer - after that follow the SSL handshake
  ByteBuf byteBuf = (ByteBuf) msg;
  byte b = byteBuf.getByte(0);
  byteBuf.release();
  switch (b) {
    case SSL_YES: {
      conn.upgradeToSSL(v -> {
        ctx.pipeline().remove(this);
        upgradeFuture.complete();
      });
      break;
    }
    case SSL_NO: {
      // This case is not tested as our test db is configured for SSL
      ctx.fireExceptionCaught(new Exception("Postgres does not handle SSL"));
      break;
    }
    default:
      ctx.fireExceptionCaught(new Exception("Invalid connection data"));
      break;
  }
}
 
Example 5
Project: dremio-oss   File: StringFunctionUtil.java   Source Code and License Vote up 6 votes
public static int stringLeftMatchUTF8(ByteBuf str, int strStart, int strEnd,
                                  ByteBuf substr, int subStart, int subEnd, int offset) {
  for (int i = strStart + offset; i <= strEnd - (subEnd - subStart); i++) {
    int j = subStart;
    for (; j< subEnd; j++) {
      if (str.getByte(i + j - subStart) != substr.getByte(j)) {
        break;
      }
    }

    if (j == subEnd  && j!= subStart) {  // found a matched substr (non-empty) in str.
      return i;   // found a match.
    }
  }

  return -1;
}
 
Example 6
Project: dremio-oss   File: StringFunctionUtil.java   Source Code and License Vote up 5 votes
public static int utf8CharLen(ByteBuf buffer, int idx) {
  byte firstByte = buffer.getByte(idx);
  if (firstByte >= 0) { // 1-byte char. First byte is 0xxxxxxx.
    return 1;
  } else if ((firstByte & 0xE0) == 0xC0) { // 2-byte char. First byte is 110xxxxx
    return 2;
  } else if ((firstByte & 0xF0) == 0xE0) { // 3-byte char. First byte is 1110xxxx
    return 3;
  } else if ((firstByte & 0xF8) == 0xF0) { //4-byte char. First byte is 11110xxx
    return 4;
  }
  throw new RuntimeException("Unexpected byte 0x" + Integer.toString(firstByte & 0xff, 16)
      + " at position " + idx + " encountered while decoding UTF8 string.");
}
 
Example 7
Project: ClusterDeviceControlPlatform   File: CanFrameChannelInboundHandler.java   Source Code and License Vote up 5 votes
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {

    int remainder = msg.readableBytes() % 13;

    if (remainder == 0 && (msg.getByte(0) & 0xF0) == 0x80 & msg.getByte(1) == 0x00) {
        processByteBuf(ctx, msg);
        return;
    }

    if (remainder != 0 && index == 0 && (msg.getByte(0) & 0xF0) == 0x80 & msg.getByte(1) == 0x00) {
        logger.warn("读取到非整数个 CAN 帧");
        processByteBuf(ctx, msg);
        cacheRemainByte(msg);
        return;
    }

    if (index != 0) {
        if (cacheRemainByte(msg)) {
            ByteBuf byteBuf = Unpooled.copiedBuffer(bytes);
            if ((byteBuf.getByte(0) & 0xF0) == 0x80 & byteBuf.getByte(1) == 0x00) {
                processByteBuf(ctx, byteBuf);
            }
        }
        remainder = msg.readableBytes() % 13;
        if (remainder == 0) {
            System.out.println("lml");
        }
        if (remainder == 0 && (msg.getByte(msg.readerIndex()) & 0xF0) == 0x80 & msg.getByte(msg.readerIndex() + 1) == 0x00) {
            processByteBuf(ctx, msg);
            return;
        }
        return;
    }
}
 
Example 8
Project: QDrill   File: StringFunctionUtil.java   Source Code and License Vote up 5 votes
public static int utf8CharLen(ByteBuf buffer, int idx) {
  byte firstByte = buffer.getByte(idx);
  if (firstByte >= 0) { // 1-byte char. First byte is 0xxxxxxx.
    return 1;
  } else if ((firstByte & 0xE0) == 0xC0) { // 2-byte char. First byte is 110xxxxx
    return 2;
  } else if ((firstByte & 0xF0) == 0xE0) { // 3-byte char. First byte is 1110xxxx
    return 3;
  } else if ((firstByte & 0xF8) == 0xF0) { //4-byte char. First byte is 11110xxx
    return 4;
  }
  throw new DrillRuntimeException("Unexpected byte 0x" + Integer.toString((int)firstByte & 0xff, 16)
      + " at position " + idx + " encountered while decoding UTF8 string.");
}
 
Example 9
Project: NettyStudy   File: ByteBufExamples.java   Source Code and License Vote up 5 votes
/**
 * Listing 5.6
 */
public static void byteBufRelativeAccess(ByteBuf buffer) {
    for (int i = 0; i < buffer.capacity(); i++) {
        byte b = buffer.getByte(i);
        System.out.println((char) b);
    }

}
 
Example 10
Project: NioSmtpClient   File: CrlfTerminatingChunkedStream.java   Source Code and License Vote up 5 votes
private boolean isTerminatedWithCrLf(ByteBuf chunk) {
  int length = chunk.readableBytes();

  return length >= 2 &&
      chunk.getByte(length - 2) == CR &&
      chunk.getByte(length - 1) == LF;
}
 
Example 11
Project: NioSmtpClient   File: DotStuffing.java   Source Code and License Vote up 5 votes
private static int findDotAtBeginningOfLine(ByteBuf buffer, int startAt, byte[] previousBytes) {
  int length = buffer.readableBytes();

  if (previousBytes[0] == CR && previousBytes[1] == LF && buffer.getByte(startAt) == DOT) {
    return startAt;
  }

  if (previousBytes[1] == CR && length >= 2 && buffer.getByte(startAt) == LF && buffer.getByte(startAt + 1) == DOT) {
    return startAt + 1;
  }

  int i = startAt;
  while (++i < length) {
    i = buffer.forEachByte(i, length - i, ByteProcessor.FIND_LF);
    if (i == -1) {
      return -1;
    }

    if (buffer.getByte(i - 1) == CR) {
      if (i + 1 < length && buffer.getByte(i + 1) == DOT) {
        return i + 1;
      } else {
        continue;
      }
    }
  }

  return -1;
}
 
Example 12
Project: NioSmtpClient   File: DotStuffingChunkedStream.java   Source Code and License Vote up 5 votes
private void updateTrailingBytes(ByteBuf chunk) {
  if (chunk.readableBytes() == 0) {
    return;
  }

  if (chunk.readableBytes() == 1) {
    trailingBytes[0] = trailingBytes[1];
    trailingBytes[1] = chunk.getByte(0);
    return;
  }

  trailingBytes[0] = chunk.getByte(chunk.readableBytes() - 2);
  trailingBytes[1] = chunk.getByte(chunk.readableBytes() - 1);
}
 
Example 13
Project: athena   File: JsonRpcReaderUtil.java   Source Code and License Vote up 5 votes
/**
 * Filter the invalid characters before decoding.
 * @param in input of bytes
 * @param lastReadBytes the bytes for last decoding incomplete record
 */
private static void fliterCharaters(ByteBuf in) {
    while (in.isReadable()) {
        int ch = in.getByte(in.readerIndex());
        if ((ch != ' ') && (ch != '\n') && (ch != '\t') && (ch != '\r')) {
            break;
        } else {
            in.readByte();
        }
    }
}
 
Example 14
Project: proxyee   File: HttpProxyServerHandle.java   Source Code and License Vote up 4 votes
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
  if (msg instanceof HttpRequest) {
    HttpRequest request = (HttpRequest) msg;
    //第一次建立连接取host和端口号和处理代理握手
    if (status == 0) {
      RequestProto requestProto = ProtoUtil.getRequestProto(request);
      if (requestProto == null) { //bad request
        ctx.channel().close();
        return;
      }
      status = 1;
      this.host = requestProto.getHost();
      this.port = requestProto.getPort();
      if ("CONNECT".equalsIgnoreCase(request.method().name())) {//建立代理握手
        status = 2;
        HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
            HttpProxyServer.SUCCESS);
        ctx.writeAndFlush(response);
        ctx.channel().pipeline().remove("httpCodec");
        return;
      }
    }
    interceptPipeline = buildPiepeline();
    interceptPipeline.setRequestProto(new RequestProto(host, port, isSsl));
    interceptPipeline.beforeRequest(ctx.channel(), request);
  } else if (msg instanceof HttpContent) {
    if (status != 2) {
      interceptPipeline.beforeRequest(ctx.channel(), (HttpContent) msg);
    } else {
      status = 1;
    }
  } else { //ssl和websocket的握手处理
    ByteBuf byteBuf = (ByteBuf) msg;
    if (byteBuf.getByte(0) == 22) {//ssl握手
      isSsl = true;
      SslContext sslCtx = SslContextBuilder
          .forServer(serverConfig.getServerPriKey(), CertPool.getCert(this.host, serverConfig))
          .build();
      ctx.pipeline().addFirst("httpCodec", new HttpServerCodec());
      ctx.pipeline().addFirst("sslHandle", sslCtx.newHandler(ctx.alloc()));
      //重新过一遍pipeline,拿到解密后的的http报文
      ctx.pipeline().fireChannelRead(msg);
      return;
    }
    handleProxyData(ctx.channel(), msg, false);
  }
}
 
Example 15
Project: neoscada   File: APDUDecoder.java   Source Code and License Vote up 4 votes
@Override
protected void decode ( final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out ) throws Exception
{
    if ( logger.isTraceEnabled () )
    {
        logger.trace ( "decode - bytes: {}", ByteBufUtil.hexDump ( in ) );
    }

    if ( in.readableBytes () < Constants.APCI_MIN_LENGTH )
    {
        return;
    }

    final byte start = in.getByte ( in.readerIndex () + 0 );
    if ( start != Constants.START_BYTE )
    {
        throw new DecoderException ( String.format ( "ACPI must start with 0x%02x but did with 0x%02x", Constants.START_BYTE, start ) );
    }

    final short len = in.getUnsignedByte ( in.readerIndex () + 1 );

    if ( len > Constants.APCI_MAX_DATA_LENGTH )
    {
        throw new DecoderException ( String.format ( "APCI has a maximum length of %s bytes, but we received %s", Constants.APCI_MAX_DATA_LENGTH, len ) );
    }

    if ( in.readableBytes () < len + 2 )
    {
        return;
    }

    // we have the full InformationTransfer

    // skip start & len
    in.skipBytes ( 2 );

    // read control fields
    final ByteBuf controlFields = in.readSlice ( 4 );

    final ByteBuf data;
    if ( len > 4 )
    {
        data = Unpooled.copiedBuffer ( in.readSlice ( len - 4 ) ).order ( ByteOrder.LITTLE_ENDIAN );
    }
    else
    {
        data = null;
    }

    // now add the PDU

    out.add ( decode ( controlFields, data ) );
}
 
Example 16
Project: sbrw-freeroam-srv   File: PlayerInfoHandler.java   Source Code and License Vote up 4 votes
private boolean isPlayerInfoPacket(ByteBuf buf) {
	return (buf.getByte(2) == (byte) 0x07);
}
 
Example 17
Project: JavaNRPC   File: NrpcDecoder.java   Source Code and License Vote up 4 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    int readable = in.readableBytes();
    if (readable > Constants.MAX_FRAME_SIZE) {
        logger.error("Frame too big : {}, max is {}",new Object[]{readable,Constants.MAX_FRAME_SIZE});
        in.skipBytes(readable);
        ctx.close();
        throw new TooLongFrameException("Frame too big!");
    }
    int pos = 0;
    if(readable >= Constants.HEADER_SIZE){
        // 检查Magic number
        if(in.getByte(pos) == 'N' && in.getByte(pos+1) == 'R' && in.getByte(pos+2) == 'P' && in.getByte(pos+3) == 'C'){
        }else{
            logger.error("Wrong magic number!");
            in.skipBytes(readable);
            ctx.close();
            throw new WrongMagicNumException("Wrong magic number!");
        }
        int totalSize = (int)in.getUnsignedInt(pos+4);
        byte type = in.getByte(pos+8);
        if(type == 0){
            logger.debug("one request");
        }else if(type == 1){
            logger.debug("one response");
        }
        if(readable < totalSize ){
            return;
        }
        // 开始解码报文
        try{
            in.skipBytes(Constants.HEADER_SIZE);
            byte[] dest = new byte[totalSize-Constants.HEADER_SIZE];
            in.readBytes(dest);
            ByteArrayInputStream destByteInputStream = new ByteArrayInputStream(dest);
            NrpcMeta nrpcMeta = NrpcMeta.parseFrom(destByteInputStream);
            out.add(nrpcMeta);
        }catch(Exception ex) {
            logger.error(ex.getMessage(), ex);
            ctx.close();
            throw new DecodeException("NrpcMeta decode failed!");
        }
    }
}
 
Example 18
Project: NioSmtpClient   File: ByteBufMessageContent.java   Source Code and License Vote up 4 votes
private static boolean isTerminated(ByteBuf buffer) {
  int length = buffer.readableBytes();
  return length >= 2 && buffer.getByte(length - 2) == '\r' && buffer.getByte(length - 1) == '\n';
}
 
Example 19
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 20
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);
    }
}