Search in sources :

Example 11 with ByteBuf

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf in project vert.x by eclipse.

the class Http2ServerTest method testQueuePushPromise.

@Test
public void testQueuePushPromise() throws Exception {
    Context ctx = vertx.getOrCreateContext();
    int numPushes = 10;
    Set<String> pushSent = new HashSet<>();
    server.requestHandler(req -> {
        req.response().setChunked(true).write("abc");
        for (int i = 0; i < numPushes; i++) {
            int val = i;
            String path = "/wibble" + val;
            req.response().push(HttpMethod.GET, path, ar -> {
                assertTrue(ar.succeeded());
                assertSame(ctx, Vertx.currentContext());
                pushSent.add(path);
                vertx.setTimer(10, id -> {
                    ar.result().end("wibble-" + val);
                });
            });
        }
    });
    startServer(ctx);
    TestClient client = new TestClient();
    client.settings.maxConcurrentStreams(3);
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        Http2ConnectionEncoder encoder = request.encoder;
        encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.decoder.frameListener(new Http2FrameAdapter() {

            int count = numPushes;

            Set<String> pushReceived = new HashSet<>();

            @Override
            public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId, Http2Headers headers, int padding) throws Http2Exception {
                pushReceived.add(headers.path().toString());
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
                if (count-- == 0) {
                    vertx.runOnContext(v -> {
                        assertEquals(numPushes, pushSent.size());
                        assertEquals(pushReceived, pushSent);
                        testComplete();
                    });
                }
                return super.onDataRead(ctx, streamId, data, padding, endOfStream);
            }
        });
    });
    fut.sync();
    await();
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelFuture(io.netty.channel.ChannelFuture) Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) HttpServer(io.vertx.core.http.HttpServer) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Context(io.vertx.core.Context) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ReadStream(io.vertx.core.streams.ReadStream) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) StreamResetException(io.vertx.core.http.StreamResetException) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) IOException(java.io.IOException) SSLHelper(io.vertx.core.net.impl.SSLHelper) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Bootstrap(io.netty.bootstrap.Bootstrap) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2Connection(io.netty.handler.codec.http2.Http2Connection) HttpMethod(io.vertx.core.http.HttpMethod) HttpUtils(io.vertx.core.http.impl.HttpUtils) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 12 with ByteBuf

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf in project vert.x by eclipse.

the class Http2ServerTest method testUnknownFrame.

@Test
public void testUnknownFrame() throws Exception {
    Buffer expectedSend = TestUtils.randomBuffer(500);
    Buffer expectedRecv = TestUtils.randomBuffer(500);
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {
        req.customFrameHandler(frame -> {
            assertOnIOContext(ctx);
            assertEquals(10, frame.type());
            assertEquals(253, frame.flags());
            assertEquals(expectedSend, frame.payload());
            req.response().writeCustomFrame(12, 134, expectedRecv).end();
        });
    });
    startServer(ctx);
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.decoder.frameListener(new Http2EventAdapter() {

            int status = 0;

            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
                int s = status++;
                vertx.runOnContext(v -> {
                    assertEquals(0, s);
                });
            }

            @Override
            public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags, ByteBuf payload) {
                int s = status++;
                Buffer recv = Buffer.buffer(payload.copy());
                vertx.runOnContext(v -> {
                    assertEquals(1, s);
                    assertEquals(12, frameType);
                    assertEquals(134, flags.value());
                    assertEquals(expectedRecv, recv);
                });
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
                int len = data.readableBytes();
                int s = status++;
                vertx.runOnContext(v -> {
                    assertEquals(2, s);
                    assertEquals(0, len);
                    assertTrue(endOfStream);
                    testComplete();
                });
                return data.readableBytes() + padding;
            }
        });
        request.encoder.writeHeaders(request.context, id, GET("/"), 0, false, request.context.newPromise());
        request.encoder.writeFrame(request.context, (byte) 10, id, new Http2Flags((short) 253), expectedSend.getByteBuf(), request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelFuture(io.netty.channel.ChannelFuture) Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) HttpServer(io.vertx.core.http.HttpServer) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Context(io.vertx.core.Context) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ReadStream(io.vertx.core.streams.ReadStream) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) StreamResetException(io.vertx.core.http.StreamResetException) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) IOException(java.io.IOException) SSLHelper(io.vertx.core.net.impl.SSLHelper) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Bootstrap(io.netty.bootstrap.Bootstrap) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2Connection(io.netty.handler.codec.http2.Http2Connection) HttpMethod(io.vertx.core.http.HttpMethod) HttpUtils(io.vertx.core.http.impl.HttpUtils) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) Test(org.junit.Test)

Example 13 with ByteBuf

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf in project vert.x by eclipse.

the class ClientConnection method createNetSocket.

public NetSocket createNetSocket() {
    // connection was upgraded to raw TCP socket
    NetSocketImpl socket = new NetSocketImpl(vertx, channel, context, client.getSslHelper(), metrics);
    socket.metric(metric());
    Map<Channel, NetSocketImpl> connectionMap = new HashMap<>(1);
    connectionMap.put(channel, socket);
    // Flush out all pending data
    endReadAndFlush();
    // remove old http handlers and replace the old handler with one that handle plain sockets
    ChannelPipeline pipeline = channel.pipeline();
    ChannelHandler inflater = pipeline.get(HttpContentDecompressor.class);
    if (inflater != null) {
        pipeline.remove(inflater);
    }
    pipeline.remove("codec");
    pipeline.replace("handler", "handler", new VertxNetHandler<NetSocketImpl>(channel, socket, connectionMap) {

        @Override
        public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception {
            // remove from the real mapping
            pool.removeChannel(channel);
            super.exceptionCaught(chctx, t);
        }

        @Override
        public void channelInactive(ChannelHandlerContext chctx) throws Exception {
            // remove from the real mapping
            pool.removeChannel(channel);
            super.channelInactive(chctx);
        }

        @Override
        public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
            if (msg instanceof HttpContent) {
                if (msg instanceof LastHttpContent) {
                    handleResponseEnd((LastHttpContent) msg);
                }
                ReferenceCountUtil.release(msg);
                return;
            }
            super.channelRead(chctx, msg);
        }

        @Override
        protected void handleMsgReceived(Object msg) {
            ByteBuf buf = (ByteBuf) msg;
            conn.handleDataReceived(Buffer.buffer(buf));
        }
    });
    return socket;
}
Also used : HashMap(java.util.HashMap) ByteBuf(io.netty.buffer.ByteBuf) VertxException(io.vertx.core.VertxException) NetSocketImpl(io.vertx.core.net.impl.NetSocketImpl)

Example 14 with ByteBuf

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf in project vert.x by eclipse.

the class DatagramServerHandler method safeObject.

@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);
        }
        return new DatagramPacketImpl(packet.sender(), Buffer.buffer(content));
    }
    return msg;
}
Also used : DatagramPacket(io.netty.channel.socket.DatagramPacket) ByteBuf(io.netty.buffer.ByteBuf)

Example 15 with ByteBuf

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf in project vert.x by eclipse.

the class EventLoopGroupTest method testNettyServerUsesContextEventLoop.

@Test
public void testNettyServerUsesContextEventLoop() throws Exception {
    ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
    AtomicReference<Thread> contextThread = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    context.runOnContext(v -> {
        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();
}
Also used : NetSocket(io.vertx.core.net.NetSocket) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NetClientOptions(io.vertx.core.net.NetClientOptions) ContextInternal(io.vertx.core.impl.ContextInternal) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Aggregations

ByteBuf (io.netty.buffer.ByteBuf)5135 Test (org.junit.Test)1813 Test (org.junit.jupiter.api.Test)717 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)392 ArrayList (java.util.ArrayList)312 IOException (java.io.IOException)309 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)209 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)183 ByteBuffer (java.nio.ByteBuffer)174 InetSocketAddress (java.net.InetSocketAddress)156 List (java.util.List)146 ByteBuf (org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf)144 Channel (io.netty.channel.Channel)141 Test (org.testng.annotations.Test)140 ChannelFuture (io.netty.channel.ChannelFuture)132 Map (java.util.Map)118 CountDownLatch (java.util.concurrent.CountDownLatch)108 MatchEntryBuilder (org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntryBuilder)107 Position (org.traccar.model.Position)105 DeviceSession (org.traccar.DeviceSession)100