io.netty.handler.codec.http.DefaultHttpRequest Java Examples

The following examples show how to use io.netty.handler.codec.http.DefaultHttpRequest. 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: HttpAuthUpstreamHandlerTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotNoHbaConfig() throws Exception {
    HttpAuthUpstreamHandler handler = new HttpAuthUpstreamHandler(Settings.EMPTY, authService);
    EmbeddedChannel ch = new EmbeddedChannel(handler);

    DefaultHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/_sql");
    request.headers().add(HttpHeaderNames.AUTHORIZATION.toString(), "Basic QWxhZGRpbjpPcGVuU2VzYW1l");
    request.headers().add("X-Real-Ip", "10.1.0.100");

    ch.writeInbound(request);
    ch.releaseInbound();
    assertFalse(handler.authorized());

    assertUnauthorized(
        ch.readOutbound(),
        "No valid auth.host_based.config entry found for host \"10.1.0.100\", user \"Aladdin\", protocol \"http\"\n");
}
 
Example #2
Source File: HttpPostRequestDecoderTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormEncodeIncorrect() throws Exception {
    LastHttpContent content = new DefaultLastHttpContent(
            Unpooled.copiedBuffer("project=netty&&project=netty", CharsetUtil.US_ASCII));
    DefaultHttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req);
    try {
        decoder.offer(content);
        fail();
    } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) {
        assertTrue(e.getCause() instanceof IllegalArgumentException);
    } finally {
        decoder.destroy();
        content.release();
    }
}
 
Example #3
Source File: RtspDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected HttpMessage createMessage(final String[] initialLine)
        throws Exception {
    // If the first element of the initial line is a version string then
    // this is a response
    if (versionPattern.matcher(initialLine[0]).matches()) {
        isDecodingRequest = false;
        return new DefaultHttpResponse(RtspVersions.valueOf(initialLine[0]),
            new HttpResponseStatus(Integer.parseInt(initialLine[1]),
                                   initialLine[2]),
            validateHeaders);
    } else {
        isDecodingRequest = true;
        return new DefaultHttpRequest(RtspVersions.valueOf(initialLine[2]),
                RtspMethods.valueOf(initialLine[0]),
                initialLine[1],
                validateHeaders);
    }
}
 
Example #4
Source File: Http2StreamFrameToHttpObjectCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeRequestHeaders() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello/world");
    assertTrue(ch.writeOutbound(request));

    Http2HeadersFrame headersFrame = ch.readOutbound();
    Http2Headers headers = headersFrame.headers();

    assertThat(headers.scheme().toString(), is("http"));
    assertThat(headers.method().toString(), is("GET"));
    assertThat(headers.path().toString(), is("/hello/world"));
    assertFalse(headersFrame.isEndStream());

    assertThat(ch.readOutbound(), is(nullValue()));
    assertFalse(ch.finish());
}
 
Example #5
Source File: HttpConversionUtil.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new object to contain the request data.
 *
 * @param streamId The stream associated with the request
 * @param http2Headers The initial set of HTTP/2 headers to create the request with
 * @param validateHttpHeaders <ul>
 *        <li>{@code true} to validate HTTP headers in the http-codec</li>
 *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
 *        </ul>
 * @return A new request object which represents headers for a chunked request
 * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
 */
public static HttpRequest toHttpRequest(int streamId, Http2Headers http2Headers, boolean validateHttpHeaders)
                throws Http2Exception {
    // HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line.
    final CharSequence method = checkNotNull(http2Headers.method(),
            "method header cannot be null in conversion to HTTP/1.x");
    final CharSequence path = checkNotNull(http2Headers.path(),
            "path header cannot be null in conversion to HTTP/1.x");
    HttpRequest msg = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method.toString()),
            path.toString(), validateHttpHeaders);
    try {
        addHttp2ToHttpHeaders(streamId, http2Headers, msg.headers(), msg.protocolVersion(), false, true);
    } catch (Http2Exception e) {
        throw e;
    } catch (Throwable t) {
        throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
    }
    return msg;
}
 
Example #6
Source File: ProxyRouterEndpoint.java    From riposte with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method that generates a {@link HttpRequest} for the downstream call's first chunk that uses the given
 * downstreamPath and downstreamMethod, and the query string and headers from the incomingRequest will be added and
 * passed through without modification.
 */
@SuppressWarnings("UnusedParameters")
protected @NotNull HttpRequest generateSimplePassthroughRequest(
    @NotNull RequestInfo<?> incomingRequest,
    @NotNull String downstreamPath,
    @NotNull HttpMethod downstreamMethod,
    @NotNull ChannelHandlerContext ctx
) {
    String queryString = extractQueryString(incomingRequest.getUri());
    String downstreamUri = downstreamPath;
    // TODO: Add logic to support when downstreamPath already has a query string on it. The two query strings should be combined
    if (queryString != null)
        downstreamUri += queryString;
    HttpRequest downstreamRequestInfo =
        new DefaultHttpRequest(HttpVersion.HTTP_1_1, downstreamMethod, downstreamUri);
    downstreamRequestInfo.headers().set(incomingRequest.getHeaders());
    return downstreamRequestInfo;
}
 
Example #7
Source File: HttpRequestInfo.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
public static HttpRequest adapter(HttpRequest httpRequest) {
  if (httpRequest instanceof DefaultHttpRequest) {
    HttpVer version;
    if (httpRequest.protocolVersion().minorVersion() == 0) {
      version = HttpVer.HTTP_1_0;
    } else {
      version = HttpVer.HTTP_1_1;
    }
    HttpHeadsInfo httpHeadsInfo = new HttpHeadsInfo();
    for (Entry<String, String> entry : httpRequest.headers()) {
      httpHeadsInfo.set(entry.getKey(), entry.getValue());
    }
    return new HttpRequestInfo(version, httpRequest.method().toString(), httpRequest.uri(),
        httpHeadsInfo, null);
  }
  return httpRequest;
}
 
Example #8
Source File: HttpRequestInfo.java    From pdown-core with MIT License 6 votes vote down vote up
public static HttpRequest adapter(HttpRequest httpRequest) {
  if (httpRequest instanceof DefaultHttpRequest) {
    HttpVer version;
    if (httpRequest.protocolVersion().minorVersion() == 0) {
      version = HttpVer.HTTP_1_0;
    } else {
      version = HttpVer.HTTP_1_1;
    }
    HttpHeadsInfo httpHeadsInfo = new HttpHeadsInfo();
    for (Entry<String, String> entry : httpRequest.headers()) {
      httpHeadsInfo.set(entry.getKey(), entry.getValue());
    }
    return new HttpRequestInfo(version, httpRequest.method(), httpRequest.uri(),
        httpHeadsInfo, null);
  }
  return httpRequest;
}
 
Example #9
Source File: HttpRequestOperationTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTransformStyxRequestToNettyRequestWithAllRelevantInformation() {
    LiveHttpRequest request = new LiveHttpRequest.Builder()
            .method(GET)
            .header("X-Forwarded-Proto", "https")
            .cookies(
                    requestCookie("HASESSION_V3", "asdasdasd"),
                    requestCookie("has", "123456789")
            )
            .uri("https://www.example.com/foo%2Cbar?foo,baf=2")
            .build();

    DefaultHttpRequest nettyRequest = HttpRequestOperation.toNettyRequest(request);
    assertThat(nettyRequest.method(), is(io.netty.handler.codec.http.HttpMethod.GET));
    assertThat(nettyRequest.uri(), is("https://www.example.com/foo%2Cbar?foo%2Cbaf=2"));
    assertThat(nettyRequest.headers().get("X-Forwarded-Proto"), is("https"));

    assertThat(ServerCookieDecoder.LAX.decode(nettyRequest.headers().get("Cookie")),
            containsInAnyOrder(
                    new DefaultCookie("HASESSION_V3", "asdasdasd"),
                    new DefaultCookie("has", "123456789")));

}
 
Example #10
Source File: HttpRequestOperationTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTransformUrlQueryParametersToNettyRequest() {
    LiveHttpRequest request = new LiveHttpRequest.Builder()
            .method(GET)
            .header("X-Forwarded-Proto", "https")
            .uri("https://www.example.com/foo?some=value&blah=blah")
            .build();

    LiveHttpRequest.Transformer builder = request.newBuilder();

    LiveHttpRequest newRequest = builder.url(
            request.url().newBuilder()
                    .addQueryParam("format", "json")
                    .build())
            .build();

    DefaultHttpRequest nettyRequest = HttpRequestOperation.toNettyRequest(newRequest);
    assertThat(nettyRequest.method(), is(io.netty.handler.codec.http.HttpMethod.GET));
    assertThat(nettyRequest.uri(), is("https://www.example.com/foo?some=value&blah=blah&format=json"));
    assertThat(nettyRequest.headers().get("X-Forwarded-Proto"), is("https"));
}
 
Example #11
Source File: RequestAdapter.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Configures the headers in the specified Netty HTTP request.
 */
private void addHeadersToRequest(DefaultHttpRequest httpRequest, SdkHttpRequest request) {
    httpRequest.headers().add(HOST, getHostHeaderValue(request));

    String scheme = request.getUri().getScheme();
    if (Protocol.HTTP2 == protocol && !StringUtils.isBlank(scheme)) {
        httpRequest.headers().add(ExtensionHeaderNames.SCHEME.text(), scheme);
    }

    // Copy over any other headers already in our request
    request.headers().entrySet().stream()
            /*
             * Skip the Host header to avoid sending it twice, which will
             * interfere with some signing schemes.
             */
            .filter(e -> !IGNORE_HEADERS.contains(e.getKey()))
            .forEach(e -> e.getValue().forEach(h -> httpRequest.headers().add(e.getKey(), h)));
}
 
Example #12
Source File: ExceptionHandlingHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void getRequestInfo_uses_dummy_instance_if_an_exception_occurs_while_creating_RequestInfo_from_HttpRequest_msg() {
    // given
    assertThat(state.getRequestInfo(), nullValue());

    RiposteHandlerInternalUtil explodingHandlerUtilMock = mock(RiposteHandlerInternalUtil.class);
    doThrow(new RuntimeException("intentional exception"))
        .when(explodingHandlerUtilMock)
        .createRequestInfoFromNettyHttpRequestAndHandleStateSetupIfNecessary(any(), any());

    Whitebox.setInternalState(handler, "handlerUtils", explodingHandlerUtilMock);

    HttpRequest httpRequest = new DefaultHttpRequest(
        HttpVersion.HTTP_1_1, HttpMethod.GET, "/some/uri"
    );

    // when
    RequestInfo<?> result = handler.getRequestInfo(state, httpRequest);

    // then
    assertThat(result.getUri(), is(RequestInfo.NONE_OR_UNKNOWN_TAG));
    verify(explodingHandlerUtilMock)
        .createRequestInfoFromNettyHttpRequestAndHandleStateSetupIfNecessary(httpRequest, state);
}
 
Example #13
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
private void doTestStatus(HttpResponseStatus status) {
	EmbeddedChannel channel = new EmbeddedChannel();
	HttpServerOperations ops = new HttpServerOperations(
			Connection.from(channel),
			ConnectionObserver.emptyListener(),
			null,
			new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"),
			null,
			ServerCookieEncoder.STRICT,
			ServerCookieDecoder.STRICT);
	ops.status(status);
	HttpMessage response = ops.newFullBodyMessage(Unpooled.EMPTY_BUFFER);
	assertThat(((FullHttpResponse) response).status().reasonPhrase()).isEqualTo(status.reasonPhrase());
	// "FutureReturnValueIgnored" is suppressed deliberately
	channel.close();
}
 
Example #14
Source File: WebWhoisProtocolsModuleTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that the client converts given {@link FullHttpRequest} to bytes, which is sent to the
 * server and reconstructed to a {@link FullHttpRequest} that is equivalent to the original. Then
 * test that the server converts given {@link FullHttpResponse} to bytes, which is sent to the
 * client and reconstructed to a {@link FullHttpResponse} that is equivalent to the original.
 *
 * <p>The request and response equivalences are tested in the same method because the client codec
 * tries to pair the response it receives with the request it sends. Receiving a response without
 * sending a request first will cause the {@link HttpObjectAggregator} to fail to aggregate
 * properly.
 */
private void requestAndRespondWithStatus(HttpResponseStatus status) {
  ByteBuf buffer;
  FullHttpRequest requestSent = makeHttpGetRequest(HOST, PATH);
  // Need to send a copy as the content read index will advance after the request is written to
  // the outbound of client channel, making comparison with requestReceived fail.
  assertThat(clientChannel.writeOutbound(requestSent.copy())).isTrue();
  buffer = clientChannel.readOutbound();
  assertThat(channel.writeInbound(buffer)).isTrue();
  // We only have a DefaultHttpRequest, not a FullHttpRequest because there is no HTTP aggregator
  // in the server's pipeline. But it is fine as we are not interested in the content (payload) of
  // the request, just its headers, which are contained in the DefaultHttpRequest.
  DefaultHttpRequest requestReceived = channel.readInbound();
  // Verify that the request received is the same as the request sent.
  assertHttpRequestEquivalent(requestSent, requestReceived);

  FullHttpResponse responseSent = makeHttpResponse(status);
  assertThat(channel.writeOutbound(responseSent.copy())).isTrue();
  buffer = channel.readOutbound();
  assertThat(clientChannel.writeInbound(buffer)).isTrue();
  FullHttpResponse responseReceived = clientChannel.readInbound();
  // Verify that the request received is the same as the request sent.
  assertHttpResponseEquivalent(responseSent, responseReceived);
}
 
Example #15
Source File: HttpHeadersImplTest.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
    HttpCarbonMessage httpCarbonMessage = new HttpCarbonMessage(
            new DefaultHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.GET, "msf4j"));
    httpCarbonMessage.getHeaders().add("testA", "test1");
    httpCarbonMessage.getHeaders().add("testA", "test2");
    httpCarbonMessage.setHeader("Accept", "application/json");
    httpCarbonMessage.setHeader("Content-Type", "text/html");
    httpCarbonMessage.setHeader("Content-Language", "en");
    httpCarbonMessage.setHeader("Content-Length", "1024");
    httpCarbonMessage.setHeader("Date", "Sun, 06 Nov 1994 08:49:37 GMT");
    httpCarbonMessage.getHeaders().add("Accept-Language", "da");
    httpCarbonMessage.getHeaders().add("Accept-Language", "en-gb;q=0.8");
    httpCarbonMessage.getHeaders().add("Accept-Language", "en;q=0.7");
    httpCarbonMessage.getHeaders().add("Cookie", "JSESSIONID=3508015E4EF0ECA8C4B761FCC4BC1718");
    httpHeaders1 = new HttpHeadersImpl(httpCarbonMessage.getHeaders());

    HttpCarbonMessage httpCarbonMessage2 = new HttpCarbonMessage(
            new DefaultHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.GET, "msf4j"));
    httpHeaders2 = new HttpHeadersImpl(httpCarbonMessage2.getHeaders());
}
 
Example #16
Source File: Http1FilterUnitTest.java    From xio with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeniedRule() throws UnknownHostException {
  List<Http1DeterministicRuleEngineConfig.Rule> blacklist = new ArrayList<>();
  HashMultimap<String, String> headers = HashMultimap.create();
  headers.put("User-Agent", "Bad-actor: 1.0");
  Http1DeterministicRuleEngineConfig.Rule bad =
      new Http1DeterministicRuleEngineConfig.Rule(
          HttpMethod.GET, "/path/to/failure", HttpVersion.HTTP_1_0, headers);
  blacklist.add(bad);
  Http1Filter http1Filter =
      new Http1Filter(new Http1FilterConfig(ImmutableList.copyOf(blacklist)));
  EmbeddedChannel chDeny = new EmbeddedChannel(http1Filter);
  DefaultHttpRequest request =
      new DefaultHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "/path/to/failure");
  request.headers().set("User-Agent", "Bad-actor: 1.0");
  chDeny.writeInbound(request);
  chDeny.runPendingTasks();
  assertFalse(chDeny.isActive());
  assertFalse(chDeny.isOpen());
}
 
Example #17
Source File: Http1FilterUnitTest.java    From xio with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllowedRule() throws UnknownHostException {
  List<Http1DeterministicRuleEngineConfig.Rule> blacklist = new ArrayList<>();
  HashMultimap<String, String> headers = HashMultimap.create();
  headers.put("User-Agent", "Bad-actor: 1.0");
  Http1DeterministicRuleEngineConfig.Rule bad =
      new Http1DeterministicRuleEngineConfig.Rule(
          HttpMethod.POST, "/path/to/failure", HttpVersion.HTTP_1_1, headers);
  blacklist.add(bad);
  Http1Filter http1Filter =
      new Http1Filter(new Http1FilterConfig(ImmutableList.copyOf(blacklist)));
  EmbeddedChannel chAllow = new EmbeddedChannel(http1Filter);
  DefaultHttpRequest request =
      new DefaultHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "/path/to/failure");
  request.headers().set("User-Agent", "Bad-actor: 1.0");
  chAllow.writeInbound(request);

  assertTrue(chAllow.isActive());
  assertTrue(chAllow.isOpen());
}
 
Example #18
Source File: ProtocolNegotiators.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
  negotiationLogger(ctx).log(ChannelLogLevel.INFO, "Http2Upgrade started");
  HttpClientCodec httpClientCodec = new HttpClientCodec();
  ctx.pipeline().addBefore(ctx.name(), null, httpClientCodec);

  Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(next);
  HttpClientUpgradeHandler upgrader =
      new HttpClientUpgradeHandler(httpClientCodec, upgradeCodec, /*maxContentLength=*/ 1000);
  ctx.pipeline().addBefore(ctx.name(), null, upgrader);

  // Trigger the HTTP/1.1 plaintext upgrade protocol by issuing an HTTP request
  // which causes the upgrade headers to be added
  DefaultHttpRequest upgradeTrigger =
      new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
  upgradeTrigger.headers().add(HttpHeaderNames.HOST, authority);
  ctx.writeAndFlush(upgradeTrigger).addListener(
      ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
  super.handlerAdded(ctx);
}
 
Example #19
Source File: NettyRequestTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link NettyRequest} with the given parameters.
 * @param httpMethod the {@link HttpMethod} desired.
 * @param uri the URI desired.
 * @param headers {@link HttpHeaders} that need to be a part of the request.
 * @param channel the {@link Channel} that the request arrived over.
 * @return {@link NettyRequest} encapsulating a {@link HttpRequest} with the given parameters.
 * @throws RestServiceException if the {@code httpMethod} is not recognized by {@link NettyRequest}.
 */
private NettyRequest createNettyRequest(HttpMethod httpMethod, String uri, HttpHeaders headers, Channel channel)
    throws RestServiceException {
  MetricRegistry metricRegistry = new MetricRegistry();
  RestRequestMetricsTracker.setDefaults(metricRegistry);
  HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri, false);
  if (headers != null) {
    httpRequest.headers().set(headers);
  }
  NettyRequest nettyRequest =
      new NettyRequest(httpRequest, channel, new NettyMetrics(metricRegistry), BLACKLISTED_QUERY_PARAM_SET);
  assertEquals("Auto-read is in an invalid state",
      (!httpMethod.equals(HttpMethod.POST) && !httpMethod.equals(HttpMethod.PUT))
          || NettyRequest.bufferWatermark <= 0, channel.config().isAutoRead());
  return nettyRequest;
}
 
Example #20
Source File: ClientCodecFunctionalTest.java    From xio with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncodeGet() {
  Request request =
      new Request(
          UUID.fromString("934bf16b-7d6f-4f8a-92ce-6d46affb933f"),
          SettableFuture.create(),
          SettableFuture.create());
  HttpRequest payload = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/path");

  Message message = new Message(request, payload);
  channel.writeOutbound(message);
  channel.runPendingTasks();

  ByteBuf expectedLength = Unpooled.copiedBuffer(hexToBytes("0042"));
  ByteBuf expectedEncoded =
      Unpooled.copiedBuffer(
          hexToBytes(
              "39333462663136622d376436662d346638612d393263652d3664343661666662393333660000000100000016474554202f7061746820485454502f312e310d0a0d0a"));

  ByteBuf length = (ByteBuf) channel.outboundMessages().poll();
  ByteBuf encoded = (ByteBuf) channel.outboundMessages().poll();

  assertTrue(
      "Expected: " + ByteBufUtil.hexDump(expectedLength),
      ByteBufUtil.equals(expectedLength, length));
  assertTrue(
      "Expected: " + ByteBufUtil.hexDump(expectedEncoded),
      ByteBufUtil.equals(expectedEncoded, encoded));
}
 
Example #21
Source File: Http1ClientCodec.java    From xio with Apache License 2.0 5 votes vote down vote up
HttpRequest buildRequest(Request request) {
  if (!request.headers().contains(HttpHeaderNames.CONTENT_TYPE)) {
    request.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
  }

  if (request.keepAlive()) {
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
  }

  if (request instanceof FullRequest) {
    FullRequest full = (FullRequest) request;
    ByteBuf content = full.body();
    if (content == null) {
      content = Unpooled.EMPTY_BUFFER;
    }
    if (!full.headers().contains(HttpHeaderNames.CONTENT_LENGTH)) {
      full.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
    }

    // Request request = getChannelRequest(ctx);

    // setChannelResponse(ctx, null);

    return new DefaultFullHttpRequest(
        HttpVersion.HTTP_1_1,
        full.method(),
        full.path(),
        content,
        full.headers().http1Headers(false, true),
        EmptyHttpHeaders.INSTANCE);
  } else {
    // TODO(CK): TransferEncoding
    return new DefaultHttpRequest(
        HttpVersion.HTTP_1_1,
        request.method(),
        request.path(),
        request.headers().http1Headers(false, true));
  }
}
 
Example #22
Source File: ArmeriaHttpUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void addHostHeaderIfMissing() throws URISyntaxException {
    final io.netty.handler.codec.http.HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(HttpHeaderNames.HOST, "bar");

    final HttpRequest originReq =
            new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello", headers);

    final InetSocketAddress socketAddress = new InetSocketAddress(36462);
    final Channel channel = mock(Channel.class);
    when(channel.localAddress()).thenReturn(socketAddress);

    final ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.channel()).thenReturn(channel);

    RequestHeaders armeriaHeaders = toArmeria(ctx, originReq, serverConfig());
    assertThat(armeriaHeaders.get(HttpHeaderNames.HOST)).isEqualTo("bar");
    assertThat(armeriaHeaders.authority()).isEqualTo("bar");

    final HttpRequest absoluteUriReq =
            new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                                   "http://example.com/hello", headers);
    armeriaHeaders = toArmeria(ctx, absoluteUriReq, serverConfig());
    assertThat(armeriaHeaders.get(HttpHeaderNames.HOST)).isEqualTo("bar");
    assertThat(armeriaHeaders.authority()).isEqualTo("bar");

    // Remove Host header.
    headers.remove(HttpHeaderNames.HOST);
    armeriaHeaders = toArmeria(ctx, originReq, serverConfig());
    assertThat(armeriaHeaders.get(HttpHeaderNames.HOST)).isEqualTo("foo:36462"); // The default hostname.
    assertThat(armeriaHeaders.authority()).isEqualTo("foo:36462");

    armeriaHeaders = toArmeria(ctx, absoluteUriReq, serverConfig());
    assertThat(armeriaHeaders.get(HttpHeaderNames.HOST)).isEqualTo("example.com");
    assertThat(armeriaHeaders.authority()).isEqualTo("example.com");
}
 
Example #23
Source File: TraceableHttpServerRequestTest.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setUp() throws IOException {
    HttpCarbonMessage httpCarbonMessage = new HttpCarbonMessage(
            new DefaultHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.GET, "msf4j"));
    httpCarbonMessage.setHeader("testK", "testV");
    httpCarbonMessage.setHttpMethod(HttpMethod.GET);
    request = new Request(httpCarbonMessage);
    request.setProperty("TO", "msf4j");
    httpServerRequest = new TraceableHttpServerRequest(request);
}
 
Example #24
Source File: ExceptionHandlingHandlerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void getRequestInfo_creates_new_RequestInfo_based_on_msg_if_state_requestInfo_is_null_and_msg_is_a_HttpRequest() {
    // given
    assertThat(state.getRequestInfo(), nullValue());
    String expectedUri = "/some/uri/" + UUID.randomUUID().toString();
    HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, expectedUri);

    // when
    RequestInfo<?> result = handler.getRequestInfo(state, httpRequest);

    // then
    assertThat(result.getUri(), is(expectedUri));
}
 
Example #25
Source File: StreamingAsyncHttpClientTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
        "80   | false | localhost | localhost",
        "80   | true  | localhost | localhost:80",
        "8080 | false | localhost | localhost:8080",
        "443  | true  | localhost | localhost",
        "443  | false | localhost | localhost:443",
        "8080 | true  | localhost | localhost:8080",
}, splitBy = "\\|")
@Test
public void streamDownstreamCall_setsHostHeaderCorrectly(int downstreamPort, boolean isSecure, String downstreamHost, String expectedHostHeader) {
    // given
    DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
    ChannelHandlerContext ctx = mockChannelHandlerContext();
    StreamingCallback streamingCallback = mock(StreamingCallback.class);

    ProxyRouterProcessingState proxyState = ChannelAttributes.getProxyRouterProcessingStateForChannel(ctx).get();
    RequestInfo<?> requestInfoMock = mock(RequestInfo.class);

    // when
    new StreamingAsyncHttpClient(
        200, 200, true, mock(DistributedTracingConfig.class)
    ).streamDownstreamCall(
        downstreamHost, downstreamPort, request, isSecure, false, streamingCallback, 200, true, true,
        proxyState, requestInfoMock, ctx
    );

    // then
    assertThat(request.headers().get(HOST)).isEqualTo(expectedHostHeader);
}
 
Example #26
Source File: ProtocolNegotiators.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void channelActive(ChannelHandlerContext ctx) throws Exception {
  // Trigger the HTTP/1.1 plaintext upgrade protocol by issuing an HTTP request
  // which causes the upgrade headers to be added
  DefaultHttpRequest upgradeTrigger =
      new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
  ctx.writeAndFlush(upgradeTrigger);
  super.channelActive(ctx);
}
 
Example #27
Source File: HttpUploadHandler.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private HttpRequest buildRequest(UploadCommand msg) {
  HttpRequest request =
      new DefaultHttpRequest(
          HttpVersion.HTTP_1_1,
          HttpMethod.PUT,
          constructPath(msg.uri(), msg.hash(), msg.casUpload()));
  request.headers().set(HttpHeaderNames.HOST, constructHost(msg.uri()));
  request.headers().set(HttpHeaderNames.ACCEPT, "*/*");
  request.headers().set(HttpHeaderNames.CONTENT_LENGTH, msg.contentLength());
  request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
  return request;
}
 
Example #28
Source File: WebSocketExtensionTestUtil.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static HttpRequest newUpgradeRequest(String ext) {
    HttpRequest req = new DefaultHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.GET, "/chat");

    req.headers().set(HttpHeaderNames.HOST, "server.example.com");
    req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET.toString().toLowerCase());
    req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
    req.headers().set(HttpHeaderNames.ORIGIN, "http://example.com");
    if (ext != null) {
        req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS, ext);
    }

    return req;
}
 
Example #29
Source File: NettyToStyxRequestDecoderTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
    channel = createEmbeddedChannel(newHttpRequestDecoderWithFlowControl());
    chunkedRequestHeaders = new DefaultHttpRequest(HTTP_1_1, POST, "/foo/bar");
    chunkedRequestHeaders.headers().set(TRANSFER_ENCODING, CHUNKED);
    chunkedRequestHeaders.headers().set(HOST, "foo.com");
    bodyCompletedLatch = new CountDownLatch(1);
}
 
Example #30
Source File: RiposteHandlerInternalUtilTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    implSpy = spy(new RiposteHandlerInternalUtil());
    stateSpy = spy(new HttpProcessingState());
    nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PATCH, "/some/uri");

    resetTracingAndMdc();
}