List of usage examples for io.netty.buffer ByteBuf readCharSequence
public abstract CharSequence readCharSequence(int length, Charset charset);
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) {/* w w w . ja v 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.core.utils.ByteBufUtils.java
License:Open Source License
public static String readStringToEnd(ByteBuf buffer, Charset encoding) { int length = buffer.readableBytes(); if (length > 0) return buffer.readCharSequence(length, encoding).toString(); return null;/*from w w w . java 2s . c o m*/ }
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 www .j a va 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.ibasco.agql.protocols.valve.source.query.SourceRconPacketBuilder.java
License:Open Source License
@SuppressWarnings("unchecked") @Override//w w w. j a v a 2 s . c o m public <T extends SourceRconPacket> T construct(ByteBuf data) { try { if (data.readableBytes() < 14) { log.warn("Packet is less than 10 bytes. Unsupported packet."); if (log.isDebugEnabled()) log.debug("Unrecognized Packet: \n{}", ByteBufUtil.prettyHexDump(data)); return null; } //Remember the reader index data.markReaderIndex(); //Read from the listen data.readerIndex(0); int size = data.readIntLE(); int id = data.readIntLE(); int type = data.readIntLE(); String body = data.readCharSequence(data.readableBytes() - 2, StandardCharsets.UTF_8).toString(); SourceRconResponsePacket packet = getResponsePacket(type); if (packet != null) { //Ok, we have a valid response packet. Lets keep reading. packet.setId(id); packet.setSize(size); packet.setType(type); packet.setBody(body); return (T) packet; } } finally { //Reset the index data.resetReaderIndex(); } return null; }
From source file:io.airlift.drift.transport.netty.codec.HeaderTransport.java
License:Apache License
private static String readString(ByteBuf messageHeader) { int length = readVariableLengthInt(messageHeader); return messageHeader.readCharSequence(length, UTF_8).toString(); }
From source file:io.reactiverse.pgclient.impl.codec.util.Util.java
License:Apache License
public static String readCString(ByteBuf src, Charset charset) { int len = src.bytesBefore(ZERO); String s = src.readCharSequence(len, charset).toString(); src.readByte();/*w w w . j a v a 2s .c o m*/ return s; }
From source file:io.reactiverse.pgclient.impl.codec.util.Util.java
License:Apache License
public static String readCStringUTF8(ByteBuf src) { int len = src.bytesBefore(ZERO); String s = src.readCharSequence(len, UTF_8).toString(); src.readByte();//from w ww . j a v a 2 s . co m return s; }
From source file:org.pumpkindb.examples.todolist.Main.java
License:Mozilla Public License
private static boolean hasPrefix(byte[] b, String prefix) { ByteBuf bb = Unpooled.wrappedBuffer(b); return (bb.readableBytes() > prefix.length()) && (bb .readCharSequence(prefix.length(), Charset.defaultCharset()).toString().contentEquals(prefix)); }
From source file:org.traccar.protocol.Gt06ProtocolDecoder.java
License:Apache License
private Object decodeExtended(Channel channel, SocketAddress remoteAddress, ByteBuf buf) { DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); if (deviceSession == null) { return null; }// w w w . j a va 2s . c o m if (deviceSession.getTimeZone() == null) { deviceSession.setTimeZone(getTimeZone(deviceSession.getDeviceId())); } Position position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); buf.readUnsignedShort(); // length int type = buf.readUnsignedByte(); if (type == MSG_STRING_INFO) { buf.readUnsignedInt(); // server flag String data; if (buf.readUnsignedByte() == 1) { data = buf.readSlice(buf.readableBytes() - 6).toString(StandardCharsets.US_ASCII); } else { data = buf.readSlice(buf.readableBytes() - 6).toString(StandardCharsets.UTF_16BE); } if (decodeLocationString(position, data) == null) { getLastLocation(position, null); position.set(Position.KEY_RESULT, data); } return position; } else if (type == MSG_INFO) { int subType = buf.readUnsignedByte(); getLastLocation(position, null); if (subType == 0x00) { position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); return position; } else if (subType == 0x05) { int flags = buf.readUnsignedByte(); position.set(Position.KEY_DOOR, BitUtil.check(flags, 0)); position.set(Position.PREFIX_IO + 1, BitUtil.check(flags, 2)); return position; } else if (subType == 0x0a) { buf.skipBytes(8); // imei buf.skipBytes(8); // imsi position.set("iccid", ByteBufUtil.hexDump(buf.readSlice(8))); return position; } else if (subType == 0x0d) { if (buf.getByte(buf.readerIndex()) != '!') { buf.skipBytes(6); } return decodeFuelData(position, buf.toString(buf.readerIndex(), buf.readableBytes() - 4 - 2, StandardCharsets.US_ASCII)); } } else if (type == MSG_X1_PHOTO_DATA) { int pictureId = buf.readInt(); ByteBuf photo = photos.get(pictureId); buf.readUnsignedInt(); // offset buf.readBytes(photo, buf.readUnsignedShort()); if (photo.writableBytes() > 0) { sendPhotoRequest(channel, pictureId); } else { Device device = Context.getDeviceManager().getById(deviceSession.getDeviceId()); position.set(Position.KEY_IMAGE, Context.getMediaManager().writeFile(device.getUniqueId(), photo, "jpg")); photos.remove(pictureId).release(); } } else if (type == MSG_AZ735_GPS || type == MSG_AZ735_ALARM) { if (!decodeGps(position, buf, true, deviceSession.getTimeZone())) { getLastLocation(position, position.getDeviceTime()); } if (decodeLbs(position, buf, true)) { position.set(Position.KEY_RSSI, buf.readUnsignedByte()); } buf.skipBytes(buf.readUnsignedByte()); // additional cell towers buf.skipBytes(buf.readUnsignedByte()); // wifi access point int status = buf.readUnsignedByte(); position.set(Position.KEY_STATUS, status); if (type == MSG_AZ735_ALARM) { switch (status) { case 0xA0: position.set(Position.KEY_ARMED, true); break; case 0xA1: position.set(Position.KEY_ARMED, false); break; case 0xA2: case 0xA3: position.set(Position.KEY_ALARM, Position.ALARM_LOW_BATTERY); break; case 0xA4: position.set(Position.KEY_ALARM, Position.ALARM_GENERAL); break; case 0xA5: position.set(Position.KEY_ALARM, Position.ALARM_DOOR); break; default: break; } } buf.skipBytes(buf.readUnsignedByte()); // reserved extension sendResponse(channel, true, type, buf.getShort(buf.writerIndex() - 6), null); return position; } else if (type == MSG_OBD) { DateBuilder dateBuilder = new DateBuilder(deviceSession.getTimeZone()) .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); getLastLocation(position, dateBuilder.getDate()); position.set(Position.KEY_IGNITION, buf.readUnsignedByte() > 0); String data = buf.readCharSequence(buf.readableBytes() - 18, StandardCharsets.US_ASCII).toString(); for (String pair : data.split(",")) { String[] values = pair.split("="); switch (Integer.parseInt(values[0].substring(0, 2), 16)) { case 40: position.set(Position.KEY_ODOMETER, Integer.parseInt(values[1], 16) * 0.01); break; case 43: position.set(Position.KEY_FUEL_LEVEL, Integer.parseInt(values[1], 16) * 0.01); break; case 45: position.set(Position.KEY_COOLANT_TEMP, Integer.parseInt(values[1], 16) * 0.01); break; case 53: position.set(Position.KEY_OBD_SPEED, Integer.parseInt(values[1], 16) * 0.01); break; case 54: position.set(Position.KEY_RPM, Integer.parseInt(values[1], 16) * 0.01); break; case 71: position.set(Position.KEY_FUEL_USED, Integer.parseInt(values[1], 16) * 0.01); break; case 73: position.set(Position.KEY_HOURS, Integer.parseInt(values[1], 16) * 0.01); break; case 74: position.set(Position.KEY_VIN, values[1]); break; default: break; } } return position; } return null; }
From source file:org.traccar.protocol.NyitechProtocolDecoder.java
License:Apache License
@Override protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; buf.skipBytes(2); // header buf.readUnsignedShortLE(); // length String id = buf.readCharSequence(12, StandardCharsets.US_ASCII).toString(); DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id); if (deviceSession == null) { return null; }/*from w ww. j a v a 2 s . c om*/ int type = buf.readUnsignedShortLE(); if (type != MSG_LOGIN && type != MSG_COMPREHENSIVE_LIVE && type != MSG_COMPREHENSIVE_HISTORY && type != MSG_ALARM && type != MSG_FIXED) { return null; } Position position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); if (type == MSG_COMPREHENSIVE_LIVE || type == MSG_COMPREHENSIVE_HISTORY) { buf.skipBytes(6); // time boolean includeLocation = buf.readUnsignedByte() > 0; boolean includeObd = buf.readUnsignedByte() > 0; buf.readUnsignedByte(); // include sensor if (includeLocation) { decodeLocation(position, buf); } else { getLastLocation(position, null); } if (includeObd) { int count = buf.readUnsignedByte(); for (int i = 0; i < count; i++) { int pid = buf.readUnsignedShortLE(); int length = buf.readUnsignedByte(); switch (length) { case 1: position.add(ObdDecoder.decodeData(pid, buf.readByte(), true)); break; case 2: position.add(ObdDecoder.decodeData(pid, buf.readShortLE(), true)); break; case 4: position.add(ObdDecoder.decodeData(pid, buf.readIntLE(), true)); break; default: buf.skipBytes(length); break; } } } position.set(Position.KEY_FUEL_USED, buf.readUnsignedInt() * 0.01); position.set(Position.KEY_ODOMETER_TRIP, buf.readUnsignedInt()); } else if (type == MSG_ALARM) { buf.readUnsignedShortLE(); // random number buf.readUnsignedByte(); // tag position.set(Position.KEY_ALARM, decodeAlarm(buf.readUnsignedByte())); buf.readUnsignedShortLE(); // threshold buf.readUnsignedShortLE(); // value buf.skipBytes(6); // time decodeLocation(position, buf); } else if (type == MSG_FIXED) { buf.skipBytes(6); // time decodeLocation(position, buf); } else { decodeLocation(position, buf); } return position; }