List of usage examples for io.netty.buffer ByteBuf readShort
public abstract short readShort();
From source file:com.antsdb.saltedfish.server.mysql.ReplicationPacketDecoder.java
License:Open Source License
@SuppressWarnings("unused") private ReplicationPacket readPacket(ByteBuf in, int size) { // packet sequence number for multiple packets // byte packetSequence = in.readByte(); byte seqId = in.readByte(); // handshake/*from w w w. ja v a 2 s. c o m*/ ReplicationPacket packet = null; // using state to decide how to handle connecting messages. if (state == StateIndicator.INITIAL_STATE) { packet = new StateIndicator(StateIndicator.INITIAL_STATE); packet.packetLength = size; packet.packetId = seqId; packet.read(this.handler, in); state = StateIndicator.RESPONSED_STATE; } else if (state == StateIndicator.RESPONSED_STATE) { byte header = in.readByte(); if (header == 0) { packet = new StateIndicator(StateIndicator.HANDSHAKEN_STATE); state = StateIndicator.HANDSHAKEN_STATE; } else { packet = new StateIndicator(StateIndicator.HANDSHAKE_FAIL_STATE); state = StateIndicator.HANDSHAKE_FAIL_STATE; } char[] bytes = new char[size]; for (int i = 0; i < size; i++) { int ch = in.getByte(i); bytes[i] = (char) ch; } packet.packetId = seqId; packet.packetLength = size; packet.read(this.handler, in); } else if (state == StateIndicator.HANDSHAKEN_STATE) { // expecting response for registered slave byte header = in.readByte(); if (header == 0) { packet = new StateIndicator(StateIndicator.REGISTERED_STATE); state = StateIndicator.REGISTERED_STATE; } else { packet = new StateIndicator(StateIndicator.REGISTER_FAIL_STATE); state = StateIndicator.REGISTER_FAIL_STATE; } packet.packetId = seqId; packet.packetLength = size; packet.read(this.handler, in); } else { // binlog stream started with 00 ok-byte byte okByte = in.readByte(); if (okByte == 0) { // read event header // timestamp 4 bytes int timeStamp = in.readInt(); // event type byte eventType = in.readByte(); // server id, 4 bytes int serverId = (int) BufferUtils.readLong(in); // event length, 4 bytes long eventLength = BufferUtils.readLong(in); // next position, 4 bytes long nextPosition = BufferUtils.readLong(in); // flags int flags = in.readShort(); // events switch (eventType) { case ReplicationPacket.ROTATE_EVENT: packet = new RotatePacket(eventType, eventLength, nextPosition); break; case ReplicationPacket.TABLE_MAP_EVENT: packet = new TableMapPacket(eventType, eventLength, nextPosition); break; case ReplicationPacket.WRITE_ROWS_EVENT: case ReplicationPacket.UPDATE_ROWS_EVENT: case ReplicationPacket.DELETE_ROWS_EVENT: packet = new RowsEventV2Packet(eventType, eventLength, nextPosition); break; case ReplicationPacket.STOP_EVENT: packet = new StopPacket(eventType, eventLength, nextPosition); break; case ReplicationPacket.XID_EVENT: packet = new XIDPacket(eventType, eventLength, nextPosition); break; case ReplicationPacket.QUERY_EVENT: case ReplicationPacket.FORMAT_DESCRIPTION_EVENT: case ReplicationPacket.START_EVENT_V3: // use GenericPacket to ignore unsupported events for now packet = new GenericPacket(eventType, eventLength, nextPosition); break; default: _log.error("unknown event: " + eventType); throw new CodingError("unknown event: " + eventType); } if (packet != null) { packet.packetId = seqId; packet.packetLength = size; packet.read(this.handler, in); } } else { ByteBuf pkt = (ByteBuf) in; ByteBuffer bbuf = pkt.nioBuffer(); int i = bbuf.remaining(); byte[] bytes = new byte[i]; pkt.readBytes(bytes); String dump = '\n' + UberUtil.hexDump(bytes); _log.error("unknown packet: " + dump); throw new CodingError("unknown packet"); } } return packet; }
From source file:com.builtbroken.icbm.content.missile.tile.TileCrashedMissile.java
@Override public void readDescPacket(ByteBuf buf) { ItemStack stack = ByteBufUtils.readItemStack(buf); missile = stack.getItem() instanceof IMissileItem ? ((IMissileItem) stack.getItem()).toMissile(stack) : null;/* ww w . j a va2s . c o m*/ yaw = buf.readFloat(); pitch = buf.readFloat(); posOffset = new Pos(buf); if (buf.readBoolean()) { block = Block.getBlockFromName(ByteBufUtils.readUTF8String(buf)); meta = buf.readShort(); } }
From source file:com.cloudhopper.smpp.util.ChannelBufferUtil.java
License:Apache License
/** * Reads a TLV from a buffer. This method is greedy and will read bytes * even if it won't be able to successfully complete. It's assumed this * method will only be called if its known ahead of time that all bytes * will be available ahead of time./*from w w w .ja v a 2 s . c o m*/ * @param buffer The buffer to read from * @return A new TLV instance * @throws NotEnoughDataInBufferException */ static public Tlv readTlv(ByteBuf buffer) throws NotEnoughDataInBufferException { // a TLV is at least 4 bytes (tag+length) if (buffer.readableBytes() < 4) { throw new NotEnoughDataInBufferException("Parsing TLV tag and length", buffer.readableBytes(), 4); } short tag = buffer.readShort(); int length = buffer.readUnsignedShort(); // check if we have enough data for the TLV if (buffer.readableBytes() < length) { throw new NotEnoughDataInBufferException("Parsing TLV value", buffer.readableBytes(), length); } byte[] value = new byte[length]; buffer.readBytes(value); return new Tlv(tag, value); }
From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java
License:Apache License
private Packet parseBinary(ClientHead head, ByteBuf frame) throws IOException { if (frame.getByte(0) == 1) { frame.readByte();//from w w w . j a v a 2 s.c o m int headEndIndex = frame.bytesBefore((byte) -1); int len = (int) readLong(frame, headEndIndex); ByteBuf oldFrame = frame; frame = frame.slice(oldFrame.readerIndex() + 1, len); oldFrame.readerIndex(oldFrame.readerIndex() + 1 + len); } if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') { frame.readShort(); } else if (frame.getByte(0) == 4) { frame.readByte(); } Packet binaryPacket = head.getLastBinaryPacket(); if (binaryPacket != null) { ByteBuf attachBuf; if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') { attachBuf = frame; } else { attachBuf = Base64.encode(frame); } binaryPacket.addAttachment(Unpooled.copiedBuffer(attachBuf)); frame.readerIndex(frame.readerIndex() + frame.readableBytes()); if (binaryPacket.isAttachmentsLoaded()) { LinkedList<ByteBuf> slices = new LinkedList<ByteBuf>(); ByteBuf source = binaryPacket.getDataSource(); for (int i = 0; i < binaryPacket.getAttachments().size(); i++) { ByteBuf attachment = binaryPacket.getAttachments().get(i); ByteBuf scanValue = Unpooled.copiedBuffer("{\"_placeholder\":true,\"num\":" + i + "}", CharsetUtil.UTF_8); int pos = PacketEncoder.find(source, scanValue); if (pos == -1) { throw new IllegalStateException( "Can't find attachment by index: " + i + " in packet source"); } ByteBuf prefixBuf = source.slice(source.readerIndex(), pos - source.readerIndex()); slices.add(prefixBuf); slices.add(QUOTES); slices.add(attachment); slices.add(QUOTES); source.readerIndex(pos + scanValue.readableBytes()); } slices.add(source.slice()); ByteBuf compositeBuf = Unpooled.wrappedBuffer(slices.toArray(new ByteBuf[slices.size()])); parseBody(head, compositeBuf, binaryPacket); head.setLastBinaryPacket(null); return binaryPacket; } } return new Packet(PacketType.MESSAGE); }
From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java
License:Apache License
/** * Helper method to decode all multi lookup response messages. * * @param request the current request.//w w w. ja va2s . c o m * @param msg the current response message. * @param ctx the handler context. * @param status the response status code. * @return the decoded response or null if it wasn't a subdocument multi lookup. */ private static CouchbaseResponse handleSubdocumentMultiLookupResponseMessages(BinaryRequest request, FullBinaryMemcacheResponse msg, ChannelHandlerContext ctx, ResponseStatus status) { if (!(request instanceof BinarySubdocMultiLookupRequest)) return null; BinarySubdocMultiLookupRequest subdocRequest = (BinarySubdocMultiLookupRequest) request; short statusCode = msg.getStatus(); long cas = msg.getCAS(); String bucket = request.bucket(); ByteBuf body = msg.content(); List<MultiResult<Lookup>> responses; if (status.isSuccess() || ResponseStatus.SUBDOC_MULTI_PATH_FAILURE.equals(status)) { long bodyLength = body.readableBytes(); List<LookupCommand> commands = subdocRequest.commands(); responses = new ArrayList<MultiResult<Lookup>>(commands.size()); for (LookupCommand cmd : commands) { if (msg.content().readableBytes() < 6) { body.release(); throw new IllegalStateException("Expected " + commands.size() + " lookup responses, only got " + responses.size() + ", total of " + bodyLength + " bytes"); } short cmdStatus = body.readShort(); int valueLength = body.readInt(); ByteBuf value = ctx.alloc().buffer(valueLength, valueLength); value.writeBytes(body, valueLength); responses.add(MultiResult.create(cmdStatus, ResponseStatusConverter.fromBinary(cmdStatus), cmd.path(), cmd.lookup(), value)); } } else { responses = Collections.emptyList(); } body.release(); return new MultiLookupResponse(status, statusCode, bucket, responses, subdocRequest, cas); }
From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java
License:Apache License
/** * Helper method to decode all multi mutation response messages. * * @param request the current request.//from w w w . j a va 2 s. c om * @param msg the current response message. * @param ctx the handler context. * @param status the response status code. * @return the decoded response or null if it wasn't a subdocument multi lookup. */ private static CouchbaseResponse handleSubdocumentMultiMutationResponseMessages(BinaryRequest request, FullBinaryMemcacheResponse msg, ChannelHandlerContext ctx, ResponseStatus status, boolean seqOnMutation) { if (!(request instanceof BinarySubdocMultiMutationRequest)) return null; BinarySubdocMultiMutationRequest subdocRequest = (BinarySubdocMultiMutationRequest) request; long cas = msg.getCAS(); short statusCode = msg.getStatus(); String bucket = request.bucket(); MutationToken mutationToken = null; if (msg.getExtrasLength() > 0) { mutationToken = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); } MultiMutationResponse response; ByteBuf body = msg.content(); List<MultiResult<Mutation>> responses; if (status.isSuccess()) { List<MutationCommand> commands = subdocRequest.commands(); responses = new ArrayList<MultiResult<Mutation>>(commands.size()); //MB-17842: Mutations can have a value, so there could be individual results //but only mutation commands that provide a value will have an explicit result in the binary response. //However, we still want MutationResult for all of the commands ListIterator<MutationCommand> it = commands.listIterator(); int explicitResultSize = 0; //as long as there is an explicit response to read... while (msg.content().readableBytes() >= 7) { explicitResultSize++; //...read the data byte responseIndex = body.readByte(); short responseStatus = body.readShort(); //will this always be SUCCESS? int responseLength = body.readInt(); ByteBuf responseValue; if (responseLength > 0) { responseValue = ctx.alloc().buffer(responseLength, responseLength); responseValue.writeBytes(body, responseLength); } else { responseValue = Unpooled.EMPTY_BUFFER; //can an explicit response be 0-length (empty)? } //...sanity check response so subsequent loop don't run forever if (it.nextIndex() > responseIndex) { body.release(); throw new IllegalStateException("Unable to interpret multi mutation response, responseIndex = " + responseIndex + " while next available command was #" + it.nextIndex()); } ///...catch up on all commands before current one that didn't get an explicit response while (it.nextIndex() < responseIndex) { MutationCommand noResultCommand = it.next(); responses.add(MultiResult.create(KeyValueStatus.SUCCESS.code(), ResponseStatus.SUCCESS, noResultCommand.path(), noResultCommand.mutation(), Unpooled.EMPTY_BUFFER)); } //...then process the one that did get an explicit response MutationCommand cmd = it.next(); responses.add(MultiResult.create(responseStatus, ResponseStatusConverter.fromBinary(responseStatus), cmd.path(), cmd.mutation(), responseValue)); } //...and finally the remainder of commands after the last one that got an explicit response: while (it.hasNext()) { MutationCommand noResultCommand = it.next(); responses.add(MultiResult.create(KeyValueStatus.SUCCESS.code(), ResponseStatus.SUCCESS, noResultCommand.path(), noResultCommand.mutation(), Unpooled.EMPTY_BUFFER)); } if (responses.size() != commands.size()) { body.release(); throw new IllegalStateException( "Multi mutation spec size and result size differ: " + commands.size() + " vs " + responses.size() + ", including " + explicitResultSize + " explicit results"); } response = new MultiMutationResponse(bucket, subdocRequest, cas, mutationToken, responses); } else if (ResponseStatus.SUBDOC_MULTI_PATH_FAILURE.equals(status)) { //MB-17842: order of index and status has been swapped byte firstErrorIndex = body.readByte(); short firstErrorCode = body.readShort(); response = new MultiMutationResponse(status, statusCode, bucket, firstErrorIndex, firstErrorCode, subdocRequest, cas, mutationToken); } else { response = new MultiMutationResponse(status, statusCode, bucket, subdocRequest, cas, mutationToken); } body.release(); return response; }
From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java
License:Apache License
/** * Helper method to decode all other response messages. * * @param request the current request.//from w w w. j a v a2 s . c om * @param msg the current response message. * @param status the response status code. * @return the decoded response or null if none did match. */ private static CouchbaseResponse handleOtherResponseMessages(BinaryRequest request, FullBinaryMemcacheResponse msg, ResponseStatus status, boolean seqOnMutation, String remoteHostname) { CouchbaseResponse response = null; ByteBuf content = msg.content(); long cas = msg.getCAS(); short statusCode = msg.getStatus(); String bucket = request.bucket(); if (request instanceof UnlockRequest) { response = new UnlockResponse(status, statusCode, bucket, content, request); } else if (request instanceof TouchRequest) { response = new TouchResponse(status, statusCode, bucket, content, request); } else if (request instanceof AppendRequest) { MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); response = new AppendResponse(status, statusCode, cas, bucket, content, descr, request); } else if (request instanceof PrependRequest) { MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); response = new PrependResponse(status, statusCode, cas, bucket, content, descr, request); } else if (request instanceof KeepAliveRequest) { releaseContent(content); response = new KeepAliveResponse(status, statusCode, request); } else if (request instanceof CounterRequest) { long value = status.isSuccess() ? content.readLong() : 0; releaseContent(content); MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); response = new CounterResponse(status, statusCode, bucket, value, cas, descr, request); } else if (request instanceof StatRequest) { String key = new String(msg.getKey(), CHARSET); String value = content.toString(CHARSET); releaseContent(content); response = new StatResponse(status, statusCode, remoteHostname, key, value, bucket, request); } else if (request instanceof GetAllMutationTokensRequest) { // 2 bytes for partition ID, and 8 bytes for sequence number MutationToken[] mutationTokens = new MutationToken[content.readableBytes() / 10]; for (int i = 0; i < mutationTokens.length; i++) { mutationTokens[i] = new MutationToken((long) content.readShort(), 0, content.readLong(), request.bucket()); } releaseContent(content); response = new GetAllMutationTokensResponse(mutationTokens, status, statusCode, bucket, request); } else if (request instanceof ObserveRequest) { byte observed = ObserveResponse.ObserveStatus.UNKNOWN.value(); long observedCas = 0; if (status.isSuccess()) { short keyLength = content.getShort(2); observed = content.getByte(keyLength + 4); observedCas = content.getLong(keyLength + 5); } releaseContent(content); response = new ObserveResponse(status, statusCode, observed, ((ObserveRequest) request).master(), observedCas, bucket, request); } else if (request instanceof ObserveSeqnoRequest) { if (status.isSuccess()) { byte format = content.readByte(); switch (format) { case 0: response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), content.readShort(), content.readLong(), content.readLong(), content.readLong(), status, statusCode, bucket, request); break; case 1: response = new FailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), content.readShort(), content.readLong(), content.readLong(), content.readLong(), content.readLong(), content.readLong(), status, statusCode, bucket, request); break; default: throw new IllegalStateException("Unknown format for observe-seq: " + format); } } else { response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), (short) 0, 0, 0, 0, status, statusCode, bucket, request); } releaseContent(content); } return response; }
From source file:com.datastax.driver.core.DataType.java
License:Apache License
static DataType decode(ByteBuf buffer) { Name name = Name.fromProtocolId(buffer.readUnsignedShort()); switch (name) { case CUSTOM://from w w w. ja v a 2s. c o m String className = CBUtil.readString(buffer); return CassandraTypeParser.isUserType(className) || CassandraTypeParser.isTupleType(className) ? CassandraTypeParser.parseOne(className) : custom(className); case LIST: return list(decode(buffer)); case SET: return set(decode(buffer)); case MAP: DataType keys = decode(buffer); DataType values = decode(buffer); return map(keys, values); case UDT: String keyspace = CBUtil.readString(buffer); String type = CBUtil.readString(buffer); int nFields = buffer.readShort() & 0xffff; List<UserType.Field> fields = new ArrayList<UserType.Field>(nFields); for (int i = 0; i < nFields; i++) { String fieldName = CBUtil.readString(buffer); DataType fieldType = decode(buffer); fields.add(new UserType.Field(fieldName, fieldType)); } return new UserType(keyspace, type, fields); case TUPLE: nFields = buffer.readShort() & 0xffff; List<DataType> types = new ArrayList<DataType>(nFields); for (int i = 0; i < nFields; i++) { types.add(decode(buffer)); } return new TupleType(types); default: return primitiveTypeMap.get(name); } }
From source file:com.datastax.driver.core.Frame.java
License:Apache License
private static int readStreamid(ByteBuf fullFrame, ProtocolVersion version) { switch (version) { case V1://from w w w . j a v a 2 s .c o m case V2: return fullFrame.readByte(); case V3: case V4: return fullFrame.readShort(); default: throw version.unsupported(); } }
From source file:com.digitalpetri.modbus.codec.MbapHeader.java
License:Apache License
public static MbapHeader decode(ByteBuf buffer) { return new MbapHeader(buffer.readShort(), buffer.readUnsignedShort(), buffer.readUnsignedShort(), buffer.readUnsignedByte());//from w ww . j ava 2 s. c o m }