Search in sources :

Example 1 with VertxHandler

use of io.vertx.core.net.impl.VertxHandler in project vert.x by eclipse.

the class Http1xServerConnection method netSocket.

void netSocket(Promise<NetSocket> promise) {
    context.execute(() -> {
        // Flush out all pending data
        flush();
        // remove old http handlers and replace the old handler with one that handle plain sockets
        ChannelPipeline pipeline = chctx.pipeline();
        ChannelHandler compressor = pipeline.get(HttpChunkContentCompressor.class);
        if (compressor != null) {
            pipeline.remove(compressor);
        }
        pipeline.remove("httpDecoder");
        if (pipeline.get("chunkedWriter") != null) {
            pipeline.remove("chunkedWriter");
        }
        pipeline.replace("handler", "handler", VertxHandler.create(ctx -> {
            NetSocketImpl socket = new NetSocketImpl(context, ctx, sslHelper, metrics) {

                @Override
                protected void handleClosed() {
                    if (metrics != null) {
                        Http1xServerRequest request = Http1xServerConnection.this.responseInProgress;
                        metrics.responseEnd(request.metric(), request.response(), request.response().bytesWritten());
                    }
                    super.handleClosed();
                }

                @Override
                public synchronized void handleMessage(Object msg) {
                    if (msg instanceof HttpContent) {
                        ReferenceCountUtil.release(msg);
                        return;
                    }
                    super.handleMessage(msg);
                }
            };
            socket.metric(metric());
            return socket;
        }));
        // check if the encoder can be removed yet or not.
        pipeline.remove("httpEncoder");
        // 
        VertxHandler<NetSocketImpl> handler = (VertxHandler<NetSocketImpl>) pipeline.get("handler");
        promise.complete(handler.getConnection());
    });
}
Also used : NetSocketImpl(io.vertx.core.net.impl.NetSocketImpl) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ServerWebSocket(io.vertx.core.http.ServerWebSocket) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) ContextInternal(io.vertx.core.impl.ContextInternal) Supplier(java.util.function.Supplier) Unpooled(io.netty.buffer.Unpooled) BAD_REQUEST(io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST) HttpServerMetrics(io.vertx.core.spi.metrics.HttpServerMetrics) METHOD_NOT_ALLOWED(io.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED) io.netty.channel(io.netty.channel) HTTP_1_1(io.netty.handler.codec.http.HttpVersion.HTTP_1_1) AsyncResult(io.vertx.core.AsyncResult) TracingPolicy(io.vertx.core.tracing.TracingPolicy) Logger(io.vertx.core.impl.logging.Logger) VertxHandler(io.vertx.core.net.impl.VertxHandler) CONTINUE(io.netty.handler.codec.http.HttpResponseStatus.CONTINUE) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) VertxTracer(io.vertx.core.spi.tracing.VertxTracer) Future(io.vertx.core.Future) SSLHelper(io.vertx.core.net.impl.SSLHelper) UPGRADE_REQUIRED(io.netty.handler.codec.http.HttpResponseStatus.UPGRADE_REQUIRED) DecoderResult(io.netty.handler.codec.DecoderResult) io.netty.handler.codec.http(io.netty.handler.codec.http) Buffer(io.vertx.core.buffer.Buffer) io.netty.handler.codec.http.websocketx(io.netty.handler.codec.http.websocketx) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) HttpServerOptions(io.vertx.core.http.HttpServerOptions) METRICS_ENABLED(io.vertx.core.spi.metrics.Metrics.METRICS_ENABLED) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) VertxHandler(io.vertx.core.net.impl.VertxHandler) NetSocketImpl(io.vertx.core.net.impl.NetSocketImpl)

Example 2 with VertxHandler

use of io.vertx.core.net.impl.VertxHandler in project vert.x by eclipse.

the class HttpServerHandlerBenchmark method setup.

@Setup
public void setup() {
    vertx = (VertxInternal) Vertx.vertx();
    HttpServerOptions options = new HttpServerOptions();
    vertxChannel = new EmbeddedChannel(new VertxHttpRequestDecoder(options), // We don't use the VertxHttpResponseDecoder because it will use the PartialPooledByteBufAllocator
    new HttpResponseEncoder() {

        @Override
        protected void encodeHeaders(HttpHeaders headers, ByteBuf buf) {
            ((HeadersMultiMap) headers).encode(buf);
        }
    });
    vertxChannel.config().setAllocator(new Alloc());
    ContextInternal context = vertx.createEventLoopContext(vertxChannel.eventLoop(), null, Thread.currentThread().getContextClassLoader());
    Handler<HttpServerRequest> app = request -> {
        HttpServerResponse response = request.response();
        MultiMap headers = response.headers();
        headers.add(HEADER_CONTENT_TYPE, RESPONSE_TYPE_PLAIN).add(HEADER_SERVER, SERVER).add(HEADER_DATE, DATE_STRING).add(HEADER_CONTENT_LENGTH, HELLO_WORLD_LENGTH);
        response.end(HELLO_WORLD_BUFFER);
    };
    VertxHandler<Http1xServerConnection> handler = VertxHandler.create(chctx -> {
        Http1xServerConnection conn = new Http1xServerConnection(() -> context, null, new HttpServerOptions(), chctx, context, "localhost", null);
        conn.handler(app);
        return conn;
    });
    vertxChannel.pipeline().addLast("handler", handler);
    nettyChannel = new EmbeddedChannel(new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(), options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()), new HttpResponseEncoder(), new SimpleChannelInboundHandler<HttpRequest>() {

        private final byte[] STATIC_PLAINTEXT = "Hello, World!".getBytes(CharsetUtil.UTF_8);

        private final int STATIC_PLAINTEXT_LEN = STATIC_PLAINTEXT.length;

        private final ByteBuf PLAINTEXT_CONTENT_BUFFER = Unpooled.unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_PLAINTEXT));

        private final CharSequence PLAINTEXT_CLHEADER_VALUE = new AsciiString(String.valueOf(STATIC_PLAINTEXT_LEN));

        private final CharSequence TYPE_PLAIN = new AsciiString("text/plain");

        private final CharSequence SERVER_NAME = new AsciiString("Netty");

        private final CharSequence CONTENT_TYPE_ENTITY = HttpHeaderNames.CONTENT_TYPE;

        private final CharSequence DATE_ENTITY = HttpHeaderNames.DATE;

        private final CharSequence CONTENT_LENGTH_ENTITY = HttpHeaderNames.CONTENT_LENGTH;

        private final CharSequence SERVER_ENTITY = HttpHeaderNames.SERVER;

        private final DateFormat FORMAT = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");

        private final CharSequence date = new AsciiString(FORMAT.format(new Date()));

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
            writeResponse(ctx, msg, PLAINTEXT_CONTENT_BUFFER.duplicate(), TYPE_PLAIN, PLAINTEXT_CLHEADER_VALUE);
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }

        private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf, CharSequence contentType, CharSequence contentLength) {
            // Build the response object.
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false);
            HttpHeaders headers = response.headers();
            headers.set(CONTENT_TYPE_ENTITY, contentType);
            headers.set(SERVER_ENTITY, SERVER_NAME);
            headers.set(DATE_ENTITY, date);
            headers.set(CONTENT_LENGTH_ENTITY, contentLength);
            // Close the non-keep-alive connection after the write operation is done.
            ctx.write(response, ctx.voidPromise());
        }
    });
    nettyChannel.config().setAllocator(new Alloc());
    GET = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(("GET / HTTP/1.1\r\n" + "\r\n").getBytes()));
    readerIndex = GET.readerIndex();
    writeIndex = GET.writerIndex();
}
Also used : HttpVersion(io.netty.handler.codec.http.HttpVersion) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) Date(java.util.Date) MultiMap(io.vertx.core.MultiMap) AsciiString(io.netty.util.AsciiString) ContextInternal(io.vertx.core.impl.ContextInternal) SimpleDateFormat(java.text.SimpleDateFormat) Scope(org.openjdk.jmh.annotations.Scope) Unpooled(io.netty.buffer.Unpooled) HeadersMultiMap(io.vertx.core.http.impl.headers.HeadersMultiMap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) CharsetUtil(io.netty.util.CharsetUtil) DateFormat(java.text.DateFormat) VertxHandler(io.vertx.core.net.impl.VertxHandler) Setup(org.openjdk.jmh.annotations.Setup) HttpRequest(io.netty.handler.codec.http.HttpRequest) VertxInternal(io.vertx.core.impl.VertxInternal) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Vertx(io.vertx.core.Vertx) VertxHttpRequestDecoder(io.vertx.core.http.impl.VertxHttpRequestDecoder) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Http1xServerConnection(io.vertx.core.http.impl.Http1xServerConnection) State(org.openjdk.jmh.annotations.State) Benchmark(org.openjdk.jmh.annotations.Benchmark) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Buffer(io.vertx.core.buffer.Buffer) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) HttpServerResponse(io.vertx.core.http.HttpServerResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Fork(org.openjdk.jmh.annotations.Fork) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) CompilerControl(org.openjdk.jmh.annotations.CompilerControl) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) HttpServerOptions(io.vertx.core.http.HttpServerOptions) ContextInternal(io.vertx.core.impl.ContextInternal) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) Http1xServerConnection(io.vertx.core.http.impl.Http1xServerConnection) MultiMap(io.vertx.core.MultiMap) HeadersMultiMap(io.vertx.core.http.impl.headers.HeadersMultiMap) HeadersMultiMap(io.vertx.core.http.impl.headers.HeadersMultiMap) VertxHttpRequestDecoder(io.vertx.core.http.impl.VertxHttpRequestDecoder) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) HttpServerResponse(io.vertx.core.http.HttpServerResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) VertxHttpRequestDecoder(io.vertx.core.http.impl.VertxHttpRequestDecoder) HttpServerRequest(io.vertx.core.http.HttpServerRequest) AsciiString(io.netty.util.AsciiString) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Date(java.util.Date) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) Setup(org.openjdk.jmh.annotations.Setup)

Aggregations

Unpooled (io.netty.buffer.Unpooled)2 Handler (io.vertx.core.Handler)2 Vertx (io.vertx.core.Vertx)2 Buffer (io.vertx.core.buffer.Buffer)2 HttpServerOptions (io.vertx.core.http.HttpServerOptions)2 HttpServerRequest (io.vertx.core.http.HttpServerRequest)2 ContextInternal (io.vertx.core.impl.ContextInternal)2 VertxHandler (io.vertx.core.net.impl.VertxHandler)2 ByteBuf (io.netty.buffer.ByteBuf)1 ByteBufAllocator (io.netty.buffer.ByteBufAllocator)1 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)1 io.netty.channel (io.netty.channel)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 SimpleChannelInboundHandler (io.netty.channel.SimpleChannelInboundHandler)1 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)1 DecoderResult (io.netty.handler.codec.DecoderResult)1 io.netty.handler.codec.http (io.netty.handler.codec.http)1 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)1 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)1 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)1