Example usage for io.netty.buffer ByteBuf readerIndex

List of usage examples for io.netty.buffer ByteBuf readerIndex

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readerIndex.

Prototype

public abstract int readerIndex();

Source Link

Document

Returns the readerIndex of this buffer.

Usage

From source file:com.corundumstudio.socketio.parser.UTF8CharsScannerTest.java

License:Apache License

@Test
public void testfindTailIndex() {
    String str = "132 4  \ufffd\ufffd  \\";
    UTF8CharsScanner p = new UTF8CharsScanner();
    ByteBuf b = Unpooled.wrappedBuffer(str.getBytes());
    int len = p.findTailIndex(b, b.readerIndex(), b.capacity(), str.length());
    Assert.assertEquals(b.capacity(), len);
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private boolean isStringPacket(ByteBuf content) {
    return content.getByte(content.readerIndex()) == 0x0;
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private long readLong(ByteBuf chars, int length) {
    long result = 0;
    for (int i = chars.readerIndex(); i < chars.readerIndex() + length; i++) {
        int digit = ((int) chars.getByte(i) & 0xF);
        for (int j = 0; j < chars.readerIndex() + length - 1 - i; j++) {
            digit *= 10;// w  w w. ja  v a2  s .c o m
        }
        result += digit;
    }
    chars.readerIndex(chars.readerIndex() + length);
    return result;
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private boolean hasLengthHeader(ByteBuf buffer) {
    for (int i = 0; i < Math.min(buffer.readableBytes(), 10); i++) {
        byte b = buffer.getByte(buffer.readerIndex() + i);
        if (b == (byte) ':' && i > 0) {
            return true;
        }/*from w w  w.jav  a 2  s  . c  om*/
        if (b > 57 || b < 48) {
            return false;
        }
    }
    return false;
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

public Packet decodePackets(ByteBuf buffer, ClientHead client) throws IOException {
    if (isStringPacket(buffer)) {
        // TODO refactor
        int headEndIndex = buffer.bytesBefore((byte) -1);
        int len = (int) readLong(buffer, headEndIndex);

        ByteBuf frame = buffer.slice(buffer.readerIndex() + 1, len);
        // skip this frame
        buffer.readerIndex(buffer.readerIndex() + 1 + len);
        return decode(client, frame);
    } else if (hasLengthHeader(buffer)) {
        // TODO refactor
        int lengthEndIndex = buffer.bytesBefore((byte) ':');
        int lenHeader = (int) readLong(buffer, lengthEndIndex);
        int len = utf8scanner.getActualLength(buffer, lenHeader);

        ByteBuf frame = buffer.slice(buffer.readerIndex() + 1, len);
        if (lenHeader != len) {
            frame = Unpooled.wrappedBuffer(frame.toString(CharsetUtil.UTF_8).getBytes(CharsetUtil.ISO_8859_1));
        }/*ww w. j  ava  2 s.c  om*/
        // skip this frame
        buffer.readerIndex(buffer.readerIndex() + 1 + len);
        return decode(client, frame);
    }
    return decode(client, buffer);
}

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();/*  w  w w  . ja  va 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.corundumstudio.socketio.protocol.PacketEncoder.java

License:Apache License

public static int find(ByteBuf buffer, ByteBuf searchValue) {
    for (int i = buffer.readerIndex(); i < buffer.readerIndex() + buffer.readableBytes(); i++) {
        if (isValueFound(buffer, i, searchValue)) {
            return i;
        }//w w  w  .  ja  v  a  2  s .  c o  m
    }
    return -1;
}

From source file:com.corundumstudio.socketio.protocol.UTF8CharsScanner.java

License:Apache License

public int getActualLength(ByteBuf inputBuffer, int length) {
    int len = 0;//  ww w  . j a v a 2  s  .  c  o m
    int start = inputBuffer.readerIndex();
    for (int i = inputBuffer.readerIndex(); i < inputBuffer.readableBytes() + inputBuffer.readerIndex();) {
        i = getCharTailIndex(inputBuffer, i);
        len++;
        if (length == len) {
            return i - start;
        }
    }
    throw new IllegalStateException();
}

From source file:com.couchbase.client.core.endpoint.binary.BinaryHandler.java

License:Open Source License

@Override
protected CouchbaseResponse decodeResponse(final ChannelHandlerContext ctx,
        final FullBinaryMemcacheResponse msg) throws Exception {
    BinaryRequest request = currentRequest();
    ResponseStatus status = convertStatus(msg.getStatus());

    CouchbaseResponse response;/*from  ww  w  .j  a  v a2s .c om*/
    ByteBuf content = msg.content().copy();
    long cas = msg.getCAS();
    String bucket = request.bucket();
    if (request instanceof GetRequest || request instanceof ReplicaGetRequest) {
        int flags = 0;
        if (msg.getExtrasLength() > 0) {
            final ByteBuf extrasReleased = msg.getExtras();
            final ByteBuf extras = ctx.alloc().buffer(msg.getExtrasLength());
            extras.writeBytes(extrasReleased, extrasReleased.readerIndex(), extrasReleased.readableBytes());
            flags = extras.getInt(0);
            extras.release();
        }
        response = new GetResponse(status, cas, flags, bucket, content, request);
    } else if (request instanceof GetBucketConfigRequest) {
        response = new GetBucketConfigResponse(status, bucket, content,
                ((GetBucketConfigRequest) request).hostname());
    } else if (request instanceof InsertRequest) {
        response = new InsertResponse(status, cas, bucket, content, request);
    } else if (request instanceof UpsertRequest) {
        response = new UpsertResponse(status, cas, bucket, content, request);
    } else if (request instanceof ReplaceRequest) {
        response = new ReplaceResponse(status, cas, bucket, content, request);
    } else if (request instanceof RemoveRequest) {
        response = new RemoveResponse(status, bucket, content, request);
    } else if (request instanceof CounterRequest) {
        response = new CounterResponse(status, bucket, msg.content().readLong(), cas, request);
    } else if (request instanceof UnlockRequest) {
        response = new UnlockResponse(status, bucket, content, request);
    } else if (request instanceof TouchRequest) {
        response = new TouchResponse(status, bucket, content, request);
    } else if (request instanceof ObserveRequest) {
        byte observed = content.getByte(content.getShort(2) + 4);
        response = new ObserveResponse(status, observed, ((ObserveRequest) request).master(), bucket, content,
                request);
    } else if (request instanceof AppendRequest) {
        response = new AppendResponse(status, cas, bucket, content, request);
    } else if (request instanceof PrependRequest) {
        response = new PrependResponse(status, cas, bucket, content, request);
    } else {
        throw new IllegalStateException(
                "Unhandled request/response pair: " + request.getClass() + "/" + msg.getClass());
    }

    return response;
}

From source file:com.couchbase.client.core.endpoint.util.ByteBufJsonHelper.java

License:Apache License

/**
 * 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./*from  ww  w  .  j  av a2s  .c om*/
 */
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;
    }
}