List of usage examples for io.netty.buffer ByteBuf bytesBefore
public abstract int bytesBefore(byte value);
From source file:com.eightkdata.mongowp.mongoserver.util.ByteBufUtil.java
License:Open Source License
/** * A method that reads 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.//w w w. j a v a2 s . c o m * * @param buffer * @return The C-String as a String object or null if there was no C-String in the ByteBuf */ public static String readCString(ByteBuf buffer) { int pos = buffer.bytesBefore(CSTRING_BYTE_TERMINATION); if (pos == -1) { return null; } byte[] bytes = new byte[pos]; buffer.readBytes(bytes); buffer.readByte(); // Discard the termination byte return new String(bytes, Charsets.UTF_8); }
From source file:com.ibasco.agql.core.utils.ByteBufUtils.java
License:Open Source License
public static String readString(ByteBuf buffer, Charset encoding, boolean readNonNullTerminated, String defaultString) {//from w ww . j av a 2 s .c o m int length = buffer.bytesBefore((byte) 0); if (length < 0) { if (readNonNullTerminated && buffer.readableBytes() > 0) length = buffer.readableBytes(); else return null; } String data = buffer.readCharSequence(length, encoding).toString(); //Discard the null terminator (if available) if (buffer.readableBytes() > 2 && buffer.getByte(buffer.readerIndex()) == 0) buffer.readByte(); return data; }
From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceRconPacketDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { final String separator = "================================================================================================="; //TODO: Move all code logic below to SourceRconPacketBuilder log.debug(separator);/*from w w w . j ava 2 s. c o m*/ log.debug(" ({}) DECODING INCOMING DATA : Bytes Received = {} {}", index.incrementAndGet(), in.readableBytes(), index.get() > 1 ? "[Continuation]" : ""); log.debug(separator); String desc = StringUtils.rightPad("Minimum allowable size?", PAD_SIZE); //Verify we have the minimum allowable size if (in.readableBytes() < 14) { log.debug(" [ ] {} = NO (Actual Readable Bytes: {})", desc, in.readableBytes()); return; } log.debug(" [x] {} = YES (Actual Readable Bytes: {})", desc, in.readableBytes()); //Reset if this happens to be not a valid source rcon packet in.markReaderIndex(); //Read and Verify size desc = StringUtils.rightPad("Bytes received at least => than the \"declared\" size?", PAD_SIZE); int size = in.readIntLE(); int readableBytes = in.readableBytes(); if (readableBytes < size) { log.debug(" [ ] {} = NO (Declared Size: {}, Actual Bytes Read: {})", desc, readableBytes, size); in.resetReaderIndex(); return; } log.debug(" [x] {} = YES (Declared Size: {}, Actual Bytes Read: {})", desc, readableBytes, size); //Read and verify request id desc = StringUtils.rightPad("Request Id within the valid range?", PAD_SIZE); int id = in.readIntLE(); if (!(id == -1 || id == SourceRconUtil.RCON_TERMINATOR_RID || SourceRconUtil.isValidRequestId(id))) { log.debug(" [ ] {} = NO (Actual: {})", desc, id); in.resetReaderIndex(); return; } log.debug(" [x] {} = YES (Actual: {})", desc, id); //Read and verify request type desc = StringUtils.rightPad("Valid response type?", PAD_SIZE); int type = in.readIntLE(); if (get(type) == null) { log.debug(" [ ] {} = NO (Actual: {})", desc, type); in.resetReaderIndex(); return; } log.debug(" [x] {} = YES (Actual: {} = {})", desc, type, SourceRconResponseType.get(type)); //Read and verify body desc = StringUtils.rightPad("Contains Body?", PAD_SIZE); int bodyLength = in.bytesBefore((byte) 0); String body = StringUtils.EMPTY; if (bodyLength <= 0) log.debug(" [ ] {} = NO", desc); else { body = in.readCharSequence(bodyLength, StandardCharsets.UTF_8).toString(); log.debug(" [x] {} = YES (Length: {}, Body: {})", desc, bodyLength, StringUtils.replaceAll(StringUtils.truncate(body, 30), "\n", "\\\\n")); } //Peek at the last two bytes and verify that they are null-bytes byte bodyTerminator = in.getByte(in.readerIndex()); byte packetTerminator = in.getByte(in.readerIndex() + 1); desc = StringUtils.rightPad("Contains TWO null-terminating bytes at the end?", PAD_SIZE); //Make sure the last two bytes are NULL bytes (request id: 999 is reserved for split packet responses) if ((bodyTerminator != 0 || packetTerminator != 0) && (id == SourceRconUtil.RCON_TERMINATOR_RID)) { log.debug("Skipping {} bytes", in.readableBytes()); in.skipBytes(in.readableBytes()); return; } else if (bodyTerminator != 0 || packetTerminator != 0) { log.debug(" [ ] {} = NO (Actual: Body Terminator = {}, Packet Terminator = {})", desc, bodyTerminator, packetTerminator); in.resetReaderIndex(); return; } else { log.debug(" [x] {} = YES (Actual: Body Terminator = {}, Packet Terminator = {})", desc, bodyTerminator, packetTerminator); //All is good, skip the last two bytes if (in.readableBytes() >= 2) in.skipBytes(2); } //At this point, we can now construct a packet log.debug(" [x] Status: PASS (Size = {}, Id = {}, Type = {}, Remaining Bytes = {}, Body Size = {})", size, id, type, in.readableBytes(), bodyLength); log.debug(separator); //Reset the index index.set(0); //Construct the response packet and send to the next handlers SourceRconResponsePacket responsePacket; //Did we receive a terminator packet? if (this.terminatingPacketsEnabled && id == SourceRconUtil.RCON_TERMINATOR_RID && StringUtils.isBlank(body)) { responsePacket = new SourceRconTermResponsePacket(); } else { responsePacket = SourceRconPacketBuilder.getResponsePacket(type); } if (responsePacket != null) { responsePacket.setSize(size); responsePacket.setId(id); responsePacket.setType(type); responsePacket.setBody(body); log.debug( "Decode Complete. Passing response for request id : '{}' to the next handler. Remaining bytes ({})", id, in.readableBytes()); out.add(responsePacket); } }
From source file:com.navercorp.nbasearc.gcp.RedisDecoder.java
License:Apache License
private int lineLength(ByteBuf in) { int readableBytes = in.readableBytes(); if (readableBytes < 2) { return -1; }/*from w ww . jav a 2s.c om*/ /* CR */ int length = in.bytesBefore(CR_BYTE); if (length < 0) { return -1; } if (readableBytes < length + 2) { return -1; } /* LF */ byte eolLF = in.getByte(in.readerIndex() + length + 1); if (eolLF != LF_BYTE) { throw new RuntimeException("Redis protocol exception; malformed end of line; byte=" + eolLF); } return length + 2; }
From source file:com.tesora.dve.db.mysql.libmy.MyHandshakeV10.java
License:Open Source License
@Override public void unmarshallMessage(ByteBuf cb) { protocolVersion = cb.readByte();//from w w w . ja v a2 s .co m serverVersion = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8); cb.skipBytes(1); // skip the NULL terminator threadID = cb.readInt(); scrambleBuffer1st = MysqlAPIUtils.readBytesAsString(cb, 8, CharsetUtil.ISO_8859_1); cb.skipBytes(1); long sc1 = cb.readUnsignedShort(); serverCharset = cb.readByte(); serverStatus = cb.readShort(); long sc2 = Long.rotateLeft(cb.readUnsignedShort(), 16); setServerCapabilities(sc1 + sc2); scrambleBufferSize = new Integer(cb.readByte()); cb.skipBytes(10); //unused bytes scrambleBuffer2nd = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.ISO_8859_1); cb.skipBytes(1); if ((serverCapabilitiesasLong & ClientCapabilities.CLIENT_PLUGIN_AUTH) == ClientCapabilities.CLIENT_PLUGIN_AUTH) { plugInProvidedData = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8); } }
From source file:com.tesora.dve.db.mysql.libmy.MyLoginRequest.java
License:Open Source License
@Override public void unmarshallMessage(ByteBuf cb) { clientCapabilities = cb.readUnsignedInt(); boolean hasConnectDatabase = ((clientCapabilities & ClientCapabilities.CLIENT_CONNECT_WITH_DB) == ClientCapabilities.CLIENT_CONNECT_WITH_DB); maxPacketSize = cb.readInt();/* w ww. j av a2s. c o m*/ clientCharset = cb.readByte(); cb.skipBytes(23); // login request has a 23 byte filler username = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8); cb.skipBytes(1); // skip the NULL terminator byte passwordLength = cb.readByte(); byte[] passwordBytes = new byte[passwordLength]; cb.getBytes(cb.readerIndex(), passwordBytes, 0, passwordLength); password = new String(passwordBytes, CharsetUtil.ISO_8859_1); cb.skipBytes(passwordLength); // if the clientCapabilities flag has the CLIENT_CONNECT_WITH_DB bit set, // then this message contains an initial database to connect to if (hasConnectDatabase) { database = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8); if (database.length() < 1) { database = null; } } }
From source file:com.tesora.dve.db.mysql.portal.protocol.MSPAuthenticateV10MessageMessage.java
License:Open Source License
@Override protected ParsedData unmarshall(ByteBuf source) { ParsedData parseValues = new ParsedData(); parseValues.caps = new ClientCapabilities(source.readUnsignedInt()); parseValues.maxPacketSize = source.readInt(); parseValues.charsetID = source.readByte(); source.skipBytes(23); // login request has a 23 byte filler parseValues.username = source.readSlice(source.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8); source.skipBytes(1); // skip the NULL terminator byte passwordLength = source.readByte(); parseValues.password = source.readSlice(passwordLength).toString(CharsetUtil.ISO_8859_1); // if the clientCapabilities flag has the CLIENT_CONNECT_WITH_DB bit set, // then this message contains an initial database to connect to if (parseValues.caps.connectWithDB()) { parseValues.initialDatabase = source.readSlice(source.bytesBefore((byte) 0)) .toString(CharsetUtil.UTF_8); source.skipBytes(1); // skip the NULL terminator } else {//from w ww.j av a 2 s . c om parseValues.initialDatabase = ""; } return parseValues; }
From source file:com.tesora.dve.mysqlapi.repl.messages.MyStatusVariables.java
License:Open Source License
public void parseStatusVariables(ByteBuf cb, int svLen) throws PEException { if (svLen > 0) { ByteBuf statsVarsBuf = cb.readBytes(svLen); while (statsVarsBuf.isReadable()) { byte code = statsVarsBuf.readByte(); MyQueryEventCode mqec = MyQueryEventCode.fromByte(code); if (mqec == null) { throw new PEException("Replication could not decode query event code: '" + code + "' (0x" + Integer.toHexString(code) + ")"); }/* w w w .jav a2 s . c o m*/ switch (mqec) { case Q_FLAGS2_CODE: int flags = statsVarsBuf.readInt(); suppliedEventCodes.add(new QueryFlags2Event(flags)); break; case Q_SQL_MODE_CODE: long sqlMode = statsVarsBuf.readLong(); suppliedEventCodes.add(new QuerySQLModeEvent(sqlMode)); break; case Q_CATALOG_CODE: { byte len = statsVarsBuf.readByte(); String catalog = MysqlAPIUtils.readBytesAsString(statsVarsBuf, len, CharsetUtil.UTF_8); statsVarsBuf.readByte(); // null terminated byte suppliedEventCodes.add(new QueryCatalogEvent(catalog)); break; } case Q_AUTO_INCREMENT: int autoIncrementIncrement = statsVarsBuf.readUnsignedShort(); int autoIncrementOffset = statsVarsBuf.readUnsignedShort(); suppliedEventCodes .add(new QueryAutoIncrementEvent(autoIncrementIncrement, autoIncrementOffset)); break; case Q_CHARSET_CODE: int charSetClient = statsVarsBuf.readUnsignedShort(); int collationConnection = statsVarsBuf.readUnsignedShort(); int collationServer = statsVarsBuf.readUnsignedShort(); suppliedEventCodes .add(new QueryCharSetCodeEvent(charSetClient, collationConnection, collationServer)); break; case Q_TIME_ZONE_CODE: { byte len = statsVarsBuf.readByte(); String timeZone = MysqlAPIUtils.readBytesAsString(statsVarsBuf, len, CharsetUtil.UTF_8); suppliedEventCodes.add(new QueryTimeZoneCodeEvent(timeZone)); break; } case Q_CATALOG_NZ_CODE: { byte catalogLen = statsVarsBuf.readByte(); String catalog = MysqlAPIUtils.readBytesAsString(statsVarsBuf, catalogLen, CharsetUtil.UTF_8); suppliedEventCodes.add(new QueryCatalogNZEvent(catalog)); break; } case Q_LC_TIME_NAMES_CODE: short monthDayNames = statsVarsBuf.readShort(); suppliedEventCodes.add(new QueryTimeNamesEvent(monthDayNames)); break; case Q_CHARSET_DATABASE_CODE: short collationDatabase = statsVarsBuf.readShort(); suppliedEventCodes.add(new QueryCollationDatabaseEvent(collationDatabase)); break; case Q_TABLE_MAP_FOR_UPDATE_CODE: long tableMapForUpdate = statsVarsBuf.readLong(); suppliedEventCodes.add(new QueryTableMapEvent(tableMapForUpdate)); break; case Q_MASTER_DATA_WRITTEN_CODE: int originalLength = statsVarsBuf.readInt(); suppliedEventCodes.add(new QueryMasterDataWrittenEvent(originalLength)); break; case Q_INVOKER: int userLen = statsVarsBuf.readByte(); String user = MysqlAPIUtils.readBytesAsString(statsVarsBuf, userLen, CharsetUtil.UTF_8); int hostLen = statsVarsBuf.readByte(); String host = MysqlAPIUtils.readBytesAsString(statsVarsBuf, hostLen, CharsetUtil.UTF_8); suppliedEventCodes.add(new QueryInvokerEvent(user, host)); break; case Q_UPDATED_DB_NAMES: List<String> dbNames = new ArrayList<String>(); int numDbs = statsVarsBuf.readByte(); if (numDbs > 0) { for (int i = 0; i < numDbs; i++) { dbNames.add(statsVarsBuf.readSlice(statsVarsBuf.bytesBefore((byte) 0)) .toString(CharsetUtil.UTF_8)); statsVarsBuf.readByte(); //read null byte } } suppliedEventCodes.add(new QueryUpdatedDBNamesEvent(dbNames)); break; case Q_MICROSECONDS: int microseconds = statsVarsBuf.readMedium(); suppliedEventCodes.add(new QueryMicrosecondsEvent(microseconds)); break; case Q_HRNOW: //TODO: this was apparently added for MariaDB, but I can't find a lot of info on it. skip for now. suppliedEventCodes.add(new QueryMicrosecondsEvent(statsVarsBuf.readUnsignedMedium())); break; default: throw new PEException("Replication encountered an unknown query event code: '" + code + "' (0x" + Integer.toHexString(code) + ")"); } } } }
From source file:com.zextras.modules.chat.server.xmpp.netty.XmlSubTagTokenizer.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> objects) throws Exception { int idx = byteBuf.bytesBefore(sTokenEnd); if (idx == -1) { return;//from w w w . ja v a 2s . c o m } String token = byteBuf.toString(0, idx + 1, mCharset); byteBuf.readerIndex(byteBuf.readerIndex() + idx + 1); byteBuf.discardReadBytes(); objects.add(token); }
From source file:io.crate.protocols.postgres.PostgresWireProtocol.java
License:Apache License
@Nullable static String readCString(ByteBuf buffer) { byte[] bytes = new byte[buffer.bytesBefore((byte) 0) + 1]; if (bytes.length == 0) { return null; }//from ww w. ja v a2 s . com buffer.readBytes(bytes); return new String(bytes, 0, bytes.length - 1, StandardCharsets.UTF_8); }