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:bftsmart.communication.client.netty.NettyTOMMessageDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> list) throws Exception {

    // Wait until the length prefix is available.
    if (buffer.readableBytes() < Integer.BYTES) {
        return;//from w  ww . j a  v  a 2  s. c  om
    }

    int dataLength = buffer.getInt(buffer.readerIndex());

    //Logger.println("Receiving message with "+dataLength+" bytes.");

    // Wait until the whole data is available.
    if (buffer.readableBytes() < dataLength + Integer.BYTES) {
        return;
    }

    // Skip the length field because we know it already.
    buffer.skipBytes(Integer.BYTES);

    int size = buffer.readInt();
    byte[] data = new byte[size];
    buffer.readBytes(data);

    byte[] signature = null;
    size = buffer.readInt();

    if (size > 0) {
        signature = new byte[size];
        buffer.readBytes(signature);
    }

    DataInputStream dis = null;
    TOMMessage sm = null;

    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        dis = new DataInputStream(bais);
        sm = new TOMMessage();
        sm.rExternal(dis);
        sm.serializedMessage = data;

        if (signature != null) {
            sm.serializedMessageSignature = signature;
            sm.signed = true;
        }

        if (!isClient) {
            rl.readLock().lock();
            if (!sessionTable.containsKey(sm.getSender())) {
                rl.readLock().unlock();

                NettyClientServerSession cs = new NettyClientServerSession(context.channel(), sm.getSender());

                rl.writeLock().lock();
                sessionTable.put(sm.getSender(), cs);
                logger.debug("Active clients: " + sessionTable.size());
                rl.writeLock().unlock();

            } else {
                rl.readLock().unlock();
            }
        }
        logger.debug("Decoded reply from " + sm.getSender() + " with sequence number " + sm.getSequence());
        list.add(sm);
    } catch (Exception ex) {

        logger.error("Failed to decode TOMMessage", ex);
    }
    return;
}

From source file:books.netty.protocol.netty.codec.MarshallingDecoder.java

License:Apache License

protected Object decode(ByteBuf in) throws Exception {
    int objectSize = in.readInt();
    ByteBuf buf = in.slice(in.readerIndex(), objectSize);
    ByteInput input = new ChannelBufferByteInput(buf);
    try {/*from w w  w.  j av  a 2s.  co  m*/
        unmarshaller.start(input);
        Object obj = unmarshaller.readObject();
        unmarshaller.finish();
        in.readerIndex(in.readerIndex() + objectSize);
        return obj;
    } finally {
        unmarshaller.close();
    }
}

From source file:buildcraft.core.network.serializers.SerializerFluidStack.java

License:Minecraft Mod Public

@Override
public Object read(ByteBuf data, Object o, SerializationContext context) {
    if (!data.readBoolean()) {
        return null;
    } else {/*from  w ww. j  a  v a2 s .c  om*/
        int id = data.readShort();
        int amount = data.readerIndex();

        NBTTagCompound nbt = null;

        if (data.readBoolean()) {
            nbt = Utils.readNBT(data);
            return new FluidStack(id, amount, nbt);
        } else {
            return new FluidStack(id, amount);
        }
    }
}

From source file:cloudeventbus.codec.Decoder.java

License:Open Source License

/**
 * Returns the number of bytes between the readerIndex of the haystack and
 * the first needle found in the haystack.  -1 is returned if no needle is
 * found in the haystack.//from w  w w.ja v  a2 s  . co  m
 * <p/>
 * Copied from {@link io.netty.handler.codec.DelimiterBasedFrameDecoder}.
 */
private int indexOf(ByteBuf haystack, byte[] needle) {
    for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i++) {
        int haystackIndex = i;
        int needleIndex;
        for (needleIndex = 0; needleIndex < needle.length; needleIndex++) {
            if (haystack.getByte(haystackIndex) != needle[needleIndex]) {
                break;
            } else {
                haystackIndex++;
                if (haystackIndex == haystack.writerIndex() && needleIndex != needle.length - 1) {
                    return -1;
                }
            }
        }

        if (needleIndex == needle.length) {
            // Found the needle from the haystack!
            return i - haystack.readerIndex();
        }
    }
    return -1;
}

From source file:cloudfoundry.norouter.f5.dropsonde.LineEventDecoder.java

License:Open Source License

private String nextString(ByteBuf buffer) {
    // Read space terminated string
    final int start = buffer.readerIndex();
    int length = 0;
    while (buffer.readByte() != ' ') {
        length++;//from w w w  .  j a  v a  2  s.c  om
    }
    return buffer.toString(start, length, StandardCharsets.UTF_8);
}

From source file:com.addthis.hydra.data.util.KeyTopper.java

License:Apache License

@Override
public void bytesDecode(byte[] b, long version) {
    map = new HashMap<>();
    errors = null;/*from   w w  w.j  a  v  a 2  s .  c  o m*/
    if (b.length == 0) {
        return;
    }
    ByteBuf byteBuf = Unpooled.wrappedBuffer(b);
    try {
        byte marker = byteBuf.getByte(byteBuf.readerIndex());
        if (marker == 0) {
            errors = new HashMap<>();
            // Consume the sentinel byte value
            byteBuf.readByte();
        }
        int mapSize = Varint.readUnsignedVarInt(byteBuf);
        try {
            if (mapSize > 0) {
                for (int i = 0; i < mapSize; i++) {
                    int keyLength = Varint.readUnsignedVarInt(byteBuf);
                    byte[] keybytes = new byte[keyLength];
                    byteBuf.readBytes(keybytes);
                    String k = new String(keybytes, "UTF-8");
                    long value = Varint.readUnsignedVarLong(byteBuf);
                    map.put(k, value);
                    if (hasErrors()) {
                        long error = Varint.readUnsignedVarLong(byteBuf);
                        if (error != 0) {
                            errors.put(k, error);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw Throwables.propagate(e);
        }
    } finally {
        byteBuf.release();
    }
}

From source file:com.alibaba.dubbo.qos.server.handler.QosProcessHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 1) {
        return;//from  w  w w .ja v  a2 s  . com
    }

    // read one byte to guess protocol
    final int magic = in.getByte(in.readerIndex());

    ChannelPipeline p = ctx.pipeline();
    p.addLast(new LocalHostPermitHandler(acceptForeignIp));
    if (isHttp(magic)) {
        // no welcome output for http protocol
        if (welcomeFuture != null && welcomeFuture.isCancellable()) {
            welcomeFuture.cancel(false);
        }
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpProcessHandler());
        p.remove(this);
    } else {
        p.addLast(new LineBasedFrameDecoder(2048));
        p.addLast(new StringDecoder(CharsetUtil.UTF_8));
        p.addLast(new StringEncoder(CharsetUtil.UTF_8));
        p.addLast(new IdleStateHandler(0, 0, 5 * 60));
        p.addLast(new TelnetProcessHandler());
        p.remove(this);
    }
}

From source file:com.antsdb.saltedfish.server.mysql.packet.replication.RowsEventV2Packet.java

License:Open Source License

@Override
public void read(MysqlClientHandler handler, ByteBuf in) {
    // header/*  www .j  a va 2s .  c  o  m*/
    int begin = in.readerIndex();

    // 6 bytes tabble id
    tableId = BufferUtils.readPackedInteger(in, 6);
    // 2 bytes flags
    flags = BufferUtils.readInt(in);
    extraDataLen = BufferUtils.readInt(in);

    // body
    // number of columns
    int index = in.readerIndex();
    colCount = (int) BufferUtils.readLength(in);

    int presentCount = (colCount + 7) / 8;
    byte[] presentBits = new byte[presentCount];
    in.readBytes(presentBits);

    colPresentBitmap = BitSet.valueOf(presentBits);

    if (eventType == ReplicationPacket.UPDATE_ROWS_EVENT) {
        byte[] presentUptBits = new byte[presentCount];
        in.readBytes(presentUptBits);
        colPresentBitmapAftImg = BitSet.valueOf(presentUptBits);
    }

    int readCnt = in.readerIndex() - index;

    // eventlength - event_header_length - post_header_length - rest data length
    rawRows = in.readBytes((int) eventlength - 29 - readCnt);

    int end = in.readerIndex();

    if (_log.isTraceEnabled()) {
        in.readerIndex(begin);
        byte[] bytes = new byte[end - begin];
        in.readBytes(bytes);
        String dump = '\n' + UberUtil.hexDump(bytes);
        _log.trace("Packet Info:\n" + this.toString() + "\nRowsEventV2Packet packet:\n" + dump);
    }

}

From source file:com.antsdb.saltedfish.server.mysql.packet.replication.TableMapPacket.java

License:Open Source License

@Override
public void read(MysqlClientHandler handler, ByteBuf in) {
    // header//from w ww .  j a v  a 2s . c  o m
    int begin = in.readerIndex();

    tableId = BufferUtils.readPackedInteger(in, 6);
    flags = BufferUtils.readInt(in);

    // payload
    schemaName = BufferUtils.readStringWithLength(in);
    // seperated by 0
    in.readByte();
    tableName = BufferUtils.readStringWithLength(in);
    // seperated by 0
    in.readByte();
    colCount = (int) BufferUtils.readLength(in);
    colTypeDef = BufferUtils.readBytes(in, colCount);

    metaCount = (int) BufferUtils.readLength(in);
    colMetaDef = BufferUtils.readBytes(in, metaCount);

    int nullCount = (colCount + 7) / 8;
    nullBitMap = new byte[nullCount];
    in.readBytes(nullBitMap);

    int end = in.readerIndex();

    if (_log.isTraceEnabled()) {
        in.readerIndex(begin);
        byte[] bytes = new byte[end - begin];
        in.readBytes(bytes);
        String dump = '\n' + UberUtil.hexDump(bytes);
        _log.trace("Packet Info:\n" + this.toString() + "\nTableMapPacket packet:\n" + dump);
    }

}

From source file:com.antsdb.saltedfish.server.mysql.PacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // do we have length field in buffer ?

    if (!in.isReadable(4)) {
        return;/*from w ww  .  ja  v a 2 s  .  com*/
    }

    // do we have entire packet in the buffer?

    in.markReaderIndex();
    int size = BufferUtils.readLongInt(in);
    int sequence = in.readByte() & 0xff;
    if (size == 0) {
        out.add(new ShutdownPacket());
        return;
    }
    if (!in.isReadable(size)) {
        in.resetReaderIndex();
        return;
    }

    // is very large packet?

    this.handler.packetSequence = sequence;
    if (size == MAX_PACKET_SIZE) {
        if (this.largePacket == null) {
            this.largePacket = ctx.alloc().directBuffer();
        }
        this.largePacket.writeBytes(in, MAX_PACKET_SIZE);
        return;
    }
    if (this.largePacket != null) {
        this.largePacket.writeBytes(in, size);
    }

    // parse packet

    if (this.largePacket == null) {
        int pos = in.readerIndex();
        try {
            RecievePacket packet = readPacket(in, size);
            out.add(packet);
        } finally {
            in.readerIndex(pos + size);
        }
    } else {
        RecievePacket packet = readPacket(this.largePacket, size);
        out.add(packet);
        this.largePacket.release();
        this.largePacket = null;
    }
}