Example usage for io.netty.handler.codec.http2 Http2Headers status

List of usage examples for io.netty.handler.codec.http2 Http2Headers status

Introduction

In this page you can find the example usage for io.netty.handler.codec.http2 Http2Headers status.

Prototype

CharSequence status();

Source Link

Document

Gets the PseudoHeaderName#STATUS header or null if there is no such header

Usage

From source file:com.linkedin.r2.transport.http.client.Http2FrameListener.java

License:Apache License

@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
        boolean endOfStream) throws Http2Exception {
    LOG.debug("Received HTTP/2 HEADERS frame, stream={}, end={}, headers={}, padding={}bytes",
            new Object[] { streamId, endOfStream, headers.size(), padding });
    // Ignores response for the upgrade request
    if (streamId == Http2CodecUtil.HTTP_UPGRADE_STREAM_ID) {
        return;//from www  .  jav  a  2 s .c om
    }

    final StreamResponseBuilder builder = new StreamResponseBuilder();
    // Process HTTP/2 pseudo headers
    if (headers.status() != null) {
        builder.setStatus(Integer.parseInt(headers.status().toString()));
    }
    if (headers.authority() != null) {
        builder.addHeaderValue(HttpHeaderNames.HOST.toString(), headers.authority().toString());
    }

    // Process other HTTP headers
    for (Map.Entry<CharSequence, CharSequence> header : headers) {
        if (Http2Headers.PseudoHeaderName.isPseudoHeader(header.getKey())) {
            // Do no set HTTP/2 pseudo headers to response
            continue;
        }

        final String key = header.getKey().toString();
        final String value = header.getValue().toString();
        if (key.equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) {
            builder.addCookie(value);
        } else {
            builder.unsafeAddHeaderValue(key, value);
        }
    }

    // Gets async pool handle from stream properties
    Http2Connection.PropertyKey handleKey = ctx.channel()
            .attr(Http2ClientPipelineInitializer.CHANNEL_POOL_HANDLE_ATTR_KEY).get();
    TimeoutAsyncPoolHandle<?> handle = _connection.stream(streamId).removeProperty(handleKey);
    if (handle == null) {
        _lifecycleManager.onError(ctx, Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR,
                "No channel pool handle is associated with this stream", streamId));
        return;
    }

    final StreamResponse response;
    if (endOfStream) {
        response = builder.build(EntityStreams.emptyStream());
        ctx.fireChannelRead(handle);
    } else {
        // Associate an entity stream writer to the HTTP/2 stream
        final TimeoutBufferedWriter writer = new TimeoutBufferedWriter(ctx, streamId, _maxContentLength,
                handle);
        if (_connection.stream(streamId).setProperty(_writerKey, writer) != null) {
            _lifecycleManager.onError(ctx, Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR,
                    "Another writer has already been associated with current stream ID", streamId));
            return;
        }

        // Prepares StreamResponse for the channel pipeline
        EntityStream entityStream = EntityStreams.newEntityStream(writer);
        response = builder.build(entityStream);
    }

    // Gets callback from stream properties
    Http2Connection.PropertyKey callbackKey = ctx.channel()
            .attr(Http2ClientPipelineInitializer.CALLBACK_ATTR_KEY).get();
    TransportCallback<?> callback = _connection.stream(streamId).removeProperty(callbackKey);
    if (callback != null) {
        ctx.fireChannelRead(new ResponseWithCallback<Response, TransportCallback<?>>(response, callback));
    }
}

From source file:com.turo.pushy.apns.ApnsClientHandler.java

License:Open Source License

private void handleEndOfStream(final ChannelHandlerContext context, final Http2Stream stream,
        final Http2Headers headers, final ByteBuf data) {

    final PushNotificationPromise<ApnsPushNotification, PushNotificationResponse<ApnsPushNotification>> responsePromise = stream
            .getProperty(this.responsePromisePropertyKey);

    final ApnsPushNotification pushNotification = responsePromise.getPushNotification();

    final HttpResponseStatus status = HttpResponseStatus.parseLine(headers.status());

    if (HttpResponseStatus.OK.equals(status)) {
        responsePromise.trySuccess(new SimplePushNotificationResponse<>(responsePromise.getPushNotification(),
                true, getApnsIdFromHeaders(headers), null, null));
    } else {/*from   w  ww .  j a v  a  2s . c o  m*/
        if (data != null) {
            final ErrorResponse errorResponse = GSON.fromJson(data.toString(StandardCharsets.UTF_8),
                    ErrorResponse.class);
            this.handleErrorResponse(context, stream.id(), headers, pushNotification, errorResponse);
        } else {
            log.warn("Gateway sent an end-of-stream HEADERS frame for an unsuccessful notification.");
        }
    }
}

From source file:com.turo.pushy.apns.ApnsClientHandler.java

License:Open Source License

protected void handleErrorResponse(final ChannelHandlerContext context, final int streamId,
        final Http2Headers headers, final ApnsPushNotification pushNotification,
        final ErrorResponse errorResponse) {
    final PushNotificationPromise<ApnsPushNotification, PushNotificationResponse<ApnsPushNotification>> responsePromise = this
            .connection().stream(streamId).getProperty(this.responsePromisePropertyKey);

    final HttpResponseStatus status = HttpResponseStatus.parseLine(headers.status());

    responsePromise.trySuccess(new SimplePushNotificationResponse<>(responsePromise.getPushNotification(),
            HttpResponseStatus.OK.equals(status), getApnsIdFromHeaders(headers), errorResponse.getReason(),
            errorResponse.getTimestamp()));
}

From source file:io.gatling.http.client.impl.ChunkedInboundHttp2ToHttpAdapter.java

License:Apache License

@Override
public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
        Http2Headers headers, int padding) throws Http2Exception {
    if (connection.stream(promisedStreamId) != null)
        throw connectionError(PROTOCOL_ERROR, "Push Promise Frame received for pre-existing stream id %d",
                promisedStreamId);/*from  w w  w .j av a  2 s  .co  m*/

    if (headers.status() == null)
        headers.status(OK.codeAsText());

    convertAndFire(ctx, streamId, headers, true);
}

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

License:Open Source License

@Test
public void testGet() throws Exception {
    String expected = TestUtils.randomAlphaString(1000);
    AtomicBoolean requestEnded = new AtomicBoolean();
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {/*from  w  ww. ja v  a2 s.  c o m*/
        assertOnIOContext(ctx);
        req.endHandler(v -> {
            assertOnIOContext(ctx);
            requestEnded.set(true);
        });
        HttpServerResponse resp = req.response();
        assertEquals(HttpMethod.GET, req.method());
        assertEquals(DEFAULT_HTTPS_HOST_AND_PORT, req.host());
        assertEquals("/", req.path());
        assertTrue(req.isSSL());
        assertEquals("https", req.scheme());
        assertEquals("/", req.uri());
        assertEquals("foo_request_value", req.getHeader("Foo_request"));
        assertEquals("bar_request_value", req.getHeader("bar_request"));
        assertEquals(2, req.headers().getAll("juu_request").size());
        assertEquals("juu_request_value_1", req.headers().getAll("juu_request").get(0));
        assertEquals("juu_request_value_2", req.headers().getAll("juu_request").get(1));
        assertEquals(Collections.singletonList("cookie_1; cookie_2; cookie_3"), req.headers().getAll("cookie"));
        resp.putHeader("content-type", "text/plain");
        resp.putHeader("Foo_response", "foo_response_value");
        resp.putHeader("bar_response", "bar_response_value");
        resp.putHeader("juu_response",
                (List<String>) Arrays.asList("juu_response_value_1", "juu_response_value_2"));
        resp.end(expected);
    });
    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() {
            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                vertx.runOnContext(v -> {
                    assertEquals(id, streamId);
                    assertEquals("200", headers.status().toString());
                    assertEquals("text/plain", headers.get("content-type").toString());
                    assertEquals("foo_response_value", headers.get("foo_response").toString());
                    assertEquals("bar_response_value", headers.get("bar_response").toString());
                    assertEquals(2, headers.getAll("juu_response").size());
                    assertEquals("juu_response_value_1", headers.getAll("juu_response").get(0).toString());
                    assertEquals("juu_response_value_2", headers.getAll("juu_response").get(1).toString());
                    assertFalse(endStream);
                });
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                String actual = data.toString(StandardCharsets.UTF_8);
                vertx.runOnContext(v -> {
                    assertEquals(id, streamId);
                    assertEquals(expected, actual);
                    assertTrue(endOfStream);
                    testComplete();
                });
                return super.onDataRead(ctx, streamId, data, padding, endOfStream);
            }
        });
        Http2Headers headers = GET("/").authority(DEFAULT_HTTPS_HOST_AND_PORT);
        headers.set("foo_request", "foo_request_value");
        headers.set("bar_request", "bar_request_value");
        headers.set("juu_request", "juu_request_value_1", "juu_request_value_2");
        headers.set("cookie", Arrays.asList("cookie_1", "cookie_2", "cookie_3"));
        request.encoder.writeHeaders(request.context, id, headers, 0, true, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

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

License:Open Source License

private void test100Continue() throws Exception {
    startServer();//from w  w  w .j  a v a  2s.  co  m
    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 count = 0;

            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                switch (count++) {
                case 0:
                    vertx.runOnContext(v -> {
                        assertEquals("100", headers.status().toString());
                    });
                    request.encoder.writeData(request.context, id, Buffer.buffer("the-body").getByteBuf(), 0,
                            true, request.context.newPromise());
                    request.context.flush();
                    break;
                case 1:
                    vertx.runOnContext(v -> {
                        assertEquals("200", headers.status().toString());
                        assertEquals("wibble-value", headers.get("wibble").toString());
                        testComplete();
                    });
                    break;
                default:
                    vertx.runOnContext(v -> {
                        fail();
                    });
                }
            }
        });
        request.encoder.writeHeaders(request.context, id, GET("/").add("expect", "100-continue"), 0, false,
                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 test100ContinueRejectedManually() throws Exception {
    server.requestHandler(req -> {/*from  w  ww  .j a va  2 s  .c  o  m*/
        req.response().setStatusCode(405).end();
        req.handler(buf -> {
            fail();
        });
    });
    startServer();
    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 count = 0;

            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                switch (count++) {
                case 0:
                    vertx.runOnContext(v -> {
                        assertEquals("405", headers.status().toString());
                        vertx.setTimer(100, v2 -> {
                            testComplete();
                        });
                    });
                    break;
                default:
                    vertx.runOnContext(v -> {
                        fail();
                    });
                }
            }
        });
        request.encoder.writeHeaders(request.context, id, GET("/").add("expect", "100-continue"), 0, false,
                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 testNetSocketConnect() throws Exception {
    waitFor(2);//from   w w  w.j a  va 2 s.  co  m
    List<Integer> callbacks = Collections.synchronizedList(new ArrayList<>());

    server.requestHandler(req -> {
        NetSocket socket = req.netSocket();
        AtomicInteger status = new AtomicInteger();
        socket.handler(buff -> {
            switch (status.getAndIncrement()) {
            case 0:
                assertEquals(Buffer.buffer("some-data"), buff);
                socket.write(buff, onSuccess(v2 -> callbacks.add(0)));
                break;
            case 1:
                assertEquals(Buffer.buffer("last-data"), buff);
                break;
            default:
                fail();
                break;
            }
        });
        socket.endHandler(v1 -> {
            assertEquals(2, status.getAndIncrement());
            socket.write(Buffer.buffer("last-data"), onSuccess(v2 -> callbacks.add(1)));
        });
        socket.closeHandler(v -> {
            assertEquals(2, callbacks.size());
            assertEquals(Arrays.asList(0, 1), callbacks);
            complete();
        });
    });

    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.decoder.frameListener(new Http2EventAdapter() {
            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                vertx.runOnContext(v -> {
                    assertEquals("200", headers.status().toString());
                    assertFalse(endStream);
                });
                request.encoder.writeData(request.context, id, Buffer.buffer("some-data").getByteBuf(), 0,
                        false, request.context.newPromise());
                request.context.flush();
            }

            StringBuilder received = new StringBuilder();

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                String s = data.toString(StandardCharsets.UTF_8);
                received.append(s);
                if (received.toString().equals("some-data")) {
                    received.setLength(0);
                    vertx.runOnContext(v -> {
                        assertFalse(endOfStream);
                    });
                    request.encoder.writeData(request.context, id, Buffer.buffer("last-data").getByteBuf(), 0,
                            true, request.context.newPromise());
                } else if (endOfStream) {
                    vertx.runOnContext(v -> {
                        assertEquals("last-data", received.toString());
                        complete();
                    });
                }
                return data.readableBytes() + padding;
            }
        });
        request.encoder.writeHeaders(request.context, id, GET("/"), 0, false, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

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

License:Open Source License

private void testNetSocketSendFile(Buffer expected, String path, long offset, long length) throws Exception {
    server.requestHandler(req -> {/*from   w ww  . java  2  s.  com*/
        NetSocket socket = req.netSocket();
        socket.sendFile(path, offset, length, ar -> {
            assertTrue(ar.succeeded());
            socket.end();
        });
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.decoder.frameListener(new Http2EventAdapter() {
            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                vertx.runOnContext(v -> {
                    assertEquals("200", headers.status().toString());
                    assertFalse(endStream);
                });
            }

            Buffer received = Buffer.buffer();

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                received.appendBuffer(Buffer.buffer(data.copy()));
                if (endOfStream) {
                    vertx.runOnContext(v -> {
                        assertEquals(received, expected);
                        testComplete();
                    });
                }
                return data.readableBytes() + padding;
            }
        });
        request.encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

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

License:Open Source License

@Test
public void testGet() throws Exception {
    String expected = TestUtils.randomAlphaString(1000);
    AtomicBoolean requestEnded = new AtomicBoolean();
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {/*  w w  w.ja v a2 s. com*/
        assertOnIOContext(ctx);
        req.endHandler(v -> {
            assertOnIOContext(ctx);
            requestEnded.set(true);
        });
        HttpServerResponse resp = req.response();
        assertEquals(HttpMethod.GET, req.method());
        assertEquals(DEFAULT_HTTPS_HOST_AND_PORT, req.host());
        assertEquals("/", req.path());
        assertEquals(DEFAULT_HTTPS_HOST_AND_PORT, req.getHeader(":authority"));
        assertTrue(req.isSSL());
        assertEquals("https", req.getHeader(":scheme"));
        assertEquals("/", req.getHeader(":path"));
        assertEquals("GET", req.getHeader(":method"));
        assertEquals("foo_request_value", req.getHeader("Foo_request"));
        assertEquals("bar_request_value", req.getHeader("bar_request"));
        assertEquals(2, req.headers().getAll("juu_request").size());
        assertEquals("juu_request_value_1", req.headers().getAll("juu_request").get(0));
        assertEquals("juu_request_value_2", req.headers().getAll("juu_request").get(1));
        assertEquals(Collections.singletonList("cookie_1; cookie_2; cookie_3"), req.headers().getAll("cookie"));
        resp.putHeader("content-type", "text/plain");
        resp.putHeader("Foo_response", "foo_response_value");
        resp.putHeader("bar_response", "bar_response_value");
        resp.putHeader("juu_response",
                (List<String>) Arrays.asList("juu_response_value_1", "juu_response_value_2"));
        resp.end(expected);
    });
    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() {
            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                vertx.runOnContext(v -> {
                    assertEquals(id, streamId);
                    assertEquals("200", headers.status().toString());
                    assertEquals("text/plain", headers.get("content-type").toString());
                    assertEquals("foo_response_value", headers.get("foo_response").toString());
                    assertEquals("bar_response_value", headers.get("bar_response").toString());
                    assertEquals(2, headers.getAll("juu_response").size());
                    assertEquals("juu_response_value_1", headers.getAll("juu_response").get(0).toString());
                    assertEquals("juu_response_value_2", headers.getAll("juu_response").get(1).toString());
                    assertFalse(endStream);
                });
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                String actual = data.toString(StandardCharsets.UTF_8);
                vertx.runOnContext(v -> {
                    assertEquals(id, streamId);
                    assertEquals(expected, actual);
                    assertTrue(endOfStream);
                    testComplete();
                });
                return super.onDataRead(ctx, streamId, data, padding, endOfStream);
            }
        });
        Http2Headers headers = GET("/").authority(DEFAULT_HTTPS_HOST_AND_PORT);
        headers.set("foo_request", "foo_request_value");
        headers.set("bar_request", "bar_request_value");
        headers.set("juu_request", "juu_request_value_1", "juu_request_value_2");
        headers.set("cookie", Arrays.asList("cookie_1", "cookie_2", "cookie_3"));
        request.encoder.writeHeaders(request.context, id, headers, 0, true, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}