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:net.tomp2p.storage.AlternativeCompositeByteBuf.java

License:Apache License

@Override
public ByteBuf writeBytes(ByteBuf src, int length) {
    if (length > src.readableBytes()) {
        throw new IndexOutOfBoundsException(String.format(
                "length(%d) exceeds src.readableBytes(%d) where src is: %s", length, src.readableBytes(), src));
    }// ww w . j  a  va 2 s  .  c  o  m
    writeBytes(src, src.readerIndex(), length);
    src.readerIndex(src.readerIndex() + length);
    return this;
}

From source file:net.tomp2p.storage.Data.java

License:Apache License

/**
 * Reads the header. Does not modify the buffer positions if header could
 * not be fully read.//from w w  w  .j  ava 2  s.com
 * 
 * Header format:
 * <pre>
 * 1 byte - header
 * 1 or 4 bytes - length
 * 4 or 0 bytes - ttl (hasTTL)
 * 1 or 0 bytes - number of basedon keys (hasBasedOn)
 * n x 20 bytes - basedon keys (hasBasedOn, number of basedon keys)
 * 2 or 0 bytes - length of public key (hasPublicKey)
 * n bytes - public key (hasPublicKey, length of public key)
 * </pre>
 * 
 * 
 * @param buf
 *            The buffer to read from
 * @return The data object, may be partially filled
 */
public static Data decodeHeader(final ByteBuf buf, final SignatureFactory signatureFactory) {
    // 2 is the smallest packet size, we could start if we know 1 byte to
    // decode the header, but we always need
    // a second byte. Thus, we are waiting for at least 2 bytes.
    if (buf.readableBytes() < Utils.BYTE_BYTE_SIZE + Utils.BYTE_BYTE_SIZE) {
        return null;
    }
    final int header = buf.getUnsignedByte(buf.readerIndex());
    final Data.Type type = Data.type(header);

    //Data length
    final int length;
    final int indexLength = Utils.BYTE_BYTE_SIZE;
    final int indexTTL;
    switch (type) {
    case SMALL:
        length = buf.getUnsignedByte(buf.readerIndex() + indexLength);
        indexTTL = indexLength + Utils.BYTE_BYTE_SIZE;
        break;
    case LARGE:
        indexTTL = indexLength + Utils.INTEGER_BYTE_SIZE;
        if (buf.readableBytes() < indexTTL) {
            return null;
        }
        length = buf.getInt(buf.readerIndex() + indexLength);
        break;
    default:
        throw new IllegalArgumentException("unknown type");
    }

    //TTL
    final int ttl;
    final int indexBasedOnNr;
    if (hasTTL(header)) {
        indexBasedOnNr = indexTTL + Utils.INTEGER_BYTE_SIZE;
        if (buf.readableBytes() < indexBasedOnNr) {
            return null;
        }
        ttl = buf.getInt(buf.readerIndex() + indexTTL);
    } else {
        ttl = -1;
        indexBasedOnNr = indexTTL;
    }

    //Nr BasedOn + basedon
    final int numBasedOn;
    final int indexPublicKeySize;
    final int indexBasedOn;
    final Set<Number160> basedOn = new HashSet<Number160>();
    if (hasBasedOn(header)) {
        // get # of based on keys
        indexBasedOn = indexBasedOnNr + Utils.BYTE_BYTE_SIZE;
        if (buf.readableBytes() < indexBasedOn) {
            return null;
        }
        numBasedOn = buf.getUnsignedByte(buf.readerIndex() + indexBasedOnNr) + 1;
        indexPublicKeySize = indexBasedOn + (numBasedOn * Number160.BYTE_ARRAY_SIZE);
        if (buf.readableBytes() < indexPublicKeySize) {
            return null;
        }
        //get basedon
        int index = buf.readerIndex() + indexBasedOnNr + Utils.BYTE_BYTE_SIZE;
        final byte[] me = new byte[Number160.BYTE_ARRAY_SIZE];
        for (int i = 0; i < numBasedOn; i++) {
            buf.getBytes(index, me);
            index += Number160.BYTE_ARRAY_SIZE;
            basedOn.add(new Number160(me));
        }

    } else {
        // no based on keys
        indexPublicKeySize = indexBasedOnNr;
        numBasedOn = 0;
    }

    //public key and size
    final int publicKeySize;
    final int indexPublicKey;
    final int indexEnd;
    final PublicKey publicKey;
    if (hasPublicKey(header)) {
        indexPublicKey = indexPublicKeySize + Utils.SHORT_BYTE_SIZE;
        if (buf.readableBytes() < indexPublicKey) {
            return null;
        }
        publicKeySize = buf.getUnsignedShort(buf.readerIndex() + indexPublicKeySize);
        indexEnd = indexPublicKey + publicKeySize;
        if (buf.readableBytes() < indexEnd) {
            return null;
        }
        //get public key
        buf.skipBytes(indexPublicKeySize);
        publicKey = signatureFactory.decodePublicKey(buf);
    } else {
        publicKeySize = 0;
        indexPublicKey = indexPublicKeySize;
        buf.skipBytes(indexPublicKey);
        publicKey = null;
    }

    //now we have read the header and the length
    final Data data = new Data(header, length);
    data.ttlSeconds = ttl;
    data.basedOnSet = basedOn;
    data.publicKey = publicKey;
    return data;
}

From source file:net.tomp2p.synchronization.SyncUtils.java

License:Apache License

public static List<Instruction> decodeInstructions(ByteBuf buf) {
    List<Instruction> result = new ArrayList<Instruction>();
    while (buf.isReadable()) {
        final int header = buf.readInt();
        if ((header & 0x80000000) != 0) {
            //first bit set, we have a reference
            final int reference = header & 0x7FFFFFFF;
            result.add(new Instruction(reference));
        } else {//  www.j a v a2s  . c  o m
            //otherwise the header is the length
            final int length = header;
            final int remaining = Math.min(length, buf.readableBytes());
            DataBuffer literal = new DataBuffer(buf.slice(buf.readerIndex(), remaining));
            buf.skipBytes(remaining);
            result.add(new Instruction(literal));
        }
    }
    return result;
}

From source file:netty.syslog.DecoderUtil.java

License:Open Source License

static byte peek(ByteBuf buffer) {
    return buffer.getByte(buffer.readerIndex());
}

From source file:netty.syslog.DecoderUtil.java

License:Open Source License

static void expect(ByteBuf buffer, char c) {
    if (buffer.readByte() != c) {
        throw new DecoderException("Expected " + c + " at index " + buffer.readerIndex());
    }//from   ww  w. ja  v a 2  s.co m
}

From source file:netty.syslog.DecoderUtil.java

License:Open Source License

static String readStringToSpace(ByteBuf buffer, boolean checkNull) {
    if (checkNull && peek(buffer) == '-') {
        buffer.readByte();/*from   w w  w .j  a  v a 2 s .com*/
        return null;
    }
    int length = -1;
    for (int i = buffer.readerIndex(); i < buffer.capacity(); i++) {
        if (buffer.getByte(i) == ' ') {
            length = i - buffer.readerIndex();
            break;
        }
    }
    if (length < 0) {
        length = buffer.readableBytes();
    }
    final String s = buffer.toString(buffer.readerIndex(), length, CharsetUtil.UTF_8);
    buffer.skipBytes(length);
    return s;
}

From source file:netty.syslog.MessageDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> objects) throws Exception {
    if (buffer.readableBytes() < 1) {
        return;/*from   w  w w  . j  ava2 s . c  o  m*/
    }
    final Message.MessageBuilder messageBuilder = Message.MessageBuilder.create();

    // Decode PRI
    expect(buffer, '<');
    final int pri = readDigit(buffer);
    if (pri < 0 || pri > 191) {
        throw new DecoderException("Invalid PRIVAL " + pri);
    }
    final int facility = pri / 8;
    final int severity = pri % 8;

    messageBuilder.facility(Message.Facility.values()[facility]);
    messageBuilder.severity(Message.Severity.values()[severity]);

    expect(buffer, '>');

    // Decode VERSION
    if (buffer.readByte() != '1') {
        throw new DecoderException("Expected a version 1 syslog message");
    }
    expect(buffer, ' ');

    // Decode TIMESTAMP
    final ZonedDateTime timestamp;
    final String timeStampString = readStringToSpace(buffer, true);
    if (timeStampString == null) {
        timestamp = null;
    } else {
        timestamp = ZonedDateTime.parse(timeStampString);
    }
    messageBuilder.timestamp(timestamp);
    expect(buffer, ' ');

    // Decode HOSTNAME
    messageBuilder.hostname(readStringToSpace(buffer, true));
    expect(buffer, ' ');

    // Decode APP-NAME
    messageBuilder.applicationName(readStringToSpace(buffer, true));
    expect(buffer, ' ');

    // Decode PROC-ID
    messageBuilder.processId(readStringToSpace(buffer, true));
    expect(buffer, ' ');

    // Decode MSGID
    messageBuilder.messageId(readStringToSpace(buffer, true));
    expect(buffer, ' ');

    // TODO Decode structured data
    expect(buffer, '-');
    expect(buffer, ' ');

    final int length = buffer.readableBytes();
    messageBuilder.content(buffer.slice(buffer.readerIndex(), length).retain());
    buffer.skipBytes(length);

    objects.add(messageBuilder.build());
}

From source file:nettyClient4.clientDecoder.java

License:Apache License

/**
 * return the  date of ByteBuf//from w w  w .j a va 2s .co  m
 * @param ctx
 * @param in
 * @return
 * @throws Exception
 */
private ByteBuf decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes());
        in.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;
        failIfNecessary(ctx, false);
        return null;
    }

    if (in.readableBytes() < lengthFieldEndOffset) {
        return null;
    }

    int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset;

    /**??*/
    //        long frameLength = (in.order(byteOrder)).getUnsignedByte(actualLengthFieldOffset);
    long frameLength = (in.order(byteOrder)).getUnsignedShort(actualLengthFieldOffset);

    if (frameLength < 0) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength);
    }

    frameLength += lengthAdjustment + lengthFieldEndOffset;

    if (frameLength < lengthFieldEndOffset) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than lengthFieldEndOffset: " + lengthFieldEndOffset);
    }

    if (frameLength > maxFrameLength) {
        // Enter the discard mode and discard everything received so far.
        discardingTooLongFrame = true;
        tooLongFrameLength = frameLength;
        bytesToDiscard = frameLength - in.readableBytes();
        in.skipBytes(in.readableBytes());
        failIfNecessary(ctx, true);
        return null;
    }

    // never overflows because it's less than maxFrameLength
    int frameLengthInt = (int) frameLength;
    if (in.readableBytes() < frameLengthInt) {
        return null;
    }

    if (initialBytesToStrip > frameLengthInt) {
        in.skipBytes(frameLengthInt);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than initialBytesToStrip: " + initialBytesToStrip);
    }
    in.skipBytes(initialBytesToStrip);

    // extract frame
    int readerIndex = in.readerIndex();
    int actualFrameLength = frameLengthInt - initialBytesToStrip;
    ByteBuf frame = extractFrame(in, readerIndex, actualFrameLength, ctx);
    in.readerIndex(readerIndex + actualFrameLength);
    return frame;
}

From source file:nettyClient4.clientEncoder.java

License:Apache License

/**
 * Encode a message into a {@link io.netty.buffer.ByteBuf}. This method will be called for each written message that can be handled
 * by this encoder.//from   www .j a  v a 2s .  c  o m
 *
 * @param ctx the {@link io.netty.channel.ChannelHandlerContext} which this {@link io.netty.handler.codec.MessageToByteEncoder} belongs to
 * @param msg the message to encode
 * @param out the {@link io.netty.buffer.ByteBuf} into which the encoded message will be written
 * @throws Exception is thrown if an error accour
 */
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    out.writeBytes(msg, msg.readerIndex(), msg.readableBytes());
}

From source file:nl.thijsalders.spigotproxy.haproxy.HAProxyMessageDecoder.java

License:Apache License

/**
 * Returns the proxy protocol specification version in the buffer if the version is found.
 * Returns -1 if no version was found in the buffer.
 *///  ww w .  j  av a2  s.  c o  m
private static int findVersion(final ByteBuf buffer) {
    final int n = buffer.readableBytes();
    // per spec, the version number is found in the 13th byte
    if (n < 13) {
        return -1;
    }

    int idx = buffer.readerIndex();
    return match(BINARY_PREFIX, buffer, idx) ? buffer.getByte(idx + BINARY_PREFIX_LENGTH) : 1;
}