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:dorkbox.network.pipeline.tcp.KryoDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf in, List<Object> out) throws Exception {
    // Make sure if the length field was received,
    // and read the length of the next object from the socket.
    int lengthLength = OptimizeUtilsByteBuf.canReadInt(in);
    int readableBytes = in.readableBytes(); // full length of available bytes.

    if (lengthLength == 0 || readableBytes < 2 || readableBytes < lengthLength) {
        // The length field was not fully received - do nothing (wait for more...)
        // This method will be invoked again when more packets are
        // received and appended to the buffer.
        return;/*w w w . ja  v a  2 s  .c o  m*/
    }

    // The length field is in the buffer.

    // save the writerIndex for local access
    int writerIndex = in.writerIndex();

    // Mark the current buffer position before reading the length fields
    // because the whole frame might not be in the buffer yet.
    // We will reset the buffer position to the marked position if
    // there's not enough bytes in the buffer.
    in.markReaderIndex();

    // Read the length field.
    int length = OptimizeUtilsByteBuf.readInt(in, true);
    readableBytes = in.readableBytes(); // have to adjust readable bytes, since we just read an int off the buffer.

    if (length == 0) {
        context.fireExceptionCaught(new IllegalStateException("KryoDecoder had a read length of 0"));
        return;
    }

    // we can't test against a single "max size", since objects can back-up on the buffer.
    // we must ABSOLUTELY follow a "max size" rule when encoding objects, however.

    final NetworkSerializationManager serializationManager = this.serializationManager;

    // Make sure if there's enough bytes in the buffer.
    if (length > readableBytes) {
        // The whole bytes were not received yet - return null.
        // This method will be invoked again when more packets are
        // received and appended to the buffer.

        // Reset to the marked position to read the length field again
        // next time.
        in.resetReaderIndex();

        // wait for the rest of the object to come in.
        // System.err.println(Thread.currentThread().getName() + " waiting for more of the object to arrive");
    }

    // how many objects are on this buffer?
    else if (readableBytes > length) {
        // more than one!
        // read the object off of the buffer. (save parts of the buffer so if it is too big, we can go back to it, and use it later on...)

        // we know we have at least one object
        int objectCount = 1;
        int endOfObjectPosition = in.readerIndex() + length;

        // set us up for the next object.
        in.readerIndex(endOfObjectPosition);

        // how many more objects?? The first time, it can be off, because we already KNOW it's > 0.
        //  (That's how we got here to begin with)
        while (readableBytes > 0) {
            if (OptimizeUtilsByteBuf.canReadInt(in) > 0) {
                length = OptimizeUtilsByteBuf.readInt(in, true);

                if (length <= 0) {
                    // throw new IllegalStateException("Kryo DecoderTCP had a read length of 0");
                    break;
                }

                endOfObjectPosition = in.readerIndex() + length;

                // position the reader to look for the NEXT object
                if (endOfObjectPosition <= writerIndex) {
                    in.readerIndex(endOfObjectPosition);
                    readableBytes = in.readableBytes();
                    objectCount++;
                } else {
                    break;
                }
            } else {
                break;
            }
        }
        // readerIndex is currently at the MAX place it can read data off the buffer.
        // reset it to the spot BEFORE we started reading data from the buffer.
        in.resetReaderIndex();

        // System.err.println("Found " + objectCount + " objects in this buffer.");

        // NOW add each one of the NEW objects to the array!

        for (int i = 0; i < objectCount; i++) {
            length = OptimizeUtilsByteBuf.readInt(in, true); // object LENGTH

            // however many we need to
            Object object;
            try {
                object = readObject(serializationManager, context, in, length);
                out.add(object);
            } catch (Exception ex) {
                context.fireExceptionCaught(new IOException("Unable to deserialize object!", ex));
            }
        }
        // the buffer reader index will be at the correct location, since the read object method advances it.
    } else {
        // exactly one!
        Object object;
        try {
            object = readObject(serializationManager, context, in, length);
            out.add(object);
        } catch (Exception ex) {
            context.fireExceptionCaught(
                    new IOException("Unable to deserialize object for " + this.getClass(), ex));
        }
    }
}

From source file:dorkbox.network.serialization.Serialization.java

License:Apache License

/**
 * Reads an object from the buffer./*from  w w w .  j a v  a2  s . c  o  m*/
 * <p>
 * No crypto and no sequence number
 *
 * @param length should ALWAYS be the length of the expected object!
 */
@Override
public final Object read(final ByteBuf buffer, final int length) throws IOException {
    final KryoExtra kryo = kryoPool.take();
    try {
        if (wireReadLogger.isTraceEnabled()) {
            int start = buffer.readerIndex();
            Object object = kryo.read(buffer);
            int end = buffer.readerIndex();

            wireReadLogger.trace(ByteBufUtil.hexDump(buffer, start, end - start));

            return object;
        } else {
            return kryo.read(buffer);
        }
    } finally {
        kryoPool.put(kryo);
    }
}

From source file:dorkbox.network.serialization.Serialization.java

License:Apache License

/**
 * Reads an object from the buffer.//from w w  w.  java 2 s  . c o  m
 * <p>
 * Crypto + sequence number
 *
 * @param connection can be NULL
 * @param length should ALWAYS be the length of the expected object!
 */
@SuppressWarnings("Duplicates")
@Override
public final Object readWithCrypto(final Connection_ connection, final ByteBuf buffer, final int length)
        throws IOException {
    final KryoExtra kryo = kryoPool.take();
    try {
        // we only need to encrypt when NOT on loopback, since encrypting on loopback is a waste of CPU
        if (connection.isLoopback()) {
            if (wireReadLogger.isTraceEnabled()) {
                int start = buffer.readerIndex();
                Object object = kryo.readCompressed(connection, buffer, length);
                int end = buffer.readerIndex();

                wireReadLogger.trace(ByteBufUtil.hexDump(buffer, start, end - start));

                return object;
            } else {
                return kryo.readCompressed(connection, buffer, length);
            }
        } else {
            if (wireReadLogger.isTraceEnabled()) {
                int start = buffer.readerIndex();
                Object object = kryo.readCrypto(connection, buffer, length);
                int end = buffer.readerIndex();

                wireReadLogger.trace(ByteBufUtil.hexDump(buffer, start, end - start));

                return object;
            } else {
                return kryo.readCrypto(connection, buffer, length);
            }
        }
    } finally {
        kryoPool.put(kryo);
    }
}

From source file:dorkbox.util.bytes.OptimizeUtilsByteBuf.java

License:Apache License

/**
 * FROM KRYO//w  w w  .  j  a v a 2 s  .  c om
 * <p>
 * look at buffer, and see if we can read the length of the int off of it. (from the reader index)
 *
 * @return 0 if we could not read anything, >0 for the number of bytes for the int on the buffer
 */
public static int canReadInt(ByteBuf buffer) {
    int startIndex = buffer.readerIndex();
    try {
        int remaining = buffer.readableBytes();
        for (int offset = 0, count = 1; offset < 32 && remaining > 0; offset += 7, remaining--, count++) {
            int b = buffer.readByte();
            if ((b & 0x80) == 0) {
                return count;
            }
        }
        return 0;
    } finally {
        buffer.readerIndex(startIndex);
    }
}

From source file:dorkbox.util.bytes.OptimizeUtilsByteBuf.java

License:Apache License

/**
 * FROM KRYO/*w  ww. j  a v a  2s  . c  o m*/
 * <p>
 * look at buffer, and see if we can read the length of the long off of it (from the reader index).
 *
 * @return 0 if we could not read anything, >0 for the number of bytes for the long on the buffer
 */
public static int canReadLong(ByteBuf buffer) {
    int position = buffer.readerIndex();
    try {
        int remaining = buffer.readableBytes();
        for (int offset = 0, count = 1; offset < 64 && remaining > 0; offset += 7, remaining--, count++) {
            int b = buffer.readByte();
            if ((b & 0x80) == 0) {
                return count;
            }
        }
        return 0;
    } finally {
        buffer.readerIndex(position);
    }
}

From source file:dpfmanager.shell.modules.server.core.HttpServerHandler.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // Will use the first five bytes to detect a protocol.
    if (in.readableBytes() < 5) {
        in.clear();// w w w. j ava 2 s. c  o m
        ctx.close();
        return;
    }

    final int magic1 = in.getUnsignedByte(in.readerIndex());
    final int magic2 = in.getUnsignedByte(in.readerIndex() + 1);
    if (isPost(magic1, magic2) || isOptions(magic1, magic2)) {
        // POST
        ChannelPipeline pipeline = ctx.pipeline();
        pipeline.addLast(new HttpRequestDecoder());
        pipeline.addLast(new HttpResponseEncoder());
        pipeline.addLast(new HttpPostHandler(context));
        pipeline.remove(this);
    } else if (isGet(magic1, magic2)) {
        // GET
        ChannelPipeline pipeline = ctx.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(65536));
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpGetHandler(context));
        pipeline.remove(this);
    } else {
        in.clear();
        ctx.close();
    }
}

From source file:info.conspire.temur.network.protocol.ClientMessage.java

License:BEER-WARE LICENSE

public ClientMessage(int id, int length, ByteBuf buffer) {
    this.length = length;
    this.id = id;
    this.buffer = buffer;
    this.originIndex = buffer.readerIndex();
}

From source file:io.advantageous.conekt.dns.impl.netty.decoder.AddressDecoder.java

License:Open Source License

/**
 * Returns an {@link java.net.InetAddress} containing a decoded address from either an A
 * or AAAA resource record./*from   w ww . j a  va2s  . co m*/
 *
 * @param response the {@link DnsResponse} received that contained the resource
 *                 record being decoded
 * @param resource the {@link DnsResource} being decoded
 */
@Override
public InetAddress decode(DnsResponse response, DnsResource resource) {
    ByteBuf data = resource.content().copy().readerIndex(response.originalIndex());
    int size = data.writerIndex() - data.readerIndex();
    if (data.readerIndex() != 0 || size != octets) {
        throw new DecoderException("Invalid content length, or reader index when decoding address [index: "
                + data.readerIndex() + ", expected length: " + octets + ", actual: " + size + "].");
    }
    byte[] address = new byte[octets];
    data.getBytes(data.readerIndex(), address);
    try {
        return InetAddress.getByAddress(address);
    } catch (UnknownHostException e) {
        throw new DecoderException("Could not convert address "
                + data.toString(data.readerIndex(), size, CharsetUtil.UTF_8) + " to InetAddress.");
    }
}

From source file:io.advantageous.conekt.dns.impl.netty.decoder.TextDecoder.java

License:Open Source License

/**
 * Returns a decoded TXT (text) resource record, stored as an
 * {@link java.util.ArrayList} of {@code String}s.
 *
 * @param response the DNS response that contains the resource record being
 *                 decoded//from  w w w  . ja  v  a  2  s .  c  om
 * @param resource the resource record being decoded
 */
@Override
public List<String> decode(DnsResponse response, DnsResource resource) {
    List<String> list = new ArrayList<>();
    ByteBuf data = resource.content().readerIndex(response.originalIndex());
    int index = data.readerIndex();
    while (index < data.writerIndex()) {
        int len = data.getUnsignedByte(index++);
        list.add(data.toString(index, len, CharsetUtil.UTF_8));
        index += len;
    }
    return list;
}

From source file:io.advantageous.conekt.dns.impl.netty.DnsResponse.java

License:Open Source License

public DnsResponse(ByteBuf rawPacket) {
    this.rawPacket = rawPacket;
    this.originalIndex = rawPacket.readerIndex();
}