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.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  av  a 2  s. 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   ww w  .j  a v a  2 s .  co  m*/
 * @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.DnsResponseDecoder.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 a  va  2 s.  c  o  m*/
 */
public 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.advantageous.conekt.http.impl.HttpClientRequestImpl.java

License:Open Source License

private void write(ByteBuf buff, boolean end) {
    int readableBytes = buff.readableBytes();
    if (readableBytes == 0 && !end) {
        // nothing to write to the connection just return
        return;/*from  ww  w .j av a  2  s  .  co m*/
    }

    if (end) {
        completed = true;
    }
    if (!end && !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.");
    }

    written += buff.readableBytes();
    if (conn == 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();
    } else {
        if (!headWritten) {
            writeHeadWithContent(buff, end);
        } else {
            if (end) {
                if (buff.isReadable()) {
                    conn.writeToChannel(new DefaultLastHttpContent(buff, false));
                } else {
                    conn.writeToChannel(LastHttpContent.EMPTY_LAST_CONTENT);
                }
            } else {
                conn.writeToChannel(new DefaultHttpContent(buff));
            }
        }
        if (end) {
            conn.reportBytesWritten(written);

            if (respHandler != null) {
                conn.endRequest();
            }
        }
    }
}

From source file:io.airlift.drift.transport.netty.codec.TestThriftFramedDecoder.java

License:Apache License

@Test
public void testChunked() {
    byte[] first = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    byte[] second = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    byte[] third = new byte[] { 5, 4, 3 };

    try (TestingPooledByteBufAllocator allocator = new TestingPooledByteBufAllocator()) {
        ByteBuf buffer = allocator.buffer(1024);

        ThriftFramedDecoder decoder = createDecoder(second.length);
        ByteBuf decoded = decode(decoder, buffer);
        assertNull(decoded);//www  .j a va 2s  .  c o  m

        // write a partial frame length
        buffer.writeByte(0xAB);
        decoded = decode(decoder, buffer);
        assertNull(decoded);
        assertEquals(buffer.readerIndex(), 0);
        assertEquals(buffer.writerIndex(), 1);

        // write only a frame length
        buffer.writerIndex(0);
        buffer.writeInt(first.length);
        decoded = decode(decoder, buffer);
        assertNull(decoded);
        assertEquals(buffer.readerIndex(), 0);
        assertEquals(buffer.writerIndex(), Integer.BYTES);

        // start writing a frame
        buffer.writeBytes(first, 0, 5);
        decoded = decode(decoder, buffer);
        assertNull(decoded);
        assertEquals(buffer.readerIndex(), 0);
        assertEquals(buffer.writerIndex(), Integer.BYTES + 5);

        // finish writing a frame
        buffer.writeBytes(first, 5, first.length - 5);
        decoded = decode(decoder, buffer);
        assertNotNull(decoded);
        assertContentEquals(decoded, first);
        decoded.release();

        // write the first frame
        writeLengthPrefixedFrame(buffer, second);
        // start writing the second frame
        buffer.writeInt(third.length);
        buffer.writeBytes(third, 0, 1);
        // decode the first frame
        decoded = decode(decoder, buffer);
        assertNotNull(decoded);
        assertContentEquals(decoded, second);
        decoded.release();

        // try decode the second frame
        decoded = decode(decoder, buffer);
        assertNull(decoded);

        // finish writing the second frame
        buffer.writeBytes(third, 1, third.length - 1);
        decoded = decode(decoder, buffer);
        assertNotNull(decoded);
        assertContentEquals(decoded, third);
        decoded.release();

        assertEquals(buffer.readerIndex(), buffer.writerIndex());

        buffer.release();
    }
}

From source file:io.codis.nedis.handler.RedisResponseDecoder.java

License:Apache License

private void setReaderIndex(ByteBuf in, int index) {
    in.readerIndex(index == -1 ? in.writerIndex() : index + 1);
}

From source file:io.crate.protocols.postgres.ClientMessages.java

License:Apache License

static void sendBindMessage(ByteBuf buffer, String portalName, String statementName, List<Object> params) {
    buffer.writeByte('B');
    byte[] portalBytes = portalName.getBytes(StandardCharsets.UTF_8);
    byte[] statementBytes = statementName.getBytes(StandardCharsets.UTF_8);

    int beforeLengthWriterIndex = buffer.writerIndex();
    buffer.writeInt(0);//  w ww.  j ava2 s. com
    writeCString(buffer, portalBytes);
    writeCString(buffer, statementBytes);
    buffer.writeShort(0); // formatCode use 0 to default to text for all
    buffer.writeShort(params.size());

    int paramsLength = 0;
    for (Object param : params) {
        BytesRef value = DataTypes.STRING.value(param);
        buffer.writeInt(value.length);
        // the strings here are _not_ zero-padded because we specify the length upfront
        buffer.writeBytes(value.bytes, value.offset, value.length);
        paramsLength += 4 + value.length;
    }
    buffer.writeShort(0); // numResultFormatCodes - 0 to default to text for all

    buffer.setInt(beforeLengthWriterIndex, 4 + portalBytes.length + 1 + statementBytes.length + 1 + 2 + // numFormatCodes
            2 + // numParams
            paramsLength + 2); // numResultColumnFormatCodes
}

From source file:io.crate.protocols.postgres.types.PGArray.java

License:Apache License

@Override
public int writeAsBinary(ByteBuf buffer, @Nonnull Object value) {
    int dimensions = getDimensions(value);

    List<Integer> dimensionsList = new ArrayList<>();
    buildDimensions((Object[]) value, dimensionsList, dimensions, 1);

    int bytesWritten = 4 + 4 + 4;
    final int lenIndex = buffer.writerIndex();
    buffer.writeInt(0);/*from   w ww  .  jav  a2s.c  om*/
    buffer.writeInt(dimensions);
    buffer.writeInt(1); // flags bit 0: 0=no-nulls, 1=has-nulls
    buffer.writeInt(typElem());

    for (Integer dim : dimensionsList) {
        buffer.writeInt(dim); // upper bound
        buffer.writeInt(dim); // lower bound
        bytesWritten += 8;
    }
    int len = bytesWritten + writeArrayAsBinary(buffer, (Object[]) value, dimensionsList, 1);
    buffer.setInt(lenIndex, len);
    return len;
}

From source file:io.datty.msgpack.core.ArrayMessageWriter.java

License:Apache License

@Override
public int skipHeader(int maxSize, ByteBuf sink) {
    int headerIndex = sink.writerIndex();
    int headerSize = getArrayHeaderSize(maxSize);
    for (int i = 0; i != headerSize; ++i) {
        sink.writeByte(0);//w ww  .  ja va 2  s . c  om
    }
    return headerIndex;
}

From source file:io.datty.msgpack.core.ArrayMessageWriter.java

License:Apache License

@Override
public void writeHeader(int arraySize, int maxSize, int headerIndex, ByteBuf sink) {
    int checkpoint = sink.writerIndex();
    sink.writerIndex(headerIndex);/*from   w  w  w  . j a va  2 s. c  o m*/
    writeArrayHeader(arraySize, maxSize, sink);
    sink.writerIndex(checkpoint);
}