Example usage for io.netty.buffer ByteBuf alloc

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

Introduction

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

Prototype

public abstract ByteBufAllocator alloc();

Source Link

Document

Returns the ByteBufAllocator which created this buffer.

Usage

From source file:io.jsync.dns.impl.netty.DnsResponse.java

License:Open Source License

@Override
public DnsResponse replace(ByteBuf content) {
    return DnsResponseDecoder.decodeResponse(content, content.alloc());
}

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;//www  .j av a 2 s. com
    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

}

From source file:org.apache.bookkeeper.common.allocator.impl.ByteBufAllocatorBuilderTest.java

License:Apache License

@Test
public void testOomWithFallback() {
    ByteBufAllocator baseAlloc = mock(ByteBufAllocator.class);
    when(baseAlloc.directBuffer(anyInt(), anyInt())).thenThrow(outOfDirectMemException);

    AtomicReference<OutOfMemoryError> receivedException = new AtomicReference<>();

    ByteBufAllocator alloc = ByteBufAllocatorBuilder.create().pooledAllocator(baseAlloc)
            .unpooledAllocator(UnpooledByteBufAllocator.DEFAULT)
            .outOfMemoryPolicy(OutOfMemoryPolicy.FallbackToHeap).outOfMemoryListener((e) -> {
                receivedException.set(e);
            }).build();//from  w w  w.  ja  v  a 2 s.  com

    // Should not throw exception
    ByteBuf buf = alloc.buffer();
    assertEquals(UnpooledByteBufAllocator.DEFAULT, buf.alloc());

    // No notification should have been triggered
    assertEquals(null, receivedException.get());
}

From source file:org.apache.bookkeeper.common.allocator.impl.ByteBufAllocatorBuilderTest.java

License:Apache License

@Test
public void testUnpooled() {
    ByteBufAllocator alloc = ByteBufAllocatorBuilder.create().poolingPolicy(PoolingPolicy.UnpooledHeap).build();

    ByteBuf buf = alloc.buffer();
    assertEquals(UnpooledByteBufAllocator.DEFAULT, buf.alloc());
    assertTrue(buf.hasArray());/*w  ww  .  j  a v a 2  s . c  o  m*/

    ByteBuf buf2 = alloc.directBuffer();
    assertEquals(UnpooledByteBufAllocator.DEFAULT, buf2.alloc());
    assertFalse(buf2.hasArray());
}

From source file:org.apache.bookkeeper.common.allocator.impl.ByteBufAllocatorBuilderTest.java

License:Apache License

@Test
public void testPooled() {
    PooledByteBufAllocator pooledAlloc = new PooledByteBufAllocator(true);

    ByteBufAllocator alloc = ByteBufAllocatorBuilder.create().poolingPolicy(PoolingPolicy.PooledDirect)
            .pooledAllocator(pooledAlloc).build();

    assertTrue(alloc.isDirectBufferPooled());

    ByteBuf buf1 = alloc.buffer();
    assertEquals(pooledAlloc, buf1.alloc());
    assertFalse(buf1.hasArray());//from   www.  j a v  a  2 s.  c om
    buf1.release();

    ByteBuf buf2 = alloc.directBuffer();
    assertEquals(pooledAlloc, buf2.alloc());
    assertFalse(buf2.hasArray());
    buf2.release();

    ByteBuf buf3 = alloc.heapBuffer();
    assertEquals(pooledAlloc, buf3.alloc());
    assertTrue(buf3.hasArray());
    buf3.release();
}

From source file:org.apache.bookkeeper.common.allocator.impl.ByteBufAllocatorBuilderTest.java

License:Apache License

@Test
public void testPooledWithDefaultAllocator() {
    ByteBufAllocator alloc = ByteBufAllocatorBuilder.create().poolingPolicy(PoolingPolicy.PooledDirect)
            .poolingConcurrency(3).build();

    assertTrue(alloc.isDirectBufferPooled());

    ByteBuf buf1 = alloc.buffer();
    assertEquals(PooledByteBufAllocator.class, buf1.alloc().getClass());
    assertEquals(3, ((PooledByteBufAllocator) buf1.alloc()).metric().numDirectArenas());
    assertFalse(buf1.hasArray());//from w  w  w . j ava 2 s .c  o m
    buf1.release();

    ByteBuf buf2 = alloc.directBuffer();
    assertFalse(buf2.hasArray());
    buf2.release();

    ByteBuf buf3 = alloc.heapBuffer();
    assertTrue(buf3.hasArray());
    buf3.release();
}

From source file:org.apache.drill.exec.rpc.RpcEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, OutboundRpcMessage msg, List<Object> out) throws Exception {
    if (RpcConstants.EXTRA_DEBUGGING) {
        logger.debug("Rpc Encoder called with msg {}", msg);
    }//w w  w.  j a  va2  s . c o m

    if (!ctx.channel().isOpen()) {
        //output.add(ctx.alloc().buffer(0));
        logger.debug("Channel closed, skipping encode.");
        msg.release();
        return;
    }

    try {
        if (RpcConstants.EXTRA_DEBUGGING) {
            logger.debug("Encoding outbound message {}", msg);
        }
        // first we build the RpcHeader
        RpcHeader header = RpcHeader.newBuilder() //
                .setMode(msg.mode) //
                .setCoordinationId(msg.coordinationId) //
                .setRpcType(msg.rpcType).build();

        // figure out the full length
        int headerLength = header.getSerializedSize();
        int protoBodyLength = msg.pBody.getSerializedSize();
        int rawBodyLength = msg.getRawBodySize();
        int fullLength = //
                HEADER_TAG_LENGTH + getRawVarintSize(headerLength) + headerLength + //
                        PROTOBUF_BODY_TAG_LENGTH + getRawVarintSize(protoBodyLength) + protoBodyLength; //

        if (rawBodyLength > 0) {
            fullLength += (RAW_BODY_TAG_LENGTH + getRawVarintSize(rawBodyLength) + rawBodyLength);
        }

        ByteBuf buf = ctx.alloc().buffer();
        OutputStream os = new ByteBufOutputStream(buf);
        CodedOutputStream cos = CodedOutputStream.newInstance(os);

        // write full length first (this is length delimited stream).
        cos.writeRawVarint32(fullLength);

        // write header
        cos.writeRawVarint32(HEADER_TAG);
        cos.writeRawVarint32(headerLength);
        header.writeTo(cos);

        // write protobuf body length and body
        cos.writeRawVarint32(PROTOBUF_BODY_TAG);
        cos.writeRawVarint32(protoBodyLength);
        msg.pBody.writeTo(cos);

        // if exists, write data body and tag.
        if (msg.getRawBodySize() > 0) {
            if (RpcConstants.EXTRA_DEBUGGING) {
                logger.debug("Writing raw body of size {}", msg.getRawBodySize());
            }

            cos.writeRawVarint32(RAW_BODY_TAG);
            cos.writeRawVarint32(rawBodyLength);
            cos.flush(); // need to flush so that dbody goes after if cos is caching.

            CompositeByteBuf cbb = new CompositeByteBuf(buf.alloc(), true, msg.dBodies.length + 1);
            cbb.addComponent(buf);
            int bufLength = buf.readableBytes();
            for (ByteBuf b : msg.dBodies) {
                cbb.addComponent(b);
                bufLength += b.readableBytes();
            }
            cbb.writerIndex(bufLength);
            out.add(cbb);
        } else {
            cos.flush();
            out.add(buf);
        }

        if (RpcConstants.SOME_DEBUGGING) {
            logger.debug("Wrote message length {}:{} bytes (head:body).  Message: " + msg,
                    getRawVarintSize(fullLength), fullLength);
        }
        if (RpcConstants.EXTRA_DEBUGGING) {
            logger.debug("Sent message.  Ending writer index was {}.", buf.writerIndex());
        }
    } finally {
        // make sure to release Rpc Messages underlying byte buffers.
        //msg.release();
    }
}

From source file:org.clitherproject.clither.server.net.packet.Packet.java

License:Open Source License

@SuppressWarnings("deprecation")
public static String readUTF16(ByteBuf in) {
    in = in.order(ByteOrder.BIG_ENDIAN);
    ByteBuf buffer = in.alloc().buffer();
    char chr;//from w w  w  . ja  v  a 2 s  .co  m
    while (in.readableBytes() > 1 && (chr = in.readChar()) != 0) {
        buffer.writeChar(chr);
    }

    return buffer.toString(Charsets.UTF_16LE);
}

From source file:org.dcache.xrootd.protocol.messages.WriteRequest.java

License:Open Source License

public WriteRequest(ByteBuf buffer) {
    super(buffer, kXR_write);

    fhandle = buffer.getInt(4);/*from   w w w. j  av  a 2 s  .  c om*/
    offset = buffer.getLong(8);
    dlen = buffer.getInt(20);
    data = buffer.alloc().ioBuffer(dlen); // Most likely this will be written to disk
    buffer.getBytes(24, data);
}

From source file:org.dcache.xrootd.tpc.protocol.messages.InboundReadResponse.java

License:Open Source License

public InboundReadResponse(ByteBuf buffer) {
    super(buffer);
    dlen = buffer.getInt(4);
    data = buffer.alloc().ioBuffer(dlen);
    buffer.getBytes(8, data);
}