Java Code Examples for io.netty.buffer.ByteBuf#bytesBefore()

The following examples show how to use io.netty.buffer.ByteBuf#bytesBefore() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HandshakeV10Request.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
private static ByteBuf readCStringRetainedSlice(ByteBuf buf) {
    int bytes = buf.bytesBefore(TERMINAL);

    if (bytes < 0) {
        throw new IllegalArgumentException("buf has no C-style string");
    }

    if (bytes == 0) {
        // skip terminal
        buf.skipBytes(1);
        // use EmptyByteBuf
        return buf.alloc().buffer(0, 0);
    }

    ByteBuf result = buf.readSlice(bytes);
    buf.skipBytes(1);
    return result.retain();
}
 
Example 2
Source File: HandshakeHeader.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
static String readCStringAscii(ByteBuf buf) {
    int length = buf.bytesBefore(TERMINAL);

    if (length < 0) {
        throw new IllegalArgumentException("buf has no C-style string terminal");
    }

    if (length == 0) {
        // skip terminal
        buf.skipBytes(1);
        return "";
    }

    String result = buf.toString(buf.readerIndex(), length, StandardCharsets.US_ASCII);
    buf.skipBytes(length + 1); // skip string and terminal by read

    return result;
}
 
Example 3
Source File: ByteBufJsonHelper.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
/**
 * Find the number of bytes until next occurrence of the character c
 * from the current {@link ByteBuf#readerIndex() readerIndex} in buf,
 * with the twist that if this occurrence is prefixed by the prefix
 * character, we try to find another occurrence.
 *
 * @param buf the {@link ByteBuf buffer} to look into.
 * @param c the character to search for.
 * @param prefix the character to trigger a retry.
 * @return the position of the first occurrence of c that is not prefixed by prefix
 * or -1 if none found.
 */
public static final int findNextCharNotPrefixedBy(ByteBuf buf, char c, char prefix) {
    int found =  buf.bytesBefore((byte) c);
    if (found < 1) {
        return found;
    } else {
        int from;
        while (found > -1 && (char) buf.getByte(
                buf.readerIndex() + found - 1) == prefix) {
            //advance from
            from = buf.readerIndex() + found + 1;
            //search again
            int next = buf.bytesBefore(from, buf.readableBytes() - from + buf.readerIndex(), (byte) c);
            if (next == -1) {
                return -1;
            } else {
                found += next + 1;
            }
        }
        return found;
    }
}
 
Example 4
Source File: HandshakeHeader.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
static String readCStringAscii(ByteBuf buf) {
    int length = buf.bytesBefore(TERMINAL);

    if (length < 0) {
        throw new IllegalArgumentException("buf has no C-style string terminal");
    }

    if (length == 0) {
        // skip terminal
        buf.skipBytes(1);
        return "";
    }

    String result = buf.toString(buf.readerIndex(), length, StandardCharsets.US_ASCII);
    buf.skipBytes(length + 1); // skip string and terminal by read

    return result;
}
 
Example 5
Source File: HandshakeV10Request.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
private static ByteBuf readCStringRetainedSlice(ByteBuf buf) {
    int bytes = buf.bytesBefore(TERMINAL);

    if (bytes < 0) {
        throw new IllegalArgumentException("buf has no C-style string");
    }

    if (bytes == 0) {
        // skip terminal
        buf.skipBytes(1);
        // use EmptyByteBuf
        return buf.alloc().buffer(0, 0);
    }

    ByteBuf result = buf.readSlice(bytes);
    buf.skipBytes(1);
    return result.retain();
}
 
Example 6
Source File: StompFrameDecoder.java    From hazelcastmq with Apache License 2.0 6 votes vote down vote up
/**
 * Reads any bytes in the buffer and discards them. When a {@link #NULL_CHAR}
 * is reached, the state will be reset for the start of the next frame. This
 * method is normally only used when a bad frame has been detected and should
 * be skipped; however in most cases if a bad frame is received a later
 * handler will send an error frame and terminate the connection per the STOMP
 * specification.
 *
 * @param in the input buffer to read from
 *
 * @return the next decoder state
 */
private DecoderState readAndDiscard(ByteBuf in) {

  DecoderState nextState = DecoderState.DISCARD_FRAME;

  int byteCount = in.bytesBefore((byte) NULL_CHAR);

  if (byteCount > -1) {
    // Skip all the bytes including the null character and move to the next
    // state.
    in.skipBytes(byteCount + 1);
    nextState = DecoderState.READ_CONTROL_CHARS;
  }
  else {
    // Clear the buffer, discarding all the data before the future null
    // character.
    in.readerIndex(in.writerIndex());
  }

  return nextState;
}
 
Example 7
Source File: PooledNettyStringReader.java    From mongowp with Apache License 2.0 5 votes vote down vote up
@Override
/**
 * A method that skips a C-string from a ByteBuf. This method modified the internal state of the
 * ByteBuf, advancing the read pointer to the position after the cstring.
 *
 * @param buffer
 * @throws com.eightkdata.mongowp.bson.netty.NettyBsonReaderException
 */
public void skipCString(ByteBuf buffer) throws NettyBsonReaderException {
  int bytesBefore = buffer.bytesBefore(CSTRING_BYTE_TERMINATION);
  if (bytesBefore == -1) {
    throw new NettyBsonReaderException("A cstring was expected but no 0x00 byte was found");
  }
  buffer.skipBytes(bytesBefore + 1);
}
 
Example 8
Source File: ReadTemplateService.java    From ethernet-ip with Apache License 2.0 5 votes vote down vote up
private String readNullTerminatedString(ByteBuf buffer) {
    int length = buffer.bytesBefore((byte) 0x00);

    if (length == -1) {
        return "";
    } else {
        String s = buffer.toString(buffer.readerIndex(), length, ASCII);
        buffer.skipBytes(length + 1);
        return s;
    }
}
 
Example 9
Source File: BufferUtils.java    From antsdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String readString(ByteBuf buf) {
    String s;
    int bytes = buf.bytesBefore((byte)0);
    if (bytes == -1) {
        // string might not be terminated by 0
        bytes = buf.readableBytes();
        s = buf.toString(buf.readerIndex(), bytes, Charset.defaultCharset());
        buf.skipBytes(bytes);
    }
    else {
        s = buf.toString(buf.readerIndex(), bytes, Charset.defaultCharset());
        buf.skipBytes(bytes+1);
    }
    return s;
}
 
Example 10
Source File: PostgresWireProtocol.java    From crate with Apache License 2.0 5 votes vote down vote up
@Nullable
static String readCString(ByteBuf buffer) {
    byte[] bytes = new byte[buffer.bytesBefore((byte) 0) + 1];
    if (bytes.length == 0) {
        return null;
    }
    buffer.readBytes(bytes);
    return new String(bytes, 0, bytes.length - 1, StandardCharsets.UTF_8);
}
 
Example 11
Source File: SyslogCodec.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private String decodeHostname ( final ByteBuf msg )
{
    // split by first space
    final int spaceIndex = msg.bytesBefore ( Constants.SP );
    if ( spaceIndex < 0 )
    {
        throw new CodecException ( "Unable to find hostname" );
    }

    final String hostname = msg.readSlice ( spaceIndex ).toString ( StandardCharsets.US_ASCII );

    msg.skipBytes ( 1 ); // SPACE

    return hostname;
}
 
Example 12
Source File: Socks4ServerDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a variable-length NUL-terminated string as defined in SOCKS4.
 */
private static String readString(String fieldName, ByteBuf in) {
    int length = in.bytesBefore(MAX_FIELD_LENGTH + 1, (byte) 0);
    if (length < 0) {
        throw new DecoderException("field '" + fieldName + "' longer than " + MAX_FIELD_LENGTH + " chars");
    }

    String value = in.readSlice(length).toString(CharsetUtil.US_ASCII);
    in.skipBytes(1); // Skip the NUL.

    return value;
}
 
Example 13
Source File: Util.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public static String readCString(ByteBuf src, Charset charset) {
  int len = src.bytesBefore(ZERO);
  String s = src.readCharSequence(len, charset).toString();
  src.readByte();
  return s;
}
 
Example 14
Source File: Util.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public static String readCStringUTF8(ByteBuf src) {
  int len = src.bytesBefore(ZERO);
  String s = src.readCharSequence(len, UTF_8).toString();
  src.readByte();
  return s;
}
 
Example 15
Source File: BufferUtils.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public static String readNullTerminatedString(ByteBuf buffer, Charset charset) {
  int len = buffer.bytesBefore(TERMINAL);
  String s = buffer.readCharSequence(len, charset).toString();
  buffer.readByte();
  return s;
}
 
Example 16
Source File: StompFrameDecoder.java    From hazelcastmq with Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * Reads a single line of UTF-8 text from the stream and returns once an EOL
 * is found. STOMP defines the EOL as a new line character with an optional
 * leading carriage return character. The EOL character(s) will be removed
 * from the returned data. If no EOL character is found, this method does not
 * read any data from the input buffer.
 * </p>
 * <p>
 * This method checks for too long frames.
 * </p>
 *
 * @param in the input buffer to read from
 *
 * @return the next decoder state or null if no EOL is available in the buffer
 */
private String readLine(ByteBuf in) {

  int bytesToRead;
  byte[] data = null;
  int bytesToSkip;

  if ((bytesToRead = in.bytesBefore((byte) LINE_FEED_CHAR)) > -1) {
    // Found the line feed.
    bytesToSkip = 1;

    // Check (and ignore) optional carriage return.
    if (bytesToRead > 0 && in.getByte(bytesToRead - 1) == CARRIAGE_RETURN_CHAR) {
      bytesToSkip++;
      bytesToRead--;
    }

    // Check that the bytes we're about to read will not exceed the
    // max frame size.
    checkTooLongFrame(bytesToRead);

    data = new byte[bytesToRead];
    in.readBytes(data);
    in.skipBytes(bytesToSkip);

    // Count the bytes read.
    currentDecodedByteCount += bytesToRead;
  }
  else {
    // No line feed. Make sure we're not buffering more than the max
    // frame size.
    checkTooLongFrame(in.readableBytes());
  }

  if (data != null) {
    return new String(data, StompConstants.UTF_8);
  }
  else {
    return null;
  }
}
 
Example 17
Source File: HandshakeV10Request.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
private static HandshakeV10Request afterCapabilities(
    Builder builder, ByteBuf buf, int serverCapabilities, CompositeByteBuf salt
) {
    short saltSize;
    boolean isPluginAuth = (serverCapabilities & Capabilities.PLUGIN_AUTH) != 0;

    if (isPluginAuth) {
        saltSize = buf.readUnsignedByte();
    } else {
        saltSize = 0;
        // If PLUGIN_AUTH flag not exists, MySQL server will return 0x00 always.
        buf.skipBytes(1);
    }

    // Reserved field, all bytes are 0x00.
    buf.skipBytes(RESERVED_SIZE);

    if ((serverCapabilities & Capabilities.SECURE_CONNECTION) != 0) {
        int saltSecondPartSize = Math.max(MIN_SALT_SECOND_PART_SIZE, saltSize - salt.readableBytes() - 1);
        ByteBuf saltSecondPart = buf.readSlice(saltSecondPartSize);
        // Always 0x00, and it is not the part of salt, ignore.
        buf.skipBytes(1);

        // No need release salt second part, it will release with `salt`.
        salt.addComponent(true, saltSecondPart.retain());
    }

    builder.salt(ByteBufUtil.getBytes(salt));

    if (isPluginAuth) {
        // See also MySQL bug 59453, auth type native name has no terminal character in
        // version less than 5.5.10, or version greater than 5.6.0 and less than 5.6.2
        // And MySQL only support "mysql_native_password" in those versions that has the
        // bug, maybe just use constant "mysql_native_password" without read?
        int length = buf.bytesBefore(TERMINAL);
        String authType = length < 0 ? buf.toString(StandardCharsets.US_ASCII) :
            (length == 0 ? "" : buf.toString(buf.readerIndex(), length, StandardCharsets.US_ASCII));

        builder.authType(authType);
    } else {
        builder.authType(MySqlAuthProvider.NO_AUTH_PROVIDER);
    }

    return builder.build();
}
 
Example 18
Source File: CommandDecoder.java    From redisson with Apache License 2.0 4 votes vote down vote up
private String readString(ByteBuf in) {
    int len = in.bytesBefore((byte) '\r');
    String result = in.toString(in.readerIndex(), len, CharsetUtil.UTF_8);
    in.skipBytes(len + 2);
    return result;
}
 
Example 19
Source File: HandshakeV10Request.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
private static HandshakeV10Request afterCapabilities(
    Builder builder, ByteBuf buf, int serverCapabilities, CompositeByteBuf salt
) {
    short saltSize;
    boolean isPluginAuth = (serverCapabilities & Capabilities.PLUGIN_AUTH) != 0;

    if (isPluginAuth) {
        saltSize = buf.readUnsignedByte();
    } else {
        saltSize = 0;
        // If PLUGIN_AUTH flag not exists, MySQL server will return 0x00 always.
        buf.skipBytes(1);
    }

    // Reserved field, all bytes are 0x00.
    buf.skipBytes(RESERVED_SIZE);

    if ((serverCapabilities & Capabilities.SECURE_CONNECTION) != 0) {
        int saltSecondPartSize = Math.max(MIN_SALT_SECOND_PART_SIZE, saltSize - salt.readableBytes() - 1);
        ByteBuf saltSecondPart = buf.readSlice(saltSecondPartSize);
        // Always 0x00, and it is not the part of salt, ignore.
        buf.skipBytes(1);

        // No need release salt second part, it will release with `salt`.
        salt.addComponent(true, saltSecondPart.retain());
    }

    builder.salt(ByteBufUtil.getBytes(salt));

    if (isPluginAuth) {
        // See also MySQL bug 59453, auth type native name has no terminal character in
        // version less than 5.5.10, or version greater than 5.6.0 and less than 5.6.2
        // And MySQL only support "mysql_native_password" in those versions that has the
        // bug, maybe just use constant "mysql_native_password" without read?
        int length = buf.bytesBefore(TERMINAL);
        String authType = length < 0 ? buf.toString(StandardCharsets.US_ASCII) :
            (length == 0 ? "" : buf.toString(buf.readerIndex(), length, StandardCharsets.US_ASCII));

        builder.authType(authType);
    } else {
        builder.authType(MySqlAuthProvider.NO_AUTH_PROVIDER);
    }

    return builder.build();
}
 
Example 20
Source File: ByteBufJsonHelper.java    From couchbase-jvm-core with Apache License 2.0 2 votes vote down vote up
/**
 * Shorthand for {@link ByteBuf#bytesBefore(byte)} with a simple char c,
 * finds the number of bytes until next occurrence of
 * the character c from the current readerIndex() in buf.
 *
 * @param buf the {@link ByteBuf buffer} to look into.
 * @param c the character to search for.
 * @return the number of bytes before the character or -1 if not found.
 * @see ByteBuf#bytesBefore(byte)
 */
public static final int findNextChar(ByteBuf buf, char c) {
    return buf.bytesBefore((byte) c);
}