Java Code Examples for io.netty.handler.codec.http2.Http2Headers#status()

The following examples show how to use io.netty.handler.codec.http2.Http2Headers#status() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: H2ToStH1ServerDuplexHandler.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    if (msg instanceof HttpResponseMetaData) {
        HttpResponseMetaData metaData = (HttpResponseMetaData) msg;
        HttpHeaders h1Headers = metaData.headers();
        Http2Headers h2Headers = h1HeadersToH2Headers(h1Headers);
        h2Headers.status(metaData.status().codeAsCharSequence());
        ctx.write(new DefaultHttp2HeadersFrame(h2Headers, false), promise);
    } else if (msg instanceof Buffer) {
        writeBuffer(ctx, msg, promise);
    } else if (msg instanceof HttpHeaders) {
        writeTrailers(ctx, msg, promise);
    } else {
        ctx.write(msg, promise);
    }
}
 
Example 2
Source File: H2PriorKnowledgeFeatureParityTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
private void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers) {
    if (headers.isEndStream()) {
        ctx.write(new DefaultHttp2HeadersFrame(headers.headers(), true));
    } else {
        Http2Headers outHeaders = new DefaultHttp2Headers();
        if (headers.headers().contains(EXPECT, CONTINUE)) {
            if (headers.headers().contains(EXPECT_FAIL_HEADER)) {
                outHeaders.status(
                        io.netty.handler.codec.http.HttpResponseStatus.EXPECTATION_FAILED.codeAsText());
                ctx.write(new DefaultHttp2HeadersFrame(outHeaders, true));
                return;
            } else {
                outHeaders.status(io.netty.handler.codec.http.HttpResponseStatus.CONTINUE.codeAsText());
            }
        } else {
            outHeaders.status(io.netty.handler.codec.http.HttpResponseStatus.OK.codeAsText());
        }

        CharSequence contentType = headers.headers().get(CONTENT_TYPE);
        if (contentType != null) {
            outHeaders.add(CONTENT_TYPE, contentType);
        }
        outHeaders.add(HttpHeaderNames.COOKIE, headers.headers().getAll(HttpHeaderNames.COOKIE));
        ctx.write(new DefaultHttp2HeadersFrame(outHeaders));
    }
}
 
Example 3
Source File: Http2Handler.java    From xrpc with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the given response body as "text/plain" to the given stream. Marks the response status
 * metric. Closes the stream after writing the response.
 */
private void writeResponse(
    ChannelHandlerContext ctx, int streamId, HttpResponseStatus status, ByteBuf body) {

  Preconditions.checkArgument(body != null, "body must not be null");

  markResponseStatus(ctx, status);

  Http2Headers headers = new DefaultHttp2Headers(true);
  // TODO(jkinkead): This should honor accept headers; we shouldn't send text/plain if the client
  // doesn't want it.
  headers.set(CONTENT_TYPE, "text/plain");
  headers.setInt(CONTENT_LENGTH, body.readableBytes());
  headers.status(status.codeAsText());

  writeResponse(ctx, streamId, headers, Optional.of(body));
}
 
Example 4
Source File: NettyClientStreamTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidInboundHeadersCancelStream() throws Exception {
  stream().transportState().setId(STREAM_ID);
  Http2Headers headers = grpcResponseHeaders();
  headers.set("random", "4");
  headers.remove(CONTENT_TYPE_HEADER);
  // Remove once b/16290036 is fixed.
  headers.status(new AsciiString("500"));
  stream().transportState().transportHeadersReceived(headers, false);
  verify(listener, never()).closed(any(Status.class), any(Metadata.class));

  // We are now waiting for 100 bytes of error context on the stream, cancel has not yet been
  // sent
  verify(channel, never()).writeAndFlush(any(CancelClientStreamCommand.class));
  stream().transportState().transportDataReceived(Unpooled.buffer(100).writeZero(100), false);
  verify(channel, never()).writeAndFlush(any(CancelClientStreamCommand.class));
  stream().transportState().transportDataReceived(Unpooled.buffer(1000).writeZero(1000), false);

  // Now verify that cancel is sent and an error is reported to the listener
  verify(writeQueue).enqueue(isA(CancelClientStreamCommand.class), eq(true));
  ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(Status.class);
  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
  verify(listener).closed(captor.capture(), same(PROCESSED), metadataCaptor.capture());
  assertEquals(Status.UNKNOWN.getCode(), captor.getValue().getCode());
  assertEquals("4", metadataCaptor.getValue()
      .get(Metadata.Key.of("random", Metadata.ASCII_STRING_MARSHALLER)));

}
 
Example 5
Source File: ReadOnlyHttp2HeadersBenchmark.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int defaultServerHeaders() {
    Http2Headers headers = new DefaultHttp2Headers(false);
    for (int i = 0; i < headerCount; ++i) {
        headers.add(headerNames[i], headerValues[i]);
    }
    headers.status(HttpResponseStatus.OK.codeAsText());
    return iterate(headers);
}
 
Example 6
Source File: Http2ClientCodec.java    From xio with Apache License 2.0 5 votes vote down vote up
private Response wrapResponse(ChannelHandlerContext ctx, Http2Response msg) {
  log.debug("wrapResponse msg={}", msg);
  final Response response;
  Http2MessageSession session = Http2MessageSession.lazyCreateSession(ctx);
  int streamId =
      Http2ClientStreamMapper.http2ClientStreamMapper(ctx).inboundStreamId(msg.streamId, msg.eos);
  if (msg.payload instanceof Http2Headers) {
    Http2Headers headers = (Http2Headers) msg.payload;
    if (msg.eos && headers.method() == null && headers.status() == null) {
      response =
          session
              .currentResponse(msg.streamId)
              .map(
                  resp ->
                      session.onInboundResponse(
                          new SegmentedResponseData(
                              resp, new Http2SegmentedData(headers, streamId))))
              .orElse(null);
    } else {
      response = wrapHeaders(headers, streamId, msg.eos);
      session.onInboundResponse(response);
    }
  } else if (msg.payload instanceof Http2DataFrame) {
    Http2DataFrame frame = (Http2DataFrame) msg.payload;
    response =
        session
            .currentResponse(streamId)
            .map(
                resp ->
                    session.onInboundResponse(
                        new SegmentedResponseData(
                            resp, new Http2SegmentedData(frame.content(), msg.eos, streamId))))
            .orElse(null);
  } else {
    // TODO(CK): throw an exception?
    response = null;
  }

  return response;
}
 
Example 7
Source File: NettyClientStreamTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidInboundHeadersCancelStream() throws Exception {
  stream().transportState().setId(STREAM_ID);
  Http2Headers headers = grpcResponseHeaders();
  headers.set("random", "4");
  headers.remove(CONTENT_TYPE_HEADER);
  // Remove once b/16290036 is fixed.
  headers.status(new AsciiString("500"));
  stream().transportState().transportHeadersReceived(headers, false);
  verify(listener, never()).closed(any(Status.class), any(Metadata.class));

  // We are now waiting for 100 bytes of error context on the stream, cancel has not yet been
  // sent
  verify(channel, never()).writeAndFlush(any(CancelClientStreamCommand.class));
  stream().transportState().transportDataReceived(Unpooled.buffer(100).writeZero(100), false);
  verify(channel, never()).writeAndFlush(any(CancelClientStreamCommand.class));
  stream().transportState().transportDataReceived(Unpooled.buffer(1000).writeZero(1000), false);

  // Now verify that cancel is sent and an error is reported to the listener
  verify(writeQueue).enqueue(isA(CancelClientStreamCommand.class), eq(true));
  ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(Status.class);
  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
  verify(listener).closed(captor.capture(), same(PROCESSED), metadataCaptor.capture());
  assertEquals(Status.UNKNOWN.getCode(), captor.getValue().getCode());
  assertEquals("4", metadataCaptor.getValue()
      .get(Metadata.Key.of("random", Metadata.ASCII_STRING_MARSHALLER)));

}