Example usage for io.netty.buffer ByteBuf resetReaderIndex

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

Introduction

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

Prototype

public abstract ByteBuf resetReaderIndex();

Source Link

Document

Repositions the current readerIndex to the marked readerIndex in this buffer.

Usage

From source file:org.wso2.siddhi.tcp.transport.converter.SiddhiEventConverter.java

License:Open Source License

public static void toConvertToSiddhiEvents(Object eventBundle, StreamTypeHolder streamTypeHolder) {

    ByteBuf byteBuffer = (ByteBuf) eventBundle;

    int protocol = byteBuffer.readByte();
    int messageSize = byteBuffer.readInt();
    if (protocol != 2 || messageSize > byteBuffer.readableBytes()) {
        byteBuffer.resetReaderIndex();
        return;/*from  w  ww.  j av a 2 s.co  m*/
    }

    int sessionIdSize = byteBuffer.readInt();
    String sessionId = BinaryMessageConverterUtil.getString(byteBuffer, sessionIdSize);

    int streamIdSize = byteBuffer.readInt();
    String streamId = BinaryMessageConverterUtil.getString(byteBuffer, streamIdSize);

    StreamInfo streamInfo = streamTypeHolder.getStreamInfo(streamId);

    int numberOfEvents = byteBuffer.readInt();

    Event[] events = new Event[numberOfEvents];
    for (int i = 0; i < numberOfEvents; i++) {
        int eventSize = byteBuffer.readInt();
        byte[] bytes = new byte[eventSize];
        byteBuffer.readBytes(bytes);
        ByteBuffer eventByteBuffer = ByteBuffer.wrap(bytes);
        events[i] = getEvent(eventByteBuffer, streamInfo.getAttributeTypes());
    }
    byteBuffer.markReaderIndex();
    streamInfo.getStreamListener().onEvents(events);
}

From source file:pub.vrtech.protocol.RedisCommandCodec.java

License:Apache License

@Override
protected void doDecode(Channel channel, ByteBuf buffer, List<Object> out) throws IOException {
    if (bytes != null) {
        int numArgs = bytes.length;
        for (int i = arguments; i < numArgs; i++) {//?
            buffer.markReaderIndex();//
            if (buffer.readByte() == RespType.BULK_STRING.getFlag()) {
                final long l = readLength(buffer);//?
                if (l < 0) {
                    buffer.resetReaderIndex();
                    return;
                }/*  w ww  . j  a  va 2s.co  m*/
                int size = (int) l;
                if (buffer.readableBytes() < (size + 2)) {
                    buffer.resetReaderIndex();
                    return;
                }
                bytes[i] = new byte[size];
                buffer.readBytes(bytes[i]);//?
                buffer.skipBytes(2);///r/n
                arguments++;
            } else {
                throw new IOException("Unexpected character");
            }
        }
        try {
            out.add(new RedisCommand(bytes));
        } finally {
            //?bytes
            bytes = null;
            arguments = 0;
        }
    } else if (buffer.readByte() == RespType.ARRAY.getFlag()) {// ?
        buffer.markReaderIndex();// 
        long length = readLength(buffer);
        if (length > Integer.MAX_VALUE) {
            throw new IllegalArgumentException(
                    "Java only supports arrays up to " + Integer.MAX_VALUE + " in size");
        }
        if (length < 0) {// ??
            buffer.resetReaderIndex();
            return;
        }
        final int numArgs = (int) length;
        bytes = new byte[numArgs][];//SET KEY  VALUE numArgs3
        doDecode(channel, buffer, out);
    }
}

From source file:qunar.tc.qmq.delay.receiver.ReceivedDelayMessageProcessor.java

License:Apache License

private RawMessageExtend doDeserializeRawMessagesExtend(ByteBuf body) {
    body.markReaderIndex();/* www . j a v  a  2 s.  co  m*/
    int headerStart = body.readerIndex();
    long bodyCrc = body.readLong();
    MessageHeader header = deserializeMessageHeader(body);
    header.setBodyCrc(bodyCrc);
    int bodyLen = body.readInt();
    int headerLen = body.readerIndex() - headerStart;
    int totalLen = headerLen + bodyLen;

    body.resetReaderIndex();
    ByteBuf messageBuf = body.readSlice(totalLen);
    // client config error,prefer to send after ten second
    long scheduleTime = System.currentTimeMillis() + 10000;
    if (Flags.isDelay(header.getFlag())) {
        scheduleTime = header.getExpireTime();
    }

    return new RawMessageExtend(header, messageBuf, messageBuf.readableBytes(), scheduleTime);
}

From source file:qunar.tc.qmq.netty.DecodeHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> list)
        throws Exception {
    if (in.readableBytes() < RemotingHeader.MIN_HEADER_SIZE + RemotingHeader.LENGTH_FIELD)
        return;// ww  w. j av a2 s . c o  m

    int magicCode = in.getInt(in.readerIndex() + RemotingHeader.LENGTH_FIELD);
    if (DEFAULT_MAGIC_CODE != magicCode) {
        throw new IOException("Illegal Data, MagicCode=" + Integer.toHexString(magicCode));
    }

    in.markReaderIndex();
    int total = in.readInt();
    if (in.readableBytes() < total) {
        in.resetReaderIndex();
        return;
    }

    short headerSize = in.readShort();
    RemotingHeader remotingHeader = decodeHeader(in);

    int bodyLength = total - headerSize - RemotingHeader.HEADER_SIZE_LEN;

    RemotingCommand remotingCommand = new RemotingCommand();
    //because netty(lower version) has memory leak when ByteBuf cross thread
    //We can ensure server use high version netty, bu we can't ensure client
    if (isServer) {
        ByteBuf bodyData = in.readSlice(bodyLength);
        bodyData.retain();
        remotingCommand.setBody(bodyData);
    } else {
        ByteBuf bodyData = Unpooled.buffer(bodyLength, bodyLength);
        in.readBytes(bodyData, bodyLength);
        remotingCommand.setBody(bodyData);
    }
    remotingCommand.setHeader(remotingHeader);
    list.add(remotingCommand);
}

From source file:qunar.tc.qmq.processor.SendMessageProcessor.java

License:Apache License

private RawMessage deserializeRawMessageWithCrc(ByteBuf body) {
    long bodyCrc = body.readLong();

    int headerStart = body.readerIndex();
    body.markReaderIndex();/*  w  w  w  . j ava 2 s. c  o m*/
    MessageHeader header = deserializeMessageHeader(body);
    header.setBodyCrc(bodyCrc);
    int bodyLen = body.readInt();
    int headerLen = body.readerIndex() - headerStart;

    int totalLen = headerLen + bodyLen;
    body.resetReaderIndex();
    ByteBuf messageBuf = body.readSlice(totalLen);
    return new RawMessage(header, messageBuf, totalLen);
}

From source file:qunar.tc.qmq.protocol.QMQSerializer.java

License:Apache License

public static RawMessage deserializeRawMessage(ByteBuf body) {
    int headerStart = body.readerIndex();
    body.markReaderIndex();//from  ww  w  . java  2  s . co m
    MessageHeader header = deserializeMessageHeader(body);
    int bodyLen = body.readInt();
    int headerLen = body.readerIndex() - headerStart;

    int totalLen = headerLen + bodyLen;
    body.resetReaderIndex();
    byte[] data = new byte[totalLen];
    body.readBytes(data);
    header.setBodyCrc(Crc32.crc32(data));
    return new RawMessage(header, Unpooled.wrappedBuffer(data), totalLen);
}

From source file:ratpack.session.clientside.internal.ClientSideSessionStore.java

License:Apache License

private String[] serialize(ByteBuf sessionData) throws Exception {
    if (sessionData == null || sessionData.readableBytes() == 0) {
        return new String[0];
    }/* w w  w  .j  a  v a2 s .  c  o m*/

    ByteBuf encrypted = null;
    ByteBuf digest = null;

    try {
        encrypted = crypto.encrypt(sessionData, bufferAllocator);
        String encryptedBase64 = toBase64(encrypted);
        digest = signer.sign(encrypted.resetReaderIndex(), bufferAllocator);
        String digestBase64 = toBase64(digest);
        String digestedBase64 = encryptedBase64 + SESSION_SEPARATOR + digestBase64;
        if (digestedBase64.length() <= config.getMaxSessionCookieSize()) {
            return new String[] { digestedBase64 };
        }
        int count = (int) Math.ceil((double) digestedBase64.length() / config.getMaxSessionCookieSize());
        String[] partitions = new String[count];
        for (int i = 0; i < count; i++) {
            int from = i * config.getMaxSessionCookieSize();
            int to = Math.min(from + config.getMaxSessionCookieSize(), digestedBase64.length());
            partitions[i] = digestedBase64.substring(from, to);
        }
        return partitions;
    } finally {
        if (encrypted != null) {
            encrypted.release();
        }
        if (digest != null) {
            digest.release();
        }
    }
}

From source file:ratpack.session.clientside.internal.ClientSideSessionStore.java

License:Apache License

private ByteBuf deserialize(ImmutableList<Cookie> sessionCookies) throws Exception {
    if (sessionCookies.isEmpty()) {
        return Unpooled.EMPTY_BUFFER;
    }//from   w ww.  j  ava 2 s  .c  o  m

    StringBuilder sessionCookie = new StringBuilder();
    for (Cookie cookie : sessionCookies) {
        sessionCookie.append(cookie.value());
    }
    String[] parts = sessionCookie.toString().split(SESSION_SEPARATOR);
    if (parts.length != 2) {
        return Unpooled.buffer(0, 0);
    }
    ByteBuf payload = null;
    ByteBuf digest = null;
    ByteBuf expectedDigest = null;
    ByteBuf decryptedPayload = null;
    try {
        payload = fromBase64(bufferAllocator, parts[0]);
        digest = fromBase64(bufferAllocator, parts[1]);
        expectedDigest = signer.sign(payload, bufferAllocator);
        if (ByteBufUtil.equals(digest, expectedDigest)) {
            decryptedPayload = crypto.decrypt(payload.resetReaderIndex(), bufferAllocator);
        } else {
            decryptedPayload = Unpooled.buffer(0, 0);
        }
    } finally {
        if (payload != null) {
            payload.touch().release();
        }
        if (digest != null) {
            digest.release();
        }
        if (expectedDigest != null) {
            expectedDigest.release();
        }
    }
    return decryptedPayload.touch();
}

From source file:ratpack.util.internal.BufferUtil.java

License:Apache License

public static void writeTo(ByteBuf byteBuf, OutputStream outputStream) throws IOException {
    byteBuf.resetReaderIndex();
    byteBuf.readBytes(outputStream, byteBuf.writerIndex());
}

From source file:ru.calypso.ogar.server.net.PacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
    ByteBuf buf = frame.content().order(ByteOrder.LITTLE_ENDIAN);
    if (buf.capacity() < 1) {
        // Discard empty messages
        return;//from   ww w . ja  v  a2s  .  c o  m
    }

    buf.resetReaderIndex();
    int packetId = buf.readUnsignedByte();
    Packet packet = PacketRegistry.CLIENT2SERVER.constructPacket(packetId);

    if (packet == null) {
        _log.info("Unknown packet ID: " + packetId + ", user disconected!");
        ctx.disconnect();
        return;
    }

    Log.logDebug("Received packet ID " + packetId + " (" + packet.getClass().getSimpleName() + ") from "
            + ctx.channel().remoteAddress());

    packet.readData(buf);
    out.add(packet);
}