List of usage examples for io.netty.buffer ByteBuf readerIndex
public abstract int readerIndex();
From source file:io.reactiverse.pgclient.impl.RowResultDecoder.java
License:Apache License
@Override public void decodeRow(int len, ByteBuf in) { if (container == null) { container = collector.supplier().get(); }// w ww . j av a 2 s. co m if (singleton) { if (row == null) { row = new RowImpl(desc); } else { row.clear(); } } else { row = new RowImpl(desc); } Row row = new RowImpl(desc); for (int c = 0; c < len; ++c) { int length = in.readInt(); Object decoded = null; if (length != -1) { ColumnDesc columnDesc = desc.columns()[c]; if (columnDesc.getDataFormat() == DataFormat.BINARY) { decoded = DataTypeCodec.decodeBinary(columnDesc.getDataType(), in.readerIndex(), length, in); } else { decoded = DataTypeCodec.decodeText(columnDesc.getDataType(), in.readerIndex(), length, in); } in.skipBytes(length); } row.addValue(decoded); } accumulator.accept(container, row); size++; }
From source file:io.reactivesocket.netty.TestUtil.java
License:Apache License
public static String byteBufToString(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; int readerIndex = buf.readerIndex(); buf.getBytes(readerIndex, bytes);/*from w w w . ja v a2 s.c o m*/ buf.readerIndex(readerIndex); StringBuilder result = new StringBuilder(); StringBuilder ascii = new StringBuilder(); int i = 0; for (i = 0; i < bytes.length; i++) { byte b = bytes[i]; result.append(String.format("%02X ", b)); if (32 <= b && b < 127) { ascii.append((char) b); } else { ascii.append('.'); } if ((i + 1) % 16 == 0) { result.append(" "); result.append(ascii); result.append('\n'); ascii = new StringBuilder(); } } if ((bytes.length - 1) % 16 != 0) { int x = 16 - ((bytes.length - 1) % 16); StringBuilder padding = new StringBuilder(); for (int j = 0; j < x; j++) { result.append(" "); } result.append(ascii); } return result.toString(); }
From source file:io.reactivex.netty.protocol.http.sse.ServerSentEventDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (null == sseEncodingCharset) { throw new IllegalArgumentException("Can not read SSE data as UTF-8 charset is not available."); }/* w ww . j a v a2 s . c om*/ while (in.isReadable()) { final int readerIndexAtStart = in.readerIndex(); switch (state) { case SkipColonAndWhiteSpaces: if (skipColonAndWhiteSpaces(in)) { state = State.ReadFieldValue; } break; case SkipLineDelimitersAndSpaces: if (skipLineDelimiters(in)) { state = State.ReadFieldName; } break; case DiscardTillEOL: if (skipTillEOL(in)) { state = State.SkipLineDelimitersAndSpaces; } break; case ReadFieldName: final int indexOfColon = scanAndFindColon(in); if (-1 == indexOfColon) { // No colon found // Accumulate data into the field name buffer. if (null == incompleteData) { incompleteData = ctx.alloc().buffer(); } // accumulate into incomplete data buffer to be used when the full data arrives. incompleteData.writeBytes(in); } else { int fieldNameLengthInTheCurrentBuffer = indexOfColon - readerIndexAtStart; ByteBuf fieldNameBuffer; if (null != incompleteData) { // Read the remaining data into the temporary buffer in.readBytes(incompleteData, fieldNameLengthInTheCurrentBuffer); fieldNameBuffer = incompleteData; incompleteData = null; } else { // Consume the data from the input buffer. fieldNameBuffer = ctx.alloc().buffer(fieldNameLengthInTheCurrentBuffer, fieldNameLengthInTheCurrentBuffer); in.readBytes(fieldNameBuffer, fieldNameLengthInTheCurrentBuffer); } state = State.SkipColonAndWhiteSpaces; // We have read the field name, next we should skip colon & WS. try { currentFieldType = readCurrentFieldTypeFromBuffer(fieldNameBuffer); } finally { if (null == currentFieldType) { state = State.DiscardTillEOL; // Ignore this event completely. } fieldNameBuffer.release(); } } break; case ReadFieldValue: final int endOfLineStartIndex = scanAndFindEndOfLine(in); if (-1 == endOfLineStartIndex) { // End of line not found, accumulate data into a temporary buffer. if (null == incompleteData) { incompleteData = ctx.alloc().buffer(in.readableBytes()); } // accumulate into incomplete data buffer to be used when the full data arrives. incompleteData.writeBytes(in); } else { // Read the data till end of line into the value buffer. final int bytesAvailableInThisIteration = endOfLineStartIndex - readerIndexAtStart; if (null == incompleteData) { incompleteData = ctx.alloc().buffer(bytesAvailableInThisIteration, bytesAvailableInThisIteration); } incompleteData.writeBytes(in, bytesAvailableInThisIteration); switch (currentFieldType) { case Data: if (incompleteData.isReadable()) { out.add(ServerSentEvent.withEventIdAndType(lastEventId, lastEventType, incompleteData)); } else { incompleteData.release(); } break; case Id: if (incompleteData.isReadable()) { lastEventId = incompleteData; } else { incompleteData.release(); lastEventId = null; } break; case EventType: if (incompleteData.isReadable()) { lastEventType = incompleteData; } else { incompleteData.release(); lastEventType = null; } break; } /** * Since all data is read, reset the incomplete data to null. Release of this buffer happens in * the following ways * 1) If this was a data buffer, it is released when ServerSentEvent is released. * 2) If this was an eventId buffer, it is released when next Id arrives or when the connection * is closed. * 3) If this was an eventType buffer, it is released when next type arrives or when the connection * is closed. */ incompleteData = null; state = State.SkipLineDelimitersAndSpaces; // Skip line delimiters after reading a field value completely. } break; } } }
From source file:io.reactivex.netty.protocol.http.sse.ServerSentEventDecoder.java
License:Apache License
private static ServerSentEvent.Type readCurrentFieldTypeFromBuffer(final ByteBuf fieldNameBuffer) { /**/* w w w. j a va 2 s . c om*/ * This code tries to eliminate the need of creating a string from the ByteBuf as the field names are very * constrained. The algorithm is as follows: * * -- Scan the bytes in the buffer. * -- If the first byte matches the expected field names then use the matching field name char array to verify * the rest of the field name. * -- If the first byte does not match, reject the field name. * -- After the first byte, exact match the rest of the field name with the expected field name, byte by byte. * -- If the name does not exactly match the expected value, then reject the field name. */ ServerSentEvent.Type toReturn = ServerSentEvent.Type.Data; int readableBytes = fieldNameBuffer.readableBytes(); final int readerIndexAtStart = fieldNameBuffer.readerIndex(); char[] fieldNameToVerify = DATA_FIELD_NAME; boolean verified = false; int actualFieldNameIndexToCheck = 0; // Starts with 1 as the first char is validated by equality. for (int i = readerIndexAtStart; i < readableBytes; i++) { final char charAtI = (char) fieldNameBuffer.getByte(i); if (i == readerIndexAtStart) { switch (charAtI) { // See which among the known field names this buffer belongs. case 'e': fieldNameToVerify = EVENT_ID_FIELD_NAME; toReturn = ServerSentEvent.Type.EventType; break; case 'd': fieldNameToVerify = DATA_FIELD_NAME; toReturn = ServerSentEvent.Type.Data; break; case 'i': fieldNameToVerify = ID_FIELD_NAME; toReturn = ServerSentEvent.Type.Id; break; default: return null; } } else { if (++actualFieldNameIndexToCheck >= fieldNameToVerify.length || charAtI != fieldNameToVerify[actualFieldNameIndexToCheck]) { // If the character does not match or the buffer is bigger than the expected name, then discard. verified = false; break; } else { // Verified till now. If all characters are matching then this stays as verified, else changed to false. verified = true; } } } if (verified) { return toReturn; } else { return null; } }
From source file:io.reactivex.netty.protocol.http.sse.ServerSentEventEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, ServerSentEvent serverSentEvent, ByteBuf out) throws Exception { if (serverSentEvent.hasEventType()) { // Write event type, if available out.writeBytes(EVENT_PREFIX_BYTES); out.writeBytes(serverSentEvent.getEventType()); out.writeBytes(NEW_LINE_AS_BYTES); }//w ww .ja v a2 s. c o m if (serverSentEvent.hasEventId()) { // Write event id, if available out.writeBytes(ID_PREFIX_AS_BYTES); out.writeBytes(serverSentEvent.getEventId()); out.writeBytes(NEW_LINE_AS_BYTES); } final ByteBuf content = serverSentEvent.content(); if (splitSseData) { while (content.isReadable()) { // Scan the buffer and split on new line into multiple data lines. final int readerIndexAtStart = content.readerIndex(); int newLineIndex = content.forEachByte(new ByteBufProcessor() { @Override public boolean process(byte value) throws Exception { return (char) value != '\n'; } }); if (-1 == newLineIndex) { // No new line, write the buffer as is. out.writeBytes(DATA_PREFIX_AS_BYTES); out.writeBytes(content); out.writeBytes(NEW_LINE_AS_BYTES); } else { // Write the buffer till the new line and then iterate this loop out.writeBytes(DATA_PREFIX_AS_BYTES); out.writeBytes(content, newLineIndex - readerIndexAtStart); content.readerIndex(content.readerIndex() + 1); out.writeBytes(NEW_LINE_AS_BYTES); } } } else { // write the buffer with data prefix and new line post fix. out.writeBytes(DATA_PREFIX_AS_BYTES); out.writeBytes(content); out.writeBytes(NEW_LINE_AS_BYTES); } }
From source file:io.reactivex.netty.protocol.text.sse.ServerSentEventDecoder.java
License:Apache License
private int skipLineDelimiters(ByteBuf in) { int skipped = 0; while (in.writerIndex() - in.readerIndex() > 0) { // the above check is needed to ensure that last event is delivered // otherwise, an exception (Netty's Signal object) will be thrown // from ReplayingDecoderBuffer.readByte() char c = (char) in.readByte(); if (isLineDelimiter(c)) { skipped += 1;/*w ww.j ava 2 s . com*/ continue; } // Leave the reader index at the first letter of the next line, if any in.readerIndex(in.readerIndex() - 1); checkpoint(State.NEW_LINE); break; } return skipped; }
From source file:io.scalecube.socketio.serialization.PacketFramer.java
License:Apache License
private static Packet decodeNextPacket(final ByteBuf buffer) throws IOException { Packet packet;/* w ww . jav a2 s . c o m*/ if (isDelimiter(buffer, buffer.readerIndex())) { CharSequence packetCharsCountString = decodePacketLength(buffer); final Integer packetCharsCount = Integer.valueOf(packetCharsCountString.toString()); final int packetStartIndex = buffer.readerIndex() + DELIMITER_BYTES_SIZE + packetCharsCountString.length() + DELIMITER_BYTES_SIZE; final int packetBytesCount = getUtf8ByteCountByCharCount(buffer, packetStartIndex, packetCharsCount); ByteBuf frame = buffer.slice(packetStartIndex, packetBytesCount); packet = PacketDecoder.decodePacket(frame); buffer.readerIndex(packetStartIndex + packetBytesCount); } else { packet = PacketDecoder.decodePacket(buffer); buffer.readerIndex(buffer.readableBytes()); } return packet; }
From source file:io.scalecube.socketio.serialization.PacketFramer.java
License:Apache License
private static CharSequence decodePacketLength(final ByteBuf buffer) { StringBuilder length = new StringBuilder(); final int scanStartIndex = buffer.readerIndex() + DELIMITER_BYTES_SIZE; final int scanEndIndex = buffer.readerIndex() + buffer.readableBytes(); for (int charIndex = scanStartIndex; charIndex < scanEndIndex; charIndex++) { if (isDelimiter(buffer, charIndex)) { break; } else {//from w ww .ja v a2s . c o m length.append((char) buffer.getUnsignedByte(charIndex)); } } return length; }
From source file:io.servicecomb.foundation.vertx.TestStream.java
License:Apache License
@Test public void testBufferInputStream() { ByteBuf obuf = Buffer.buffer(DIRECT_BUFFER_SIZE).getByteBuf(); obuf.writeBytes(("testss").getBytes()); @SuppressWarnings("resource") BufferInputStream oBufferInputStream = new BufferInputStream(obuf); Assert.assertNotEquals(1234, oBufferInputStream.skip(0)); Assert.assertNotEquals(obuf.readByte(), oBufferInputStream.readByte()); Assert.assertEquals(obuf.readByte() + 1, oBufferInputStream.read()); Assert.assertEquals(obuf.readBoolean(), oBufferInputStream.readBoolean()); Assert.assertEquals(obuf.readerIndex(), oBufferInputStream.getIndex()); Assert.assertEquals(obuf.readableBytes(), oBufferInputStream.available()); Assert.assertNotEquals(null, oBufferInputStream.read(("test").getBytes())); }
From source file:io.soliton.protobuf.quartz.ByteBufUtil.java
License:Apache License
public static byte[] getBytes(ByteBuf buffer) { byte[] bytes; // Not all ByteBuf implementation is backed by a byte array, so check if (buffer.hasArray()) { bytes = buffer.array();// w ww. j a va 2s . c o m } else { bytes = new byte[buffer.readableBytes()]; buffer.getBytes(buffer.readerIndex(), bytes); } return bytes; }