Java Code Examples for io.netty.handler.codec.http.HttpVersion#HTTP_1_0

The following examples show how to use io.netty.handler.codec.http.HttpVersion#HTTP_1_0 . 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: 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 2
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 3
Source File: RecordedHttpResponseBuilderTest.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testBuild()
    throws IOException {
  HttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.GATEWAY_TIMEOUT);
  RecordedHttpResponseBuilder recordedHttpResponseBuilder = new RecordedHttpResponseBuilder(httpResponse);

  String charset = "UTF-8";
  String str1 = "Hello world";
  HttpContent httpContent1 = new DefaultHttpContent(Unpooled.copiedBuffer(str1.getBytes(charset)));
  recordedHttpResponseBuilder.appendHttpContent(httpContent1);
  String str2 = "second content";
  HttpContent httpContent2 = new DefaultHttpContent(Unpooled.copiedBuffer(str2.getBytes(charset)));
  recordedHttpResponseBuilder.appendHttpContent(httpContent2);

  String lastStr = "Last chunk";
  HttpContent lastContent = new DefaultLastHttpContent(Unpooled.copiedBuffer(lastStr.getBytes(charset)));
  recordedHttpResponseBuilder.appendHttpContent(lastContent);
  RecordedHttpResponse recordedHttpResponse = recordedHttpResponseBuilder.build();
  Assert.assertEquals(recordedHttpResponse.getStatus(), HttpResponseStatus.GATEWAY_TIMEOUT.code());
  Assert.assertEquals((str1 + str2 + lastStr).getBytes(charset),
      recordedHttpResponse.getHttpBody().getContent(charset));
}
 
Example 4
Source File: RecordedHttpRequestBuilderTest.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testBuildContent()
    throws Exception {
  HttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "www.google.com");
  RecordedHttpRequestBuilder recordedHttpRequestBuilder = new RecordedHttpRequestBuilder(nettyRequest);

  String charset = "UTF-8";
  String str1 = "first content";
  HttpContent httpContent1 = new DefaultHttpContent(Unpooled.copiedBuffer(str1.getBytes(charset)));
  recordedHttpRequestBuilder.appendHttpContent(httpContent1);
  String str2 = "second content";
  HttpContent httpContent2 = new DefaultHttpContent(Unpooled.copiedBuffer(str2.getBytes(charset)));
  recordedHttpRequestBuilder.appendHttpContent(httpContent2);

  String lastStr = "Last chunk";
  HttpContent lastContent = new DefaultLastHttpContent(Unpooled.copiedBuffer(lastStr.getBytes(charset)));
  recordedHttpRequestBuilder.appendHttpContent(lastContent);

  RecordedHttpRequest recordedHttpRequest = recordedHttpRequestBuilder.build();
  Assert
      .assertEquals((str1 + str2 + lastStr).getBytes(charset), recordedHttpRequest.getHttpBody().getContent(charset));
}
 
Example 5
Source File: Http1FilterConfigUnitTest.java    From xio with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdater() throws UnknownHostException {
  ThriftMarshaller marshaller = new ThriftMarshaller();

  Http1DeterministicRuleEngineConfig rules = new Http1DeterministicRuleEngineConfig();

  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);

  rules.blacklistRule(bad);

  Http1FilterConfig.Updater updater =
      new Http1FilterConfig.Updater("path", this::setHttp1FilterConfig);
  updater.update(marshaller.marshall(rules));
  Http1FilterConfig expected = new Http1FilterConfig(rules.getBlacklistRules());

  assertEquals(expected, config);
}
 
Example 6
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void sendDecodingFailures(ChannelHandlerContext ctx, Throwable t, Object msg) {
	Throwable cause = t.getCause() != null ? t.getCause() : t;

	if (log.isDebugEnabled()) {
		log.debug(format(ctx.channel(), "Decoding failed: " + msg + " : "), cause);
	}

	ReferenceCountUtil.release(msg);

	HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0,
			cause instanceof TooLongFrameException ? HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE:
			                                         HttpResponseStatus.BAD_REQUEST);
	response.headers()
	        .setInt(HttpHeaderNames.CONTENT_LENGTH, 0)
	        .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
	ctx.writeAndFlush(response)
	   .addListener(ChannelFutureListener.CLOSE);
}
 
Example 7
Source File: HttpUtilsTest.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
@Test(groups = { "unit" })
public void verifyConversionOfHttpResponseHeadersToMap() throws UnsupportedEncodingException {
    HttpHeaders headersMap = new DefaultHttpHeaders();
    headersMap.add(HttpConstants.HttpHeaders.OWNER_FULL_NAME, OWNER_FULL_NAME_VALUE);

    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_0,
            HttpResponseStatus.ACCEPTED,
            headersMap);
    HttpResponseHeaders httpResponseHeaders = new HttpClientResponse(httpResponse, null).getHeaders();
    Set<Entry<String, String>> resultHeadersSet = HttpUtils.asMap(httpResponseHeaders).entrySet();
    
    assertThat(resultHeadersSet.size()).isEqualTo(1);
    Entry<String, String> entry = resultHeadersSet.iterator().next();
    assertThat(entry.getKey()).isEqualTo(HttpConstants.HttpHeaders.OWNER_FULL_NAME);
    assertThat(entry.getValue()).isEqualTo(HttpUtils.urlDecode(OWNER_FULL_NAME_VALUE));
    
    List<Entry<String, String>> resultHeadersList = HttpUtils.unescape(httpResponseHeaders.entries());
    assertThat(resultHeadersList.size()).isEqualTo(1);
    entry = resultHeadersSet.iterator().next();
    assertThat(entry.getKey()).isEqualTo(HttpConstants.HttpHeaders.OWNER_FULL_NAME);
    assertThat(entry.getValue()).isEqualTo(HttpUtils.urlDecode(OWNER_FULL_NAME_VALUE));
}
 
Example 8
Source File: HttpJsonProtocolTest.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeHttpRequest() {
    ServiceManager serviceManager = ServiceManager.getInstance();
    serviceManager.registerService(new HelloWorldServiceImpl(), null);
    ByteBuf content = Unpooled.wrappedBuffer(new Gson().toJson("hello").getBytes());

    FullHttpRequest fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET,
            "/HelloWorldService/hello?k=v", content);
    fullHttpRequest.headers().set("log-id", 1);
    fullHttpRequest.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8");

    Request request = protocol.decodeRequest(fullHttpRequest);

    assertEquals("HelloWorldService", request.getRpcMethodInfo().getServiceName());
    assertEquals("hello", request.getRpcMethodInfo().getMethodName());
    assertEquals(HelloWorldService.class.getMethods()[0], request.getTargetMethod());
    assertEquals(HelloWorldServiceImpl.class, request.getTarget().getClass());
}
 
Example 9
Source File: InterceptorConstraintTestBase.java    From karyon with Apache License 2.0 5 votes vote down vote up
protected static boolean doApply(InterceptorKey<HttpServerRequest<ByteBuf>, HttpKeyEvaluationContext> key, String uri,
                                 HttpMethod httpMethod) {
    DefaultHttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, httpMethod, uri);
    return key.apply(new HttpServerRequest<ByteBuf>(nettyRequest,
                                                    UnicastContentSubject.<ByteBuf>createWithoutNoSubscriptionTimeout()),
                     new HttpKeyEvaluationContext(new MockChannelHandlerContext("mock").channel()));
}
 
Example 10
Source File: RequestInfoImpl.java    From riposte with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized @Nullable List<InterfaceHttpData> getMultipartParts() {
    if (!isMultipartRequest() || !isCompleteRequestWithAllChunks())
        return null;

    if (multipartData == null) {
        byte[] contentBytes = getRawContentBytes();
        HttpVersion httpVersion = getProtocolVersion();
        HttpMethod httpMethod = getMethod();
        // HttpVersion and HttpMethod cannot be null because DefaultFullHttpRequest doesn't allow them to be
        //      null, but our getProtocolVersion() and getMethod() methods might return null (i.e. due to an
        //      invalid request). They shouldn't be null in practice by the time this getMultipartParts() method
        //      is called, but since they don't seem to be used by the Netty code we delegate to, we can just
        //      default them to something if null somehow slips through.
        if (httpVersion == null) {
            httpVersion = HttpVersion.HTTP_1_0;
        }

        if (httpMethod == null) {
            httpMethod = HttpMethod.POST;
        }

        HttpRequest fullHttpRequestForMultipartDecoder =
            (contentBytes == null)
            ? new DefaultFullHttpRequest(httpVersion, httpMethod, getUri())
            : new DefaultFullHttpRequest(httpVersion, httpMethod, getUri(),
                                         Unpooled.wrappedBuffer(contentBytes));

        fullHttpRequestForMultipartDecoder.headers().add(getHeaders());

        multipartData = new HttpPostMultipartRequestDecoder(
            new DefaultHttpDataFactory(false), fullHttpRequestForMultipartDecoder, getContentCharset()
        );
    }

    return multipartData.getBodyHttpDatas();
}
 
Example 11
Source File: RecordedHttpRequestBuilderTest.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testBuildHttpMethod() {
  HttpRequest nettyRequest =
      new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "http://www.google.com");
  RecordedHttpRequestBuilder recordedHttpRequestBuilder = new RecordedHttpRequestBuilder(nettyRequest);
  RecordedHttpRequest recordedHttpRequest = recordedHttpRequestBuilder.build();
  Assert.assertEquals(recordedHttpRequest.getMethod(), HttpMethod.GET.toString());
}
 
Example 12
Source File: HttpRequestInfo.java    From pdown-core with MIT License 5 votes vote down vote up
@Override
public HttpVersion protocolVersion() {
  if (version == HttpVer.HTTP_1_0) {
    return HttpVersion.HTTP_1_0;
  } else {
    return HttpVersion.HTTP_1_1;
  }
}
 
Example 13
Source File: RecordedHttpRequestBuilderTest.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testBuildRelativeUri() {
  String uri = "finance";
  HttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, uri);
  nettyRequest.headers().set(HttpHeaders.Names.HOST, "www.google.com/");
  RecordedHttpRequestBuilder recordedHttpRequestBuilder = new RecordedHttpRequestBuilder(nettyRequest);
  RecordedHttpRequest recordedHttpRequest = recordedHttpRequestBuilder.build();
  Assert.assertEquals(recordedHttpRequest.getUri().toString(), "https://www.google.com/finance");
}
 
Example 14
Source File: RecordedHttpRequestBuilderTest.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test(expectedExceptions = IllegalStateException.class)
public void testBuildWithUnsupportedUri() {
  String uri = "http://example.com/file[/].html";
  HttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, uri);
  RecordedHttpRequestBuilder recordedHttpRequestBuilder = new RecordedHttpRequestBuilder(nettyRequest);
  recordedHttpRequestBuilder.build();
}
 
Example 15
Source File: RecordedHttpRequestBuilderTest.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testBuildWithUriTwoLegs() {
  HttpRequest nettyRequest1 = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "finance");
  RecordedHttpRequestBuilder recordedHttpRequestBuilder = new RecordedHttpRequestBuilder(nettyRequest1);
  HttpRequest nettyRequest2 = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "google.com");
  nettyRequest2.headers().set(HttpHeaders.Names.HOST, "www.google.com/");
  recordedHttpRequestBuilder.addHeaders(nettyRequest2);
  RecordedHttpRequest recordedHttpRequest = recordedHttpRequestBuilder.build();
  Assert.assertEquals(recordedHttpRequest.getUri().toString(), "https://www.google.com/finance");
}
 
Example 16
Source File: RecordedHttpRequestBuilderTest.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test(expectedExceptions = IllegalStateException.class)
public void testBuildWithUriTwoLegsIllegalUri() {
  HttpRequest nettyRequest1 = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "file[/].html");
  RecordedHttpRequestBuilder recordedHttpRequestBuilder = new RecordedHttpRequestBuilder(nettyRequest1);
  HttpRequest nettyRequest2 = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "google.com");
  nettyRequest2.headers().set(HttpHeaders.Names.HOST, "www.google.com/");
  recordedHttpRequestBuilder.addHeaders(nettyRequest2);
  recordedHttpRequestBuilder.build();
}
 
Example 17
Source File: HttpRequestInfo.java    From proxyee-down with Apache License 2.0 5 votes vote down vote up
@Override
public HttpVersion protocolVersion() {
  if (version == HttpVer.HTTP_1_0) {
    return HttpVersion.HTTP_1_0;
  } else {
    return HttpVersion.HTTP_1_1;
  }
}
 
Example 18
Source File: ThriftUnmarshaller.java    From xio with Apache License 2.0 5 votes vote down vote up
private static HttpVersion build(Http1Version version) {
  if (version != null) {
    switch (version) {
      case HTTP_1_0:
        return HttpVersion.HTTP_1_0;
      case HTTP_1_1:
        return HttpVersion.HTTP_1_1;
    }
  }
  return null;
}
 
Example 19
Source File: ZooKeeperWriteProviderFunctionalTest.java    From xio with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteHttp1DeterministicRuleEngineConfig() throws Exception {
  try (TestingServer server = new TestingServer()) {
    server.start();

    Http1DeterministicRuleEngineConfig config = new Http1DeterministicRuleEngineConfig();

    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);
    Http1DeterministicRuleEngineConfig.Rule good =
        new Http1DeterministicRuleEngineConfig.Rule(null, null, null, null);
    config.blacklistRule(bad);
    config.whitelistRule(good);

    ThriftMarshaller marshaller = new ThriftMarshaller();
    RetryPolicy retryPolicy = new RetryOneTime(1);
    try (CuratorFramework client =
        CuratorFrameworkFactory.newClient(server.getConnectString(), retryPolicy)) {
      client.start();
      String path = "/some/path/to/nodes/http1Rules";

      ZooKeeperWriteProvider provider = new ZooKeeperWriteProvider(marshaller, client);

      provider.write(path, config);

      byte[] data = client.getData().forPath(path);
      ThriftUnmarshaller unmarshaller = new ThriftUnmarshaller();
      Http1DeterministicRuleEngineConfig read = new Http1DeterministicRuleEngineConfig();
      unmarshaller.unmarshall(read, data);

      assertEquals(config, read);
    }
  }
}
 
Example 20
Source File: BrpcHttpObjectDecoder.java    From brpc-java with Apache License 2.0 4 votes vote down vote up
@Override
protected HttpMessage createInvalidMessage() {
    return isDecodingRequest() ?
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "/bad-request", validateHeaders) :
            new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, UNKNOWN_STATUS, validateHeaders);
}