Search in sources :

Example 56 with DefaultHttp2Headers

use of io.netty.handler.codec.http2.DefaultHttp2Headers in project vert.x by eclipse.

the class Http2ClientTest method testClearText.

private void testClearText(boolean upgrade) throws Exception {
    Assume.assumeTrue(testAddress.isInetSocket());
    ServerBootstrap bootstrap = createH2CServer((dec, enc) -> new Http2EventAdapter() {

        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, true, ctx.newPromise());
            ctx.flush();
        }
    }, upgrade);
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        client.close();
        client = vertx.createHttpClient(clientOptions.setUseAlpn(false).setSsl(false).setHttp2ClearTextUpgrade(upgrade));
        client.request(requestOptions).onComplete(onSuccess(req1 -> {
            req1.send(onSuccess(resp1 -> {
                HttpConnection conn = resp1.request().connection();
                assertEquals(HttpVersion.HTTP_2, resp1.version());
                client.request(requestOptions).onComplete(onSuccess(req2 -> {
                    req2.send(onSuccess(resp2 -> {
                        assertSame(((HttpClientConnection) conn).channel(), ((HttpClientConnection) resp2.request().connection()).channel());
                        testComplete();
                    }));
                }));
            }));
        }));
        await();
    } finally {
        s.channel().close().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Arrays(java.util.Arrays) io.netty.handler.codec.http2(io.netty.handler.codec.http2) BiFunction(java.util.function.BiFunction) MultiMap(io.vertx.core.MultiMap) AsciiString(io.netty.util.AsciiString) Context(io.vertx.core.Context) HttpClientConnection(io.vertx.core.http.impl.HttpClientConnection) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Cert(io.vertx.test.tls.Cert) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Assume(org.junit.Assume) ConnectException(java.net.ConnectException) AsyncResult(io.vertx.core.AsyncResult) SocketAddress(io.vertx.core.net.SocketAddress) VertxInternal(io.vertx.core.impl.VertxInternal) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) SSLHelper(io.vertx.core.net.impl.SSLHelper) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) AtomicLong(java.util.concurrent.atomic.AtomicLong) Ignore(org.junit.Ignore) AsyncTestBase(io.vertx.test.core.AsyncTestBase) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 57 with DefaultHttp2Headers

use of io.netty.handler.codec.http2.DefaultHttp2Headers in project vert.x by eclipse.

the class Http2ClientTest method testInvalidServerResponse.

@Test
public void testInvalidServerResponse() throws Exception {
    ServerBootstrap bootstrap = createH2Server((dec, enc) -> new Http2EventAdapter() {

        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("xyz"), 0, false, ctx.newPromise());
            ctx.flush();
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        Context ctx = vertx.getOrCreateContext();
        client.close();
        ctx.runOnContext(v -> {
            client = vertx.createHttpClient(createBaseClientOptions());
            client.connectionHandler(conn -> {
                conn.exceptionHandler(err -> fail());
            });
            client.request(requestOptions).onComplete(onSuccess(req -> {
                req.send(onFailure(err -> {
                    assertOnIOContext(ctx);
                    if (err instanceof NumberFormatException) {
                        testComplete();
                    }
                }));
            }));
        });
        await();
    } finally {
        s.channel().close().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Arrays(java.util.Arrays) io.netty.handler.codec.http2(io.netty.handler.codec.http2) BiFunction(java.util.function.BiFunction) MultiMap(io.vertx.core.MultiMap) AsciiString(io.netty.util.AsciiString) Context(io.vertx.core.Context) HttpClientConnection(io.vertx.core.http.impl.HttpClientConnection) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Cert(io.vertx.test.tls.Cert) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Assume(org.junit.Assume) ConnectException(java.net.ConnectException) AsyncResult(io.vertx.core.AsyncResult) SocketAddress(io.vertx.core.net.SocketAddress) VertxInternal(io.vertx.core.impl.VertxInternal) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) SSLHelper(io.vertx.core.net.impl.SSLHelper) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) AtomicLong(java.util.concurrent.atomic.AtomicLong) Ignore(org.junit.Ignore) AsyncTestBase(io.vertx.test.core.AsyncTestBase) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Test(org.junit.Test)

Example 58 with DefaultHttp2Headers

use of io.netty.handler.codec.http2.DefaultHttp2Headers in project vert.x by eclipse.

the class HeadersTestBase method testSetAllOnExistingMapUsingHashMapHttp2.

@Test
public void testSetAllOnExistingMapUsingHashMapHttp2() {
    MultiMap mainMap = new Http2HeadersAdaptor(new DefaultHttp2Headers());
    mainMap.add("originalKey", "originalValue");
    Map<String, String> setAllMap = new HashMap<>();
    setAllMap.put("originalKey", "newValue");
    setAllMap.put("anotherKey", "anotherValue");
    MultiMap result = mainMap.setAll(setAllMap);
    assertNotNull(result);
    assertFalse(result.isEmpty());
    assertEquals(2, result.size());
    assertEquals("newValue", result.get("originalKey"));
    assertEquals("anotherValue", result.get("anotherKey"));
}
Also used : MultiMap(io.vertx.core.MultiMap) HeadersMultiMap(io.vertx.core.http.impl.headers.HeadersMultiMap) HashMap(java.util.HashMap) Http2HeadersAdaptor(io.vertx.core.http.impl.headers.Http2HeadersAdaptor) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Test(org.junit.Test)

Example 59 with DefaultHttp2Headers

use of io.netty.handler.codec.http2.DefaultHttp2Headers in project rest.li by linkedin.

the class NettyRequestAdapter method toHttp2Headers.

/**
 * Extracts fields from a {@link Request} and construct a {@link Http2Headers} instance.
 *
 * @param request StreamRequest to extract fields from
 * @return a new instance of Http2Headers
 * @throws {@link Exception}
 */
public static <R extends Request> Http2Headers toHttp2Headers(R request) throws Exception {
    URI uri = request.getURI();
    URL url = new URL(uri.toString());
    String method = request.getMethod();
    String authority = url.getAuthority();
    String path = url.getFile();
    String scheme = uri.getScheme();
    // RFC 2616, section 5.1.2:
    // Note that the absolute path cannot be empty; if none is present in the original URI,
    // it MUST be given as "/" (the server root).
    path = path.isEmpty() ? "/" : path;
    final Http2Headers headers = new DefaultHttp2Headers().method(method).authority(authority).path(path).scheme(scheme);
    for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
        // Ignores HTTP/2 blacklisted headers
        if (HEADER_BLACKLIST.contains(entry.getKey().toLowerCase())) {
            continue;
        }
        // RFC 7540, section 8.1.2:
        // ... header field names MUST be converted to lowercase prior to their
        // encoding in HTTP/2.  A request or response containing uppercase
        // header field names MUST be treated as malformed (Section 8.1.2.6).
        String name = entry.getKey().toLowerCase();
        String value = entry.getValue();
        headers.set(name, value);
    }
    // Split up cookies to allow for better header compression
    headers.set(HttpHeaderNames.COOKIE, request.getCookies());
    return headers;
}
Also used : Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) AsciiString(io.netty.util.AsciiString) URI(java.net.URI) Map(java.util.Map) URL(java.net.URL)

Example 60 with DefaultHttp2Headers

use of io.netty.handler.codec.http2.DefaultHttp2Headers in project ambry by linkedin.

the class AmbrySendToHttp2Adaptor method write.

/**
 * Handles conversion of {@link Send} to HTTP/2 frames.
 */
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    if (!ctx.channel().isOpen()) {
        logger.debug("Channel closed when write. Channel: {}", ctx.channel());
        promise.setFailure(new ChannelException("Channel has been closed when write."));
    }
    if (!(msg instanceof Send)) {
        ctx.write(msg, promise);
        return;
    }
    Send send = (Send) msg;
    Http2Headers http2Headers;
    if (forServer) {
        logger.trace("Write content to channel as server {}", ctx.channel());
        http2Headers = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText());
    } else {
        logger.trace("Write content to channel as client {}", ctx.channel());
        http2Headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName()).scheme("https").path("/");
    }
    DefaultHttp2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(http2Headers, false);
    ctx.write(headersFrame);
    // Referencing counting for derived {@link ByteBuf}: https://netty.io/wiki/reference-counted-objects.html#derived-buffers
    try {
        while (send.content().isReadable(maxFrameSize)) {
            ByteBuf slice = send.content().readSlice(maxFrameSize);
            slice.retain();
            DefaultHttp2DataFrame dataFrame = new DefaultHttp2DataFrame(slice, false);
            ctx.write(dataFrame);
        }
        // The last slice
        ByteBuf slice = send.content().readSlice(send.content().readableBytes());
        slice.retain();
        DefaultHttp2DataFrame dataFrame = new DefaultHttp2DataFrame(slice, true);
        ctx.write(dataFrame, promise);
    } catch (Exception e) {
        logger.error("Error while processing frames. Channel: {}", ctx.channel(), e);
    } finally {
        send.content().release();
    }
}
Also used : DefaultHttp2HeadersFrame(io.netty.handler.codec.http2.DefaultHttp2HeadersFrame) DefaultHttp2DataFrame(io.netty.handler.codec.http2.DefaultHttp2DataFrame) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) ByteBuf(io.netty.buffer.ByteBuf) ChannelException(io.netty.channel.ChannelException) ChannelException(io.netty.channel.ChannelException) Send(com.github.ambry.network.Send)

Aggregations

DefaultHttp2Headers (io.netty.handler.codec.http2.DefaultHttp2Headers)72 Http2Headers (io.netty.handler.codec.http2.Http2Headers)58 AsciiString (io.netty.util.AsciiString)56 ByteBuf (io.netty.buffer.ByteBuf)54 Test (org.junit.Test)49 Test (org.junit.jupiter.api.Test)32 ChannelFuture (io.netty.channel.ChannelFuture)27 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)19 ChannelPromise (io.netty.channel.ChannelPromise)17 Channel (io.netty.channel.Channel)16 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)16 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)15 List (java.util.List)15 ChannelInitializer (io.netty.channel.ChannelInitializer)14 ChannelPipeline (io.netty.channel.ChannelPipeline)14 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)14 HttpServerCodec (io.netty.handler.codec.http.HttpServerCodec)14 Http2Runnable (io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable)14 ApplicationProtocolNames (io.netty.handler.ssl.ApplicationProtocolNames)14 ApplicationProtocolNegotiationHandler (io.netty.handler.ssl.ApplicationProtocolNegotiationHandler)14