Example usage for io.netty.buffer ByteBuf capacity

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

Introduction

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

Prototype

public abstract int capacity();

Source Link

Document

Returns the number of bytes (octets) this buffer can contain.

Usage

From source file:eu.stratosphere.runtime.io.network.netty.InboundEnvelopeDecoderTest.java

License:Apache License

/**
 * Returns slices with the specified sizes of the given buffer.
 * <p/>/*from ww w  .  j  av a 2  s . c  o m*/
 * When given n indexes, n+1 slices will be returned:
 * <ul>
 * <li>0 - sliceSizes[0]</li>
 * <li>sliceSizes[0] - sliceSizes[1]</li>
 * <li>...</li>
 * <li>sliceSizes[n-1] - buf.capacity()</li>
 * </ul>
 *
 * @return slices with the specified sizes of the given buffer
 */
private static ByteBuf[] slice(ByteBuf buf, int... sliceSizes) {
    if (sliceSizes.length == 0) {
        throw new IllegalStateException("Need to provide at least one slice size");
    }

    int numSlices = sliceSizes.length;
    // transform slice sizes to buffer indexes
    for (int i = 1; i < numSlices; i++) {
        sliceSizes[i] += sliceSizes[i - 1];
    }

    for (int i = 0; i < sliceSizes.length - 1; i++) {
        if (sliceSizes[i] >= sliceSizes[i + 1] || sliceSizes[i] <= 0 || sliceSizes[i] >= buf.capacity()) {
            throw new IllegalStateException(
                    String.format("Slice size %s are off for %s", Arrays.toString(sliceSizes), buf));
        }
    }

    ByteBuf[] slices = new ByteBuf[numSlices + 1];

    // slice at slice indexes
    slices[0] = buf.slice(0, sliceSizes[0]).retain();
    for (int i = 1; i < numSlices; i++) {
        slices[i] = buf.slice(sliceSizes[i - 1], sliceSizes[i] - sliceSizes[i - 1]).retain();
    }
    slices[numSlices] = buf.slice(sliceSizes[numSlices - 1], buf.capacity() - sliceSizes[numSlices - 1])
            .retain();

    return slices;
}

From source file:io.datty.aerospike.support.AerospikeValueUtil.java

License:Apache License

public static Value toValue(ByteBuf bufferOrNull) {

    if (bufferOrNull == null) {
        return new NullValue();
    } else if (bufferOrNull.hasArray()) {
        int start = bufferOrNull.readerIndex();
        int length = bufferOrNull.readableBytes();
        if (start != 0 || length != bufferOrNull.capacity()) {
            int baseOffset = bufferOrNull.arrayOffset() + start;
            return new ByteSegmentValue(bufferOrNull.array(), baseOffset, baseOffset + length);
        } else {/*from  w w  w.j a v  a2s  .  co m*/
            return new BytesValue(bufferOrNull.array());
        }
    } else {
        byte[] bytes = new byte[bufferOrNull.readableBytes()];
        bufferOrNull.getBytes(bufferOrNull.readerIndex(), bytes);
        return new BytesValue(bytes);
    }

}

From source file:io.grpc.alts.internal.BufUnwrapper.java

License:Apache License

/**
 * Called to get access to the underlying NIO buffers for a {@link ByteBuf} that will be used for
 * writing./*from   w w  w  . j a  v  a  2 s . c o  m*/
 */
ByteBuffer[] writableNioBuffers(ByteBuf buf) {
    // Set the writer index to the capacity to guarantee that the returned NIO buffers will have
    // the capacity available.
    int readerIndex = buf.readerIndex();
    int writerIndex = buf.writerIndex();
    buf.readerIndex(writerIndex);
    buf.writerIndex(buf.capacity());

    try {
        return nioBuffers(buf, singleWriteBuffer);
    } finally {
        // Restore the writer index before returning.
        buf.readerIndex(readerIndex);
        buf.writerIndex(writerIndex);
    }
}

From source file:io.grpc.alts.internal.BufUnwrapperTest.java

License:Apache License

@Test
public void writableNioBuffers_indexesPreserved() {
    ByteBuf buf = alloc.buffer(1);
    int ridx = buf.readerIndex();
    int widx = buf.writerIndex();
    int cap = buf.capacity();
    try (BufUnwrapper unwrapper = new BufUnwrapper()) {
        ByteBuffer[] internalBufs = unwrapper.writableNioBuffers(buf);
        Truth.assertThat(internalBufs).hasLength(1);

        internalBufs[0].put((byte) 'a');

        assertEquals(ridx, buf.readerIndex());
        assertEquals(widx, buf.writerIndex());
        assertEquals(cap, buf.capacity());
    } finally {/*from w  w  w  .  j  av a2s.c o m*/
        buf.release();
    }
}

From source file:io.horizondb.io.buffers.NettyBuffer.java

License:Apache License

/**
 * Creates a new <code>NettyBuffer</code> that wraps the specified <code>ByteBuf</code>.
 * /*w  w w . j av  a  2s .co  m*/
 * @param buffer the <code>ByteBuf</code>
 */
NettyBuffer(ByteBuf buffer) {

    notNull(buffer, "the buffer parameter must not be null.");

    this.buffer = buffer;

    subRegion(0, buffer.capacity());
    writerIndex(buffer.writerIndex());
}

From source file:io.moquette.parser.netty.PublishDecoderTest.java

License:Open Source License

private ByteBuf generatePublishQoS0(ByteBuf payload) throws IllegalAccessException {
    int size = payload.capacity();
    ByteBuf messageBody = Unpooled.buffer(size);
    messageBody.writeBytes(Utils.encodeString("/topic"));

    //ONLY for QoS > 1 Utils.writeWord(messageBody, messageID);
    messageBody.writeBytes(payload);//from  ww  w . j a  v  a 2 s. c o  m

    ByteBuf completeMsg = Unpooled.buffer(size);
    completeMsg.clear().writeByte(AbstractMessage.PUBLISH << 4 | 0x00) //set Qos to 0
            .writeBytes(Utils.encodeRemainingLength(messageBody.readableBytes()));
    completeMsg.writeBytes(messageBody);

    return completeMsg;
}

From source file:io.reactivex.netty.protocol.http.server.file.FileRequestHandlerTest.java

License:Apache License

@Test
public void shouldReturnFile() throws Exception {
    HttpServer<ByteBuf, ByteBuf> server = RxNetty.createHttpServer(0, new WebappFileRequestHandler()).start();

    final CountDownLatch finishLatch = new CountDownLatch(1);
    final AtomicReference<HttpResponseStatus> status = new AtomicReference<HttpResponseStatus>();
    final AtomicReference<String> contentType = new AtomicReference<String>();
    final AtomicReference<Integer> contentLength = new AtomicReference<Integer>();
    ByteBuf response = RxNetty.createHttpClient("localhost", server.getServerPort())
            .submit(HttpClientRequest.createGet("/sample.json"))
            .doOnNext(new Action1<HttpClientResponse<ByteBuf>>() {
                @Override/* w ww.ja va 2s .  c om*/
                public void call(HttpClientResponse<ByteBuf> response) {
                    status.set(response.getStatus());
                    contentType.set(response.getHeaders().getHeader(HttpHeaders.Names.CONTENT_TYPE));
                    contentLength
                            .set(Integer.parseInt(response.getHeaders().get(HttpHeaders.Names.CONTENT_LENGTH)));
                }
            }).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() {
                @Override
                public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> response) {
                    return response.getContent();
                }
            }).finallyDo(new Action0() {
                @Override
                public void call() {
                    finishLatch.countDown();
                }
            }).toBlocking().toFuture().get(10, TimeUnit.SECONDS);

    Assert.assertEquals("Request failed.", HttpResponseStatus.OK, status.get());
    Assert.assertEquals("Request failed.", "application/json", contentType.get());
    Assert.assertEquals("Invalid content length", (Integer) 17, contentLength.get());
    Assert.assertTrue("The returned observable did not finish.", finishLatch.await(1, TimeUnit.MINUTES));
    Assert.assertEquals("Unexpected actual number of bytes", 17, response.capacity());
}

From source file:io.vertx.proton.impl.ProtonWritableBufferImplTest.java

License:Apache License

@Test
public void testLimit() {
    ByteBuf buffer = Unpooled.buffer(1024);
    ProtonWritableBufferImpl writable = new ProtonWritableBufferImpl(buffer);

    assertEquals(buffer.capacity(), writable.limit());
}

From source file:ivorius.ivtoolkit.tools.IvNBTHelper.java

License:Apache License

public static long[] readNBTLongs(String id, NBTTagCompound compound) {
    if (compound.hasKey(id)) {
        ByteBuf bytes = Unpooled.copiedBuffer(compound.getByteArray(id));
        long[] longs = new long[bytes.capacity() / 8];
        for (int i = 0; i < longs.length; i++)
            longs[i] = bytes.readLong();
        return longs;
    }//from w  ww.j  a va 2s  .  c om

    return null;
}

From source file:mysql.client.Session_Old.java

public void doHandshake() throws Exception {

    ByteBuf buf = readPacket();
    byte protocolVersion = buf.readByte();
    String serverVersion = readString(buf, "ASCII");
    System.out.println("protocolVersion = " + protocolVersion);
    System.out.println("serverVersion = " + serverVersion);

    long threadId = buf.readUnsignedInt();
    System.out.println("threadId = " + threadId);
    String seed;//  ww w.  j a  v  a2  s.co m
    if (protocolVersion > 9) {//fuck ?mysql jdbc ?,,?mysql internal manualV10
        // read auth-plugin-data-part-1 (string[8])
        seed = readString(buf, "ASCII", 8);//????,ssl??
        // read filler ([00])
        buf.readByte();
        System.out.println("seed=" + seed);
    } else {
        // read scramble (string[NUL])
        seed = readString(buf, "ASCII");//v9 handshake?,?
    }

    //v10 ???

    int serverCapabilities = 0;
    // read capability flags (lower 2 bytes)
    if (buf.readerIndex() < buf.capacity()) {
        serverCapabilities = buf.readShort();
    }

    //??,???,??,????,?,?
    //?,???????,??

    //???,?debug,??
    int serverCharsetIndex = buf.readByte();
    int serverStatus = buf.readShort();
    serverCapabilities |= buf.readShort() << 16;//??,??

    int clientParam = 3842703;//??serverCapabilitiesconnection?
    //        clientParam |= 0x00200000;
    clientParam &= ~0x00100000; // ignore connection attributes
    //        if capabilities & CLIENT_PLUGIN_AUTH {
    //            1              length of auth-plugin-data
    //        } else {
    //            1              [00]
    //        }
    int authPluginDataLength = buf.readByte();//length of auth-plugin-data

    // next 10 bytes are reserved (all [00])
    //        buf.setPosition(buf.getPosition() + 10);
    buf.readerIndex(buf.readerIndex() + 10);//10??
    String seed2 = readString(buf, "ASCII", authPluginDataLength - 8);
    seed += seed2;
    System.out.println("seed =" + seed);

    //        if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
    //            proceedHandshakeWithPluggableAuthentication(user, password, database, buf);
    //            return;
    //        }
    //?????,filter-chain??
    //?MysqlOldPasswordPlugin,MysqlNativePasswordPlugin,MysqlClearPasswordPlugin...

    boolean skipPassword = false;
    int passwordLength = 16;
    int userLength = (user != null) ? user.length() : 0;
    int databaseLength = (database != null) ? database.length() : 0;

    int packLength = ((userLength + passwordLength + databaseLength) * 3) + 7 + 4 + 33;

    String pluginName = readString(buf, "ASCII");
    //initial handshake packet ?,??Handshake response packet

    ByteBuf fromServer = buf.alloc().buffer(seed.getBytes().length).writeBytes(seed.getBytes());

    byte[] bytes = Security.scramble411(password, seed, "utf-8");
    ByteBuf authBuf = buf.alloc().buffer(bytes.length).writeBytes(bytes);
    // write Auth Response Packet
    String enc = "utf-8";
    ByteBuf sendBuf = createSendByteBuf(packLength);
    sendBuf = sendBuf.order(ByteOrder.LITTLE_ENDIAN);
    //        last_sent.writeLong(this.clientParam);
    //        last_sent.writeLong(this.maxThreeBytes);
    //0x00100000

    //        "_runtime_version" -> "1.8.0_65"
    //        "_client_version" -> "5.1.38"
    //        "_client_name" -> "MySQL Connector Java"
    //        "_client_license" -> "GPL"
    //        "_runtime_vendor" -> "Oracle Corporation"
    sendBuf.writeInt(clientParam);
    sendBuf.writeInt(16777215);//writeLong(this.maxThreeBytes);
    sendBuf.writeByte(33);//CharsetMapping.MYSQL_COLLATION_INDEX_utf8;
    sendBuf.writeBytes(new byte[23]);

    //user  string<null>
    sendBuf.writeBytes(user.getBytes());
    sendBuf.writeByte(0);

    //wite toserver length
    sendBuf.writeByte(0);

    //write database
    sendBuf.writeBytes(database.getBytes());
    sendBuf.writeByte(0);

    sendBuf.writeBytes("mysql_native_password".getBytes());
    sendBuf.writeByte(0);

    //propertie
    ByteBuf propertieBuf = allocator.heapBuffer(100);
    Properties properties = new Properties();
    properties.setProperty("_runtime_version", "1.8.0_65");
    properties.setProperty("_client_version", "5.1.38");
    properties.setProperty("_client_name", "MySQL Connector Java");
    properties.setProperty("_client_license", "GPL");
    properties.setProperty("_runtime_vendor", "Oracle Corporation");
    Buffer lb = new Buffer(100);
    for (Object p : properties.keySet()) {
        lb.writeLenString((String) p);
        lb.writeLenString(properties.getProperty((String) p));
        //mysql buffer , ?int ,,?251,?65536
    }

    //        sendBuf.writeByte((byte) (lb.getPosition() - 4));
    //        sendBuf.writeBytes(lb.getByteBuffer(), 4, lb.getBufLength() - 4);

    send(sendBuf);
    //      sendBuf.writeBytes(authBuf); //?,fromServertoServer

    //jdbc driver????,,sql

}