Example usage for io.netty.buffer ByteBuf isDirect

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

Introduction

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

Prototype

public abstract boolean isDirect();

Source Link

Document

Returns true if and only if this buffer is backed by an NIO direct buffer.

Usage

From source file:io.jsync.datagram.impl.DatagramServerHandler.java

License:Open Source License

@Override
protected Object safeObject(Object msg, ByteBufAllocator allocator) throws Exception {
    if (msg instanceof DatagramPacket) {
        DatagramPacket packet = (DatagramPacket) msg;
        ByteBuf content = packet.content();
        if (content.isDirect()) {
            content = safeBuffer(content, allocator);
        }/*from   w ww  .j av a  2 s.c  o m*/
        return new DefaultDatagramPacket(packet.sender(), new Buffer(content));
    }
    return msg;
}

From source file:io.jsync.http.impl.AsyncHttpHandler.java

License:Open Source License

@Override
protected Object safeObject(Object msg, ByteBufAllocator allocator) throws Exception {
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        ByteBuf buf = content.content();
        if (buf != Unpooled.EMPTY_BUFFER && buf.isDirect()) {
            ByteBuf newBuf = safeBuffer(content, allocator);
            if (msg instanceof LastHttpContent) {
                LastHttpContent last = (LastHttpContent) msg;
                return new AssembledLastHttpContent(newBuf, last.trailingHeaders(), last.decoderResult());
            } else {
                return new DefaultHttpContent(newBuf);
            }//ww  w  .  j  av  a2 s.  com
        }
    } else if (msg instanceof WebSocketFrame) {
        ByteBuf payload = safeBuffer((WebSocketFrame) msg, allocator);
        boolean isFinal = ((WebSocketFrame) msg).isFinalFragment();
        FrameType frameType;
        if (msg instanceof BinaryWebSocketFrame) {
            frameType = BINARY;
        } else if (msg instanceof CloseWebSocketFrame) {
            frameType = CLOSE;
        } else if (msg instanceof PingWebSocketFrame) {
            frameType = PING;
        } else if (msg instanceof PongWebSocketFrame) {
            frameType = PONG;
        } else if (msg instanceof TextWebSocketFrame) {
            frameType = TEXT;
        } else if (msg instanceof ContinuationWebSocketFrame) {
            frameType = CONTINUATION;
        } else {
            throw new IllegalStateException("Unsupported websocket msg " + msg);
        }
        return new DefaultWebSocketFrame(frameType, payload, isFinal);
    }
    return msg;
}

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

License:Open Source License

@Test
public void testDirect() {
    Buffer buff = Buffer.factory.directBuffer("hello world".getBytes());
    assertEquals("hello world", buff.toString());
    buff.appendString(" foobar");
    assertEquals("hello world foobar", buff.toString());
    ByteBuf bb = buff.getByteBuf().unwrap();
    assertTrue(bb.isDirect());
    assertTrue(bb.release());//from ww w  .j  a v  a  2 s  .  co  m
    try {
        // Check it's deallocated
        buff.toString();
        fail();
    } catch (IllegalReferenceCountException e) {
    }
}

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

License:Open Source License

/**
 * Return a buffer from HTTP/2 codec that Vert.x can use:
 *
 * - if it's a direct buffer (coming likely from OpenSSL) : we get a heap buffer version
 * - if it's a composite buffer we do the same
 * - otherwise we increase the ref count
 *//*from   w w w.  ja v  a 2s.com*/
static ByteBuf safeBuffer(ByteBuf buf, ByteBufAllocator allocator) {
    if (buf == Unpooled.EMPTY_BUFFER) {
        return buf;
    }
    if (buf.isDirect() || buf instanceof CompositeByteBuf) {
        if (buf.isReadable()) {
            ByteBuf buffer = allocator.heapBuffer(buf.readableBytes());
            buffer.writeBytes(buf);
            return buffer;
        } else {
            return Unpooled.EMPTY_BUFFER;
        }
    }
    return buf.retain();
}

From source file:io.vertx.core.net.impl.VertxHandler.java

License:Open Source License

public static ByteBuf safeBuffer(ByteBuf buf, ByteBufAllocator allocator) {
    if (buf == Unpooled.EMPTY_BUFFER) {
        return buf;
    }/*from ww  w . j  a  va2 s  .  c o m*/
    if (buf.isDirect() || buf instanceof CompositeByteBuf) {
        try {
            if (buf.isReadable()) {
                ByteBuf buffer = allocator.heapBuffer(buf.readableBytes());
                buffer.writeBytes(buf);
                return buffer;
            } else {
                return Unpooled.EMPTY_BUFFER;
            }
        } finally {
            buf.release();
        }
    }
    return buf;
}

From source file:io.vertx.core.net.NetTest.java

License:Open Source License

private void testNetClientInternal_(HttpServerOptions options, boolean expectSSL) throws Exception {
    waitFor(2);// w w w.  jav a2  s.c o  m
    HttpServer server = vertx.createHttpServer(options);
    server.requestHandler(req -> {
        req.response().end("Hello World");
    });
    CountDownLatch latch = new CountDownLatch(1);
    server.listen(onSuccess(v -> {
        latch.countDown();
    }));
    awaitLatch(latch);
    client.connect(1234, "localhost", onSuccess(so -> {
        NetSocketInternal soInt = (NetSocketInternal) so;
        assertEquals(expectSSL, soInt.isSsl());
        ChannelHandlerContext chctx = soInt.channelHandlerContext();
        ChannelPipeline pipeline = chctx.pipeline();
        pipeline.addBefore("handler", "http", new HttpClientCodec());
        AtomicInteger status = new AtomicInteger();
        soInt.handler(buff -> fail());
        soInt.messageHandler(obj -> {
            switch (status.getAndIncrement()) {
            case 0:
                assertTrue(obj instanceof HttpResponse);
                HttpResponse resp = (HttpResponse) obj;
                assertEquals(200, resp.status().code());
                break;
            case 1:
                assertTrue(obj instanceof LastHttpContent);
                ByteBuf content = ((LastHttpContent) obj).content();
                assertEquals(!expectSSL, content.isDirect());
                assertEquals(1, content.refCnt());
                String val = content.toString(StandardCharsets.UTF_8);
                assertTrue(content.release());
                assertEquals("Hello World", val);
                complete();
                break;
            default:
                fail();
            }
        });
        soInt.writeMessage(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/somepath"),
                onSuccess(v -> complete()));
    }));
    await();
}

From source file:io.vertx.core.net.NetTest.java

License:Open Source License

@Test
public void testNetSocketInternalBuffer() throws Exception {
    server.connectHandler(so -> {//from  ww  w  .ja va  2s .com
        NetSocketInternal soi = (NetSocketInternal) so;
        soi.messageHandler(msg -> fail("Unexpected"));
        soi.handler(msg -> {
            ByteBuf byteBuf = msg.getByteBuf();
            assertFalse(byteBuf.isDirect());
            assertEquals(1, byteBuf.refCnt());
            assertFalse(byteBuf.release());
            assertEquals(1, byteBuf.refCnt());
            soi.write(msg);
        });
    });
    startServer();
    client.connect(testAddress, onSuccess(so -> {
        NetSocketInternal soi = (NetSocketInternal) so;
        soi.write(Buffer.buffer("Hello World"));
        soi.messageHandler(msg -> fail("Unexpected"));
        soi.handler(msg -> {
            ByteBuf byteBuf = msg.getByteBuf();
            assertFalse(byteBuf.isDirect());
            assertEquals(1, byteBuf.refCnt());
            assertFalse(byteBuf.release());
            assertEquals(1, byteBuf.refCnt());
            assertEquals("Hello World", msg.toString());
            testComplete();
        });
    }));
    await();
}

From source file:org.apache.tajo.tuple.memory.TestHeapTuple.java

License:Apache License

@Test
public void testHeapTupleFromHeap() throws CloneNotSupportedException {
    MemoryRowBlock rowBlock = TestMemoryRowBlock.createRowBlock(1024);
    int length = rowBlock.getMemory().writerPosition();
    //write rows to heap
    ByteBuf heapBuffer = BufferPool.heapBuffer(length, length);
    heapBuffer.writeBytes(rowBlock.getMemory().getBuffer());
    assertFalse(heapBuffer.isDirect());

    ResizableMemoryBlock memoryBlock = new ResizableMemoryBlock(heapBuffer);
    assertFalse(memoryBlock.hasAddress());

    RowBlockReader reader = new HeapRowBlockReader(memoryBlock, rowBlock.getDataTypes(), rowBlock.rows());
    assertEquals(HeapRowBlockReader.class, reader.getClass());
    HeapTuple heapTuple = new HeapTuple();
    int i = 0;/*from w  w w .  ja va  2s  .c  o  m*/
    while (reader.next(heapTuple)) {

        TestMemoryRowBlock.validateTupleResult(i, heapTuple);
        TestMemoryRowBlock.validateTupleResult(i, heapTuple.clone());
        i++;
    }
    assertEquals(rowBlock.rows(), i);
    rowBlock.release();
    memoryBlock.release();
}

From source file:org.asynchttpclient.netty.util.Utf8ByteBufCharsetDecoder.java

License:Open Source License

public String decode(ByteBuf buf) throws CharacterCodingException {
    if (buf.isDirect()) {
        return buf.toString(UTF_8);
    }/*from www .ja  va2  s. co m*/

    int length = buf.readableBytes();
    ensureCapacity(length);

    if (buf.nioBufferCount() == 1) {
        decodeSingleNioBuffer(buf.internalNioBuffer(buf.readerIndex(), length).duplicate(), length);
    } else {
        decode(buf.nioBuffers(), buf.readableBytes());
    }

    return charBuffer.flip().toString();
}

From source file:org.asynchttpclient.netty.util.Utf8ByteBufCharsetDecoder.java

License:Open Source License

public String decode(ByteBuf... bufs) throws CharacterCodingException {
    if (bufs.length == 1) {
        return decode(bufs[0]);
    }//from  w ww  .  j ava  2 s  . co m

    int totalSize = 0;
    int totalNioBuffers = 0;
    boolean direct = false;
    for (ByteBuf buf : bufs) {
        if (buf.isDirect()) {
            direct = true;
            break;
        }
        totalSize += buf.readableBytes();
        totalNioBuffers += buf.nioBufferCount();
    }

    if (direct) {
        ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(bufs);
        try {
            return wrappedBuffer.toString(UTF_8);
        } finally {
            wrappedBuffer.release();
        }

    } else {
        ByteBuffer[] nioBuffers = new ByteBuffer[totalNioBuffers];
        int i = 0;
        for (ByteBuf buf : bufs) {
            for (ByteBuffer nioBuffer : buf.nioBuffers()) {
                nioBuffers[i++] = nioBuffer;
            }
        }

        ensureCapacity(totalSize);
        decode(nioBuffers, totalSize);

        return charBuffer.flip().toString();
    }
}