Example usage for io.netty.buffer Unpooled EMPTY_BUFFER

List of usage examples for io.netty.buffer Unpooled EMPTY_BUFFER

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled EMPTY_BUFFER.

Prototype

ByteBuf EMPTY_BUFFER

To view the source code for io.netty.buffer Unpooled EMPTY_BUFFER.

Click Source Link

Document

A buffer whose capacity is 0 .

Usage

From source file:io.vertx.core.http.Http2ServerTest.java

License:Open Source License

private void testStreamPauseResume(Function<HttpServerRequest, ReadStream<Buffer>> streamProvider)
        throws Exception {
    Buffer expected = Buffer.buffer();
    String chunk = TestUtils.randomAlphaString(1000);
    AtomicBoolean done = new AtomicBoolean();
    AtomicBoolean paused = new AtomicBoolean();
    Buffer received = Buffer.buffer();
    server.requestHandler(req -> {/* w w w .ja  va 2 s .c  o  m*/
        ReadStream<Buffer> stream = streamProvider.apply(req);
        vertx.setPeriodic(1, timerID -> {
            if (paused.get()) {
                vertx.cancelTimer(timerID);
                done.set(true);
                // Let some time to accumulate some more buffers
                vertx.setTimer(100, id -> {
                    stream.resume();
                });
            }
        });
        stream.handler(received::appendBuffer);
        stream.endHandler(v -> {
            assertEquals(expected, received);
            testComplete();
        });
        stream.pause();
    });
    startServer();

    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, POST("/form").set("content-type", "text/plain"), 0,
                false, request.context.newPromise());
        request.context.flush();
        Http2Stream stream = request.connection.stream(id);
        class Anonymous {
            void send() {
                boolean writable = request.encoder.flowController().isWritable(stream);
                if (writable) {
                    Buffer buf = Buffer.buffer(chunk);
                    expected.appendBuffer(buf);
                    request.encoder.writeData(request.context, id, buf.getByteBuf(), 0, false,
                            request.context.newPromise());
                    request.context.flush();
                    request.context.executor().execute(this::send);
                } else {
                    request.encoder.writeData(request.context, id, Unpooled.EMPTY_BUFFER, 0, true,
                            request.context.newPromise());
                    request.context.flush();
                    paused.set(true);
                }
            }
        }
        new Anonymous().send();
    });
    fut.sync();
    await();
}

From source file:io.vertx.core.http.Http2ServerTest.java

License:Open Source License

@Test
public void testClientSendGoAwayNoError() throws Exception {
    Future<Void> abc = Future.future();
    Context ctx = vertx.getOrCreateContext();
    Handler<HttpServerRequest> requestHandler = req -> {
        HttpConnection conn = req.connection();
        AtomicInteger numShutdown = new AtomicInteger();
        AtomicBoolean completed = new AtomicBoolean();
        conn.shutdownHandler(v -> {/*from www .j  ava  2s .com*/
            assertOnIOContext(ctx);
            numShutdown.getAndIncrement();
            vertx.setTimer(100, timerID -> {
                // Delay so we can check the connection is not closed
                completed.set(true);
                testComplete();
            });
        });
        conn.goAwayHandler(ga -> {
            assertOnIOContext(ctx);
            assertEquals(0, numShutdown.get());
            req.response().end();
        });
        conn.closeHandler(v -> {
            assertTrue(completed.get());
        });
        abc.complete();
    };
    server.requestHandler(requestHandler);
    startServer(ctx);
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        Http2ConnectionEncoder encoder = request.encoder;
        int id = request.nextStreamId();
        encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
        abc.setHandler(ar -> {
            encoder.writeGoAway(request.context, id, 0, Unpooled.EMPTY_BUFFER, request.context.newPromise());
            request.context.flush();
        });
    });
    fut.sync();
    await();
}

From source file:io.vertx.core.http.Http2ServerTest.java

License:Open Source License

@Test
public void testClientSendGoAwayInternalError() throws Exception {
    Future<Void> abc = Future.future();
    Context ctx = vertx.getOrCreateContext();
    Handler<HttpServerRequest> requestHandler = req -> {
        HttpConnection conn = req.connection();
        AtomicInteger status = new AtomicInteger();
        conn.goAwayHandler(ga -> {//from w  ww .ja  v  a 2 s .co m
            assertOnIOContext(ctx);
            assertEquals(0, status.getAndIncrement());
            req.response().end();
        });
        conn.shutdownHandler(v -> {
            assertOnIOContext(ctx);
            assertEquals(1, status.getAndIncrement());
        });
        conn.closeHandler(v -> {
            assertEquals(2, status.getAndIncrement());
            testComplete();
        });
        abc.complete();
    };
    server.requestHandler(requestHandler);
    startServer(ctx);
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        Http2ConnectionEncoder encoder = request.encoder;
        int id = request.nextStreamId();
        encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
        abc.setHandler(ar -> {
            encoder.writeGoAway(request.context, id, 3, Unpooled.EMPTY_BUFFER, request.context.newPromise());
            request.context.flush();
        });
    });
    fut.sync();
    await();
}

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

License:Open Source License

WebSocketFrame encodeFrame(WebSocketFrameImpl frame) {
    ByteBuf buf = frame.getBinaryData();
    if (buf != Unpooled.EMPTY_BUFFER) {
        buf = safeBuffer(buf, chctx.alloc());
    }//from   w w w. j a v a  2 s  . c  om
    switch (frame.type()) {
    case BINARY:
        return new BinaryWebSocketFrame(frame.isFinal(), 0, buf);
    case TEXT:
        return new TextWebSocketFrame(frame.isFinal(), 0, buf);
    case CLOSE:
        return new CloseWebSocketFrame(true, 0, buf);
    case CONTINUATION:
        return new ContinuationWebSocketFrame(frame.isFinal(), 0, buf);
    case PONG:
        return new PongWebSocketFrame(buf);
    case PING:
        return new PingWebSocketFrame(buf);
    default:
        throw new IllegalStateException("Unsupported websocket msg " + frame);
    }
}

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  . j a va  2  s .  c o m*/
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.http.impl.Http2ConnectionBase.java

License:Open Source License

@Override
public synchronized HttpConnection goAway(long errorCode, int lastStreamId, Buffer debugData) {
    if (errorCode < 0) {
        throw new IllegalArgumentException();
    }/*from w ww.  j  a v a 2 s .  c  o  m*/
    if (lastStreamId < 0) {
        throw new IllegalArgumentException();
    }
    handler.writeGoAway(errorCode, lastStreamId,
            debugData != null ? debugData.getByteBuf() : Unpooled.EMPTY_BUFFER);
    return this;
}

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

License:Open Source License

void write(ByteBuf chunk, boolean end) {
    synchronized (conn) {
        checkEnded();/*from w  w  w  .j  ava2  s  . co m*/
        if (end) {
            handleEnded(false);
        }
        boolean hasBody = chunk != null;
        boolean sent = checkSendHeaders(end && !hasBody && trailers == null);
        if (hasBody || (!sent && end)) {
            if (chunk == null) {
                chunk = Unpooled.EMPTY_BUFFER;
            }
            int len = chunk.readableBytes();
            stream.writeData(chunk, end && trailers == null);
            bytesWritten += len;
        }
        if (end && trailers != null) {
            stream.writeHeaders(trailers, true);
        }
        if (end && bodyEndHandler != null) {
            bodyEndHandler.handle(null);
        }
    }
}

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

License:Open Source License

@Override
public void end() {
    synchronized (conn) {
        writeData(Unpooled.EMPTY_BUFFER, true);
    }
}

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  www. jav a  2  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.test.core.EventLoopGroupTest.java

License:Open Source License

@Test
public void testNettyServerUsesContextEventLoop() throws Exception {
    ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
    AtomicReference<Thread> contextThread = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    context.runOnContext(v -> {//from ww  w .  ja  v a  2 s .  c om
        contextThread.set(Thread.currentThread());
        latch.countDown();
    });
    awaitLatch(latch);
    ServerBootstrap bs = new ServerBootstrap();
    bs.group(context.nettyEventLoop());
    bs.channel(NioServerSocketChannel.class);
    bs.option(ChannelOption.SO_BACKLOG, 100);
    bs.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            assertSame(contextThread.get(), Thread.currentThread());
            context.executeFromIO(() -> {
                assertSame(contextThread.get(), Thread.currentThread());
                assertSame(context, Vertx.currentContext());
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf buf = (ByteBuf) msg;
                        assertEquals("hello", buf.toString(StandardCharsets.UTF_8));
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        });
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            testComplete();
                        });
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        fail(cause.getMessage());
                    }
                });
            });
        }
    });
    bs.bind("localhost", 1234).sync();
    vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> {
        assertTrue(ar.succeeded());
        NetSocket so = ar.result();
        so.write(Buffer.buffer("hello"));
    });
    await();
}