Example usage for io.netty.buffer ByteBuf writerIndex

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

Introduction

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

Prototype

public abstract int writerIndex();

Source Link

Document

Returns the writerIndex of this buffer.

Usage

From source file:io.reactiverse.pgclient.impl.codec.DataTypeCodec.java

License:Apache License

private static <T> void binaryEncodeArray(T[] values, DataType type, ByteBuf buff) {
    int startIndex = buff.writerIndex();
    buff.writeInt(1); // ndim
    buff.writeInt(0); // dataoffset
    buff.writeInt(type.id); // elemtype
    buff.writeInt(values.length); // dimension
    buff.writeInt(1); // lower bnds
    boolean hasNulls = false;
    for (T value : values) {
        if (value == null) {
            hasNulls = true;//from   w w w  . j ava  2 s  .  c om
            buff.writeInt(-1);
        } else {
            int idx = buff.writerIndex();
            buff.writeInt(0);
            encodeBinary(type, value, buff);
            buff.setInt(idx, buff.writerIndex() - idx - 4);
        }
    }
    if (hasNulls) {
        buff.setInt(startIndex + 4, 1);
    }
}

From source file:io.reactiverse.pgclient.impl.codec.decoder.InitiateSslHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ByteBuf byteBuf = Unpooled.buffer();
    byteBuf.writeInt(0);//from   ww  w.  j  av  a2s  . c  o m
    byteBuf.writeInt(code);
    //    out.writeInt(0x12345679);
    byteBuf.setInt(0, byteBuf.writerIndex());
    ctx.writeAndFlush(byteBuf);
    super.channelActive(ctx);
}

From source file:io.reactivex.netty.protocol.text.sse.ServerSentEventDecoder.java

License:Apache License

private int skipLineDelimiters(ByteBuf in) {
    int skipped = 0;
    while (in.writerIndex() - in.readerIndex() > 0) {
        // the above check is needed to ensure that last event is delivered
        // otherwise, an exception (Netty's Signal object) will be thrown
        // from ReplayingDecoderBuffer.readByte()
        char c = (char) in.readByte();
        if (isLineDelimiter(c)) {
            skipped += 1;/*from   w w  w. j a v a2  s .c om*/
            continue;
        }

        // Leave the reader index at the first letter of the next line, if any
        in.readerIndex(in.readerIndex() - 1);
        checkpoint(State.NEW_LINE);
        break;
    }

    return skipped;
}

From source file:io.servicecomb.foundation.vertx.VertxUtils.java

License:Apache License

public static byte[] getBytesFast(ByteBuf byteBuf) {
    if (byteBuf.hasArray()) {
        return byteBuf.array();
    }//from  w ww  . j  ava2  s.c o  m

    byte[] arr = new byte[byteBuf.writerIndex()];
    byteBuf.getBytes(0, arr);
    return arr;
}

From source file:io.vertx.core.buffer.BufferTest.java

License:Open Source License

@Test
public void testAppendDoesNotModifyByteBufIndex() throws Exception {
    ByteBuf buf = Unpooled.copiedBuffer("foobar".getBytes());
    assertEquals(0, buf.readerIndex());/*from   w w  w .j av a  2 s . co  m*/
    assertEquals(6, buf.writerIndex());
    Buffer buffer = Buffer.buffer(buf);
    Buffer other = Buffer.buffer("prefix");
    other.appendBuffer(buffer);
    assertEquals(0, buf.readerIndex());
    assertEquals(6, buf.writerIndex());
    assertEquals(other.toString(), "prefixfoobar");
}

From source file:io.vertx.core.dns.impl.decoder.RecordDecoder.java

License:Open Source License

static Function<DnsRecord, String> address(int octets) {
    return record -> {
        ByteBuf data = ((DnsRawRecord) record).content();
        int size = data.writerIndex() - data.readerIndex();
        if (size != octets) {
            throw new DecoderException("Invalid content length, or reader index when decoding address [index: "
                    + data.readerIndex() + ", expected length: " + octets + ", actual: " + size + "].");
        }/*w  w w .j av a2 s  . co m*/
        byte[] address = new byte[octets];
        data.getBytes(data.readerIndex(), address);
        try {
            return InetAddress.getByAddress(address).getHostAddress();
        } catch (UnknownHostException e) {
            throw new DecoderException("Could not convert address "
                    + data.toString(data.readerIndex(), size, CharsetUtil.UTF_8) + " to InetAddress.");
        }
    };
}

From source file:io.vertx.core.dns.impl.decoder.RecordDecoder.java

License:Open Source License

/**
 * Retrieves a domain name given a buffer containing a DNS packet without
 * advancing the readerIndex for the buffer.
 *
 * @param buf    the byte buffer containing the DNS packet
 * @param offset the position at which the name begins
 * @return the domain name for an entry/*w  w w  .j  av a2 s  .  c o m*/
 */
static String getName(ByteBuf buf, int offset) {
    StringBuilder name = new StringBuilder();
    for (int len = buf.getUnsignedByte(offset++); buf.writerIndex() > offset
            && len != 0; len = buf.getUnsignedByte(offset++)) {
        boolean pointer = (len & 0xc0) == 0xc0;
        if (pointer) {
            offset = (len & 0x3f) << 8 | buf.getUnsignedByte(offset++);
        } else {
            name.append(buf.toString(offset, len, CharsetUtil.UTF_8)).append(".");
            offset += len;
        }
    }
    if (name.length() == 0) {
        return null;
    }
    return name.substring(0, name.length() - 1);
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java

License:Apache License

/**
 * Retrieves a domain name given a buffer containing a DNS packet. If the
 * name contains a pointer, the position of the buffer will be set to
 * directly after the pointer's index after the name has been read.
 *
 * @param in the byte buffer containing the DNS packet
 * @return the domain name for an entry//w w  w .  ja va 2  s.  c  o m
 */
public static String decodeName(ByteBuf in) {
    int position = -1;
    int checked = 0;
    final int end = in.writerIndex();
    final int readable = in.readableBytes();

    // Looking at the spec we should always have at least enough readable bytes to read a byte here but it seems
    // some servers do not respect this for empty names. So just workaround this and return an empty name in this
    // case.
    //
    // See:
    // - https://github.com/netty/netty/issues/5014
    // - https://www.ietf.org/rfc/rfc1035.txt , Section 3.1
    if (readable == 0) {
        return ".";
    }

    final StringBuilder name = new StringBuilder(readable << 1);
    while (in.isReadable()) {
        final int len = in.readUnsignedByte();
        final boolean pointer = (len & 0xc0) == 0xc0;
        if (pointer) {
            if (position == -1) {
                position = in.readerIndex() + 1;
            }

            if (!in.isReadable()) {
                throw new CorruptedFrameException("truncated pointer in a name");
            }

            final int next = (len & 0x3f) << 8 | in.readUnsignedByte();
            if (next >= end) {
                throw new CorruptedFrameException("name has an out-of-range pointer");
            }
            in.readerIndex(next);

            // check for loops
            checked += 2;
            if (checked >= end) {
                throw new CorruptedFrameException("name contains a loop.");
            }
        } else if (len != 0) {
            if (!in.isReadable(len)) {
                throw new CorruptedFrameException("truncated label in a name");
            }
            name.append(in.toString(in.readerIndex(), len, CharsetUtil.UTF_8)).append('.');
            in.skipBytes(len);
        } else { // len == 0
            break;
        }
    }

    if (position != -1) {
        in.readerIndex(position);
    }

    if (name.length() == 0) {
        return ".";
    }

    if (name.charAt(name.length() - 1) != '.') {
        name.append('.');
    }

    return name.toString();
}

From source file:io.vertx.core.http.impl.HttpClientRequestImpl.java

License:Open Source License

private void write(ByteBuf buff, boolean end) {
    if (buff == null && !end) {
        // nothing to write to the connection just return
        return;//from  www . ja  v  a  2  s  .  c  o  m
    }

    if (end) {
        if (buff != null && !chunked && !contentLengthSet()) {
            headers().set(CONTENT_LENGTH, String.valueOf(buff.writerIndex()));
        }
    } else {
        if (!chunked && !contentLengthSet()) {
            throw new IllegalStateException(
                    "You must set the Content-Length header to be the total size of the message "
                            + "body BEFORE sending any data if you are not using HTTP chunked encoding.");
        }
    }

    if (buff != null) {
        written += buff.readableBytes();
        if (followRedirects > 0) {
            if (cachedChunks == null) {
                cachedChunks = Unpooled.compositeBuffer();
            }
            cachedChunks.addComponent(buff).writerIndex(cachedChunks.writerIndex() + buff.writerIndex());
        }
    }

    if (stream == null) {
        if (buff != null) {
            if (pendingChunks == null) {
                pendingChunks = buff;
            } else {
                CompositeByteBuf pending;
                if (pendingChunks instanceof CompositeByteBuf) {
                    pending = (CompositeByteBuf) pendingChunks;
                } else {
                    pending = Unpooled.compositeBuffer();
                    pending.addComponent(pendingChunks).writerIndex(pendingChunks.writerIndex());
                    pendingChunks = pending;
                }
                pending.addComponent(buff).writerIndex(pending.writerIndex() + buff.writerIndex());
            }
        }
        connect(null);
    } else {
        if (!headWritten) {
            writeHeadWithContent(buff, end);
        } else {
            stream.writeBuffer(buff, end);
        }
        if (end) {
            stream.connection().reportBytesWritten(written);
            if (respHandler != null) {
                stream.endRequest();
            }
        }
    }

    if (end) {
        completed = true;
        if (completionHandler != null) {
            completionHandler.handle(null);
        }
    }
}

From source file:jazmin.server.msg.codec.json.JSONDecoder.java

License:Open Source License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 *
 * @param   ctx             the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param   buffer          the {@link ByteBuf} from which to read data
 * @return  frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                          be created./* w w w. j ava2s. co  m*/
 */
protected ByteBuf decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    final int eol = findEndOfLine(buffer);
    if (!discarding) {
        if (eol >= 0) {
            final ByteBuf frame;
            final int length = eol - buffer.readerIndex();
            final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;

            if (length > maxLength) {
                buffer.readerIndex(eol + delimLength);
                fail(ctx, length);
                return null;
            }

            if (stripDelimiter) {
                frame = buffer.readBytes(length);
                buffer.skipBytes(delimLength);
            } else {
                frame = buffer.readBytes(length + delimLength);
            }

            return frame;
        } else {
            final int length = buffer.readableBytes();
            if (length > maxLength) {
                discardedBytes = length;
                buffer.readerIndex(buffer.writerIndex());
                discarding = true;
                if (failFast) {
                    fail(ctx, "over " + discardedBytes);
                }
            }
            return null;
        }
    } else {
        if (eol >= 0) {
            final int length = discardedBytes + eol - buffer.readerIndex();
            final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;
            buffer.readerIndex(eol + delimLength);
            discardedBytes = 0;
            discarding = false;
            if (!failFast) {
                fail(ctx, length);
            }
        } else {
            discardedBytes = buffer.readableBytes();
            buffer.readerIndex(buffer.writerIndex());
        }
        return null;
    }
}