com.linecorp.armeria.common.RequestHeaders Java Examples

The following examples show how to use com.linecorp.armeria.common.RequestHeaders. 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: ContentServiceV1Test.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Test
void renameFile() {
    final WebClient client = dogma.httpClient();
    addFooJson(client);
    final String body =
            '{' +
            "   \"path\" : \"/foo.json\"," +
            "   \"type\" : \"RENAME\"," +
            "   \"content\" : \"/bar.json\"," +
            "   \"commitMessage\" : {" +
            "       \"summary\" : \"Rename foo.json\"," +
            "       \"detail\": \"Rename to bar.json\"," +
            "       \"markup\": \"PLAINTEXT\"" +
            "   }" +
            '}';
    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, CONTENTS_PREFIX,
                                                     HttpHeaderNames.CONTENT_TYPE, MediaType.JSON);
    final AggregatedHttpResponse aRes = client.execute(headers, body).aggregate().join();
    final String expectedJson =
            '{' +
            "   \"revision\": 3," +
            "   \"pushedAt\": \"${json-unit.ignore}\"" +
            '}';
    final String actualJson = aRes.contentUtf8();
    assertThatJson(actualJson).isEqualTo(expectedJson);
}
 
Example #2
Source File: RouteDecoratingTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@CsvSource({
        "/,                       headers-decorator,  headers-decorator",
        "/,                       headers-service,    headers-service",
        "/?dest=params-decorator, ,                   params-decorator",
        "/?dest=params-service,   ,                   params-service"
})
void decoratorShouldWorkWithMatchingHeadersAndParams(String path,
                                                     @Nullable String destHeader,
                                                     String result) {
    final WebClient client = WebClient.of(headersAndParamsExpectingServer.httpUri());
    final RequestHeadersBuilder builder = RequestHeaders.builder().method(HttpMethod.GET).path(path);
    if (!Strings.isNullOrEmpty(destHeader)) {
        builder.add("dest", destHeader);
    }
    assertThat(client.execute(builder.build()).aggregate().join().contentUtf8()).isEqualTo(result);
}
 
Example #3
Source File: LoggingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void sanitizeRequestHeaders() throws Exception {
    final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.POST, "/hello/trustin",
                                                             HttpHeaderNames.SCHEME, "http",
                                                             HttpHeaderNames.AUTHORITY, "test.com"));

    final ClientRequestContext ctx = ClientRequestContext.of(req);

    // use default logger
    final LoggingClient defaultLoggerClient =
            LoggingClient.builder()
                         .requestLogLevel(LogLevel.INFO)
                         .successfulResponseLogLevel(LogLevel.INFO)
                         .requestHeadersSanitizer(RegexBasedSanitizer.of(
                                 Pattern.compile("trustin"),
                                 Pattern.compile("com")))
                         .build(delegate);

    // Pre sanitize step
    assertThat(ctx.logBuilder().toString()).contains("trustin");
    assertThat(ctx.logBuilder().toString()).contains("test.com");
    defaultLoggerClient.execute(ctx, req);
    // After the sanitize
    assertThat(ctx.logBuilder().toString()).doesNotContain("trustin");
    assertThat(ctx.logBuilder().toString()).doesNotContain("com");
}
 
Example #4
Source File: ProjectServiceV1Test.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Test
void unremoveProject() {
    final WebClient client = dogma.httpClient();
    createProject(client, "bar");

    final String projectPath = PROJECTS_PREFIX + "/bar";
    client.delete(projectPath).aggregate().join();

    final RequestHeaders headers = RequestHeaders.of(HttpMethod.PATCH, projectPath,
                                                     HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_PATCH);

    final String unremovePatch = "[{\"op\":\"replace\",\"path\":\"/status\",\"value\":\"active\"}]";
    final AggregatedHttpResponse aRes = client.execute(headers, unremovePatch).aggregate().join();
    assertThat(ResponseHeaders.of(aRes.headers()).status()).isEqualTo(HttpStatus.OK);
    final String expectedJson =
            '{' +
            "   \"name\": \"bar\"," +
            "   \"creator\": {" +
            "       \"name\": \"System\"," +
            "       \"email\": \"[email protected]\"" +
            "   }," +
            "   \"url\": \"/api/v1/projects/bar\"," +
            "   \"createdAt\": \"${json-unit.ignore}\"" +
            '}';
    assertThatJson(aRes.contentUtf8()).isEqualTo(expectedJson);
}
 
Example #5
Source File: HealthCheckedEndpointGroupAuthorityTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@CsvSource({
        // Host name only
        "localhost, localhost",
        "localhost:1, localhost:1",
        "localhost:80, localhost",
        // IPv4 address only
        "127.0.0.1, 127.0.0.1",
        "127.0.0.1:1, 127.0.0.1:1",
        "127.0.0.1:80, 127.0.0.1",
        // IPv6 address only
        "[::1], [::1]",
        "[::1]:1, [::1]:1",
        "[::1]:80, [::1]"
})
void hostOnlyOrIpAddrOnly(String endpoint, String expectedAuthority) throws Exception {
    try (HealthCheckedEndpointGroup ignored = build(Endpoint.parse(endpoint))) {
        final RequestHeaders log = logs.take();
        assertThat(log.authority()).isEqualTo(expectedAuthority);
    }
}
 
Example #6
Source File: ContentServiceV1Test.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static AggregatedHttpResponse addBarTxt(WebClient client) {
    final String body =
            '{' +
            "   \"path\" : \"/a/bar.txt\"," +
            "   \"type\" : \"UPSERT_TEXT\"," +
            "   \"content\" : \"text in the file.\\n\"," +
            "   \"commitMessage\" : {" +
            "       \"summary\" : \"Add bar.txt\"," +
            "       \"detail\": \"Add because we need it.\"," +
            "       \"markup\": \"PLAINTEXT\"" +
            "   }" +
            '}';
    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, CONTENTS_PREFIX,
                                                     HttpHeaderNames.CONTENT_TYPE, MediaType.JSON);
    return client.execute(headers, body).aggregate().join();
}
 
Example #7
Source File: AnnotatedServiceRequestConverterTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testRedundantlyUsedParameters() throws Exception {
    final WebClient client = WebClient.of(server.httpUri());
    final ObjectMapper mapper = new ObjectMapper();
    final RequestBean4 expectedRequestBean = new RequestBean4(100);
    expectedRequestBean.foo2 = 100;
    expectedRequestBean.foo3 = 200;
    final String expectedResponseContent = mapper.writeValueAsString(expectedRequestBean);

    final RequestHeaders reqHeaders = RequestHeaders.of(HttpMethod.GET, "/2/default/bean4?foo=100",
                                                        HttpHeaderNames.of("foo"), 200);

    final AggregatedHttpResponse response = client.execute(reqHeaders).aggregate().join();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);
    assertThat(response.contentUtf8()).isEqualTo(expectedResponseContent);
}
 
Example #8
Source File: JettyService.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static MetaData.Request toRequestMetadata(ServiceRequestContext ctx, AggregatedHttpRequest aReq) {
    // Construct the HttpURI
    final StringBuilder uriBuf = new StringBuilder();
    final RequestHeaders aHeaders = aReq.headers();

    uriBuf.append(ctx.sessionProtocol().isTls() ? "https" : "http");
    uriBuf.append("://");
    uriBuf.append(aHeaders.authority());
    uriBuf.append(aHeaders.path());

    final HttpURI uri = new HttpURI(uriBuf.toString());
    uri.setPath(ctx.mappedPath());

    // Convert HttpHeaders to HttpFields
    final HttpFields jHeaders = new HttpFields(aHeaders.size());
    aHeaders.forEach(e -> {
        final AsciiString key = e.getKey();
        if (!key.isEmpty() && key.byteAt(0) != ':') {
            jHeaders.add(key.toString(), e.getValue());
        }
    });

    return new MetaData.Request(aHeaders.get(HttpHeaderNames.METHOD), uri,
                                HttpVersion.HTTP_1_1, jHeaders, aReq.content().length());
}
 
Example #9
Source File: StorageClient.java    From curiostack with MIT License 6 votes vote down vote up
public CompletableFuture<Void> delete(String filename) {
  String url = objectUrlPrefix + urlPathSegmentEscaper().escape(filename);
  RequestHeaders headers =
      RequestHeaders.builder(HttpMethod.DELETE, url).contentType(MediaType.JSON_UTF_8).build();
  return httpClient
      .execute(headers)
      .aggregate()
      .handle(
          (msg, t) -> {
            if (t != null) {
              throw new RuntimeException("Unexpected error deleting file.", t);
            }
            if (msg.status().codeClass().equals(HttpStatusClass.SUCCESS)) {
              return null;
            } else {
              throw new IllegalStateException(
                  "Could not delete file at " + url + ": " + msg.content().toStringUtf8());
            }
          });
}
 
Example #10
Source File: DefaultHttpRequestTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void ignoresAfterTrailersIsWritten() {
    final HttpRequestWriter req = HttpRequest.streaming(HttpMethod.GET, "/foo");
    req.write(HttpData.ofUtf8("foo"));
    req.write(HttpHeaders.of(HttpHeaderNames.of("a"), "b"));
    req.write(HttpHeaders.of(HttpHeaderNames.of("c"), "d")); // Ignored.
    req.close();

    final AggregatedHttpRequest aggregated = req.aggregate().join();
    // Request headers
    assertThat(aggregated.headers()).isEqualTo(
            RequestHeaders.of(HttpMethod.GET, "/foo",
                              HttpHeaderNames.CONTENT_LENGTH, "3"));
    // Content
    assertThat(aggregated.contentUtf8()).isEqualTo("foo");
    // Trailers
    assertThat(aggregated.trailers()).isEqualTo(HttpHeaders.of(HttpHeaderNames.of("a"), "b"));
}
 
Example #11
Source File: LoggingServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void sanitizeRequestContent() throws Exception {

    final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.POST, "/hello/trustin",
                                                             HttpHeaderNames.SCHEME, "http",
                                                             HttpHeaderNames.AUTHORITY, "test.com"));

    final ServiceRequestContext ctx = ServiceRequestContext.of(req);
    ctx.logBuilder().requestContent("Virginia 333-490-4499", "Virginia 333-490-4499");
    final Logger logger = LoggingTestUtil.newMockLogger(ctx, capturedCause);
    when(logger.isInfoEnabled()).thenReturn(true);

    final LoggingService service =
            LoggingService.builder()
                          .logger(logger)
                          .requestLogLevel(LogLevel.INFO)
                          .successfulResponseLogLevel(LogLevel.INFO)
                          .requestContentSanitizer(RegexBasedSanitizer.of(
                                                   Pattern.compile("\\d{3}[-.\\s]\\d{3}[-.\\s]\\d{4}")))
                          .newDecorator().apply(delegate);

    assertThat(ctx.logBuilder().toString()).contains("333-490-4499");
    service.serve(ctx, ctx.request());
    assertThat(ctx.logBuilder().toString()).doesNotContain("333-490-4499");
}
 
Example #12
Source File: EncodingService.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance.
 */
EncodingService(HttpService delegate,
                Predicate<MediaType> encodableContentTypePredicate,
                Predicate<? super RequestHeaders> encodableRequestHeadersPredicate,
                long minBytesToForceChunkedAndEncoding) {
    super(delegate);
    this.encodableContentTypePredicate = encodableContentTypePredicate;
    this.encodableRequestHeadersPredicate = encodableRequestHeadersPredicate;
    this.minBytesToForceChunkedAndEncoding = minBytesToForceChunkedAndEncoding;
}
 
Example #13
Source File: ArmeriaSpringActuatorAutoConfigurationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testOptions() {
    final HttpRequest req = HttpRequest.of(RequestHeaders.of(
            HttpMethod.OPTIONS, "/internal/actuator/health",
            HttpHeaderNames.ORIGIN, "https://example.com",
            HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD, "GET"));
    final AggregatedHttpResponse res = client.execute(req).aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN))
            .isEqualTo("https://example.com");
    assertThat(res.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS))
            .isEqualTo("GET,POST");
    assertThat(res.headers().contains(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE)).isTrue();
    assertThat(res.status()).isNotEqualTo(HttpStatus.METHOD_NOT_ALLOWED);
}
 
Example #14
Source File: ArmeriaServerHttpRequestTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void readBodyStream() {
    final HttpRequest httpRequest =
            HttpRequest.of(RequestHeaders.builder(HttpMethod.POST, "/")
                                         .scheme("http")
                                         .authority("127.0.0.1")
                                         .build(),
                           Flux.just("a", "b", "c", "d", "e").map(HttpData::ofUtf8));

    final ServiceRequestContext ctx = newRequestContext(httpRequest);
    final ArmeriaServerHttpRequest req = request(ctx);
    assertThat(req.initId()).isEqualTo(ctx.id().toString());
    assertThat(req.getMethodValue()).isEqualTo(HttpMethod.POST.name());
    assertThat(req.<Object>getNativeRequest()).isInstanceOf(HttpRequest.class).isEqualTo(httpRequest);

    assertThat(httpRequest.whenComplete().isDone()).isFalse();

    final Flux<String> body = req.getBody().map(TestUtil::bufferToString);
    StepVerifier.create(body, 1)
                .expectNext("a").thenRequest(1)
                .expectNext("b").thenRequest(1)
                .expectNext("c").thenRequest(1)
                .expectNext("d").thenRequest(1)
                .expectNext("e").thenRequest(1)
                .expectComplete()
                .verify();

    await().until(() -> httpRequest.whenComplete().isDone());
}
 
Example #15
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testPooledResponseDefaultSubscriber() throws Exception {
    final WebClient client = WebClient.of(server.httpUri());

    final AggregatedHttpResponse response = client.execute(
            RequestHeaders.of(HttpMethod.GET, "/pooled")).aggregate().get();

    assertThat(response.status()).isEqualTo(HttpStatus.OK);
    assertThat(response.contentUtf8()).isEqualTo("pooled content");
    await().untilAsserted(() -> assertThat(releasedByteBuf.get().refCnt()).isZero());
}
 
Example #16
Source File: ContentPreviewingServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void contentPreviewBeforeEncoding() {
    final WebClient client = WebClient.builder(server.httpUri())
                                      .decorator(DecodingClient.newDecorator())
                                      .build();
    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, "/beforeEncoding",
                                                     HttpHeaderNames.CONTENT_TYPE, "text/plain");
    assertThat(client.execute(headers, "Armeria").aggregate().join().contentUtf8())
            .isEqualTo("Hello Armeria!");
    final RequestLog requestLog = contextCaptor.get().log().whenComplete().join();
    assertThat(requestLog.requestContentPreview()).isEqualTo("Armeria");
    assertThat(requestLog.responseContentPreview()).isEqualTo("Hello Armeria!");
}
 
Example #17
Source File: StorageClient.java    From curiostack with MIT License 5 votes vote down vote up
/** Create a new file for uploading data to cloud storage. */
public CompletableFuture<FileWriter> createFile(
    FileRequest request, EventLoop eventLoop, ByteBufAllocator alloc) {
  HttpData data = serializeRequest(request, alloc);

  RequestHeaders headers =
      RequestHeaders.builder(HttpMethod.POST, uploadUrl)
          .contentType(MediaType.JSON_UTF_8)
          .build();
  HttpResponse res = httpClient.execute(headers, data);
  return res.aggregate(eventLoop)
      .handle(
          (msg, t) -> {
            if (t != null) {
              throw new RuntimeException("Unexpected error creating new file.", t);
            }

            ResponseHeaders responseHeaders = msg.headers();
            if (!responseHeaders.status().equals(HttpStatus.OK)) {
              throw new RuntimeException(
                  "Non-successful response when creating new file at "
                      + uploadUrl
                      + ": "
                      + responseHeaders
                      + "\n"
                      + msg.content().toStringUtf8());
            }

            String location = responseHeaders.get(HttpHeaderNames.LOCATION);
            String pathAndQuery = location.substring("https://www.googleapis.com".length());
            return new FileWriter(pathAndQuery, alloc, eventLoop, httpClient);
          });
}
 
Example #18
Source File: AWSSignatureVersion4Test.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
@Test public void canonicalString_getDomain() {
  String timestamp = "20190730T134617Z";
  String yyyyMMdd = timestamp.substring(0, 8);
  AggregatedHttpRequest request = AggregatedHttpRequest.of(
      RequestHeaders.builder(HttpMethod.GET, "/2015-01-01/es/domain/zipkin")
          .set(AWSSignatureVersion4.X_AMZ_DATE, timestamp)
          .build()
  );
  ClientRequestContext ctx = ClientRequestContext.builder(request.toHttpRequest())
      .endpoint(Endpoint.of("es.ap-southeast-1.amazonaws.com"))
      .build();

  ByteBuf canonicalString = Unpooled.buffer();

  writeCanonicalString(ctx, request.headers(), request.content(), canonicalString);
  assertThat(canonicalString.toString(UTF_8)).isEqualTo(""
      + "GET\n"
      + "/2015-01-01/es/domain/zipkin\n"
      + "\n"
      + "host:es.ap-southeast-1.amazonaws.com\n"
      + "x-amz-date:" + timestamp + "\n"
      + "\n"
      + "host;x-amz-date\n"
      + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");

  ByteBuf toSign = Unpooled.buffer();
  AWSSignatureVersion4.writeToSign(timestamp,
      AWSSignatureVersion4.credentialScope(yyyyMMdd, "ap-southeast-1"), canonicalString, toSign);

  assertThat(toSign.toString(UTF_8)).isEqualTo(""
      + "AWS4-HMAC-SHA256\n"
      + "20190730T134617Z\n"
      + "20190730/ap-southeast-1/es/aws4_request\n"
      + "129dd8ded740553cd28544b4000982b8f88d7199b36a013fa89ee8e56c23f80e");
}
 
Example #19
Source File: ArmeriaRequestHandler.java    From curiostack with MIT License 5 votes vote down vote up
private <T, R extends ApiResponse<T>> PendingResult<T> handleMethod(
    HttpMethod method,
    String hostName,
    String url,
    HttpData payload,
    String userAgent,
    String experienceIdHeaderValue,
    Class<R> clazz,
    FieldNamingPolicy fieldNamingPolicy,
    long errorTimeout,
    Integer maxRetries,
    ExceptionsAllowedToRetry exceptionsAllowedToRetry) {
  var client =
      httpClients.computeIfAbsent(
          hostName,
          host -> WebClient.builder(host).factory(clientFactory).options(clientOptions).build());

  var gson = gsonForPolicy(fieldNamingPolicy);

  var headers = RequestHeaders.builder(method, url);
  if (experienceIdHeaderValue != null) {
    headers.add("X-Goog-Maps-Experience-ID", experienceIdHeaderValue);
  }
  var request = HttpRequest.of(headers.build(), payload);

  return new ArmeriaPendingResult<>(client, request, clazz, gson);
}
 
Example #20
Source File: ServerRequestContextAdapterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void url() {
    final HttpRequest req = HttpRequest.of(
            RequestHeaders.of(HttpMethod.GET, "/foo?name=hoge",
                              HttpHeaderNames.SCHEME, "http",
                              HttpHeaderNames.AUTHORITY, "example.com"));

    final HttpServerRequest braveReq = ServiceRequestContextAdapter.asHttpServerRequest(
            ServiceRequestContext.of(req));

    assertThat(braveReq.url()).isEqualTo("http://example.com/foo?name=hoge");
}
 
Example #21
Source File: AnnotatedServiceBlockingTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@CsvSource({
        "/myBlocking/httpResponse, 1",
        "/myBlocking/aggregatedHttpResponse, 1",
        "/myBlocking/jsonNode, 1",
        "/myBlocking/completionStage, 1"
})
void testOnlyBlockingWithBlockingAnnotation(String path, Integer count) throws Exception {
    final WebClient client = WebClient.of(server.httpUri());

    final RequestHeaders headers = RequestHeaders.of(HttpMethod.GET, path);
    final AggregatedHttpResponse res = client.execute(headers).aggregate().join();
    assertThat(res.status()).isSameAs(HttpStatus.OK);
    assertThat(blockingCount).hasValue(count);
}
 
Example #22
Source File: ArmeriaReactiveWebServerFactoryTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static AggregatedHttpResponse sendPostRequest(WebClient client) {
    final RequestHeaders requestHeaders =
            RequestHeaders.of(HttpMethod.POST, "/hello",
                              HttpHeaderNames.USER_AGENT, "test-agent/1.0.0",
                              HttpHeaderNames.ACCEPT_ENCODING, "gzip");
    return client.execute(requestHeaders, HttpData.wrap(POST_BODY.getBytes())).aggregate().join();
}
 
Example #23
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void http1SendsOneHostHeaderWhenUserSetsIt() {
    final WebClient client = WebClient.of(
            "h1c://localhost:" + ((ServerConnector) jetty.getConnectors()[0]).getLocalPort() + '/');

    final AggregatedHttpResponse response = client.execute(
            RequestHeaders.of(HttpMethod.GET, "/onlyonehost", HttpHeaderNames.HOST, "foobar")
    ).aggregate().join();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);
}
 
Example #24
Source File: ArmeriaClientHttpRequest.java    From armeria with Apache License 2.0 5 votes vote down vote up
ArmeriaClientHttpRequest(WebClient client, HttpMethod httpMethod, String pathAndQuery,
                         URI uri, DataBufferFactoryWrapper<?> factoryWrapper) {
    this.client = requireNonNull(client, "client");
    this.httpMethod = requireNonNull(httpMethod, "httpMethod");
    this.uri = requireNonNull(uri, "uri");
    this.factoryWrapper = requireNonNull(factoryWrapper, "factoryWrapper");
    headers = RequestHeaders.builder()
                            .add(HttpHeaderNames.METHOD, httpMethod.name())
                            .add(HttpHeaderNames.PATH, requireNonNull(pathAndQuery, "pathAndQuery"));
}
 
Example #25
Source File: DefaultRequestLog.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public String toStringRequestOnly(
        BiFunction<? super RequestContext, ? super RequestHeaders, ?> headersSanitizer,
        BiFunction<? super RequestContext, Object, ?> contentSanitizer,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> trailersSanitizer) {

    return DefaultRequestLog.this.toStringRequestOnly(
            headersSanitizer, contentSanitizer, trailersSanitizer);
}
 
Example #26
Source File: ContentServiceV1Test.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void watchFileWithIdentityQuery() {
    final WebClient client = dogma.httpClient();
    addFooJson(client);
    final RequestHeaders headers = RequestHeaders.of(HttpMethod.GET, CONTENTS_PREFIX + "/foo.json",
                                                     HttpHeaderNames.IF_NONE_MATCH, "-1");
    final CompletableFuture<AggregatedHttpResponse> future = client.execute(headers).aggregate();

    assertThatThrownBy(() -> future.get(500, TimeUnit.MILLISECONDS))
            .isExactlyInstanceOf(TimeoutException.class);

    // An irrelevant change should not trigger a notification.
    addBarTxt(client);
    assertThatThrownBy(() -> future.get(500, TimeUnit.MILLISECONDS))
            .isExactlyInstanceOf(TimeoutException.class);

    // Make a relevant change now.
    editFooJson(client);
    final String expectedJson =
            '{' +
            "   \"revision\" : 4," +
            "   \"entry\": {" +
            "       \"revision\" : 4," +
            "       \"path\": \"/foo.json\"," +
            "       \"type\": \"JSON\"," +
            "       \"content\": {\"a\":\"baz\"}," +
            "       \"url\": \"/api/v1/projects/myPro/repos/myRepo/contents/foo.json\"" +
            "   }" +
            '}';
    final AggregatedHttpResponse res = future.join();
    final String actualJson = res.contentUtf8();
    assertThatJson(actualJson).isEqualTo(expectedJson);
}
 
Example #27
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void unframed_streamingApi() throws Exception {
    final WebClient client = WebClient.of(server.httpUri());
    final AggregatedHttpResponse response = client.execute(
            RequestHeaders.of(HttpMethod.POST,
                              UnitTestServiceGrpc.getStaticStreamedOutputCallMethod()
                                                 .getFullMethodName(),
                              HttpHeaderNames.CONTENT_TYPE, "application/protobuf"),
            StreamingOutputCallRequest.getDefaultInstance().toByteArray()).aggregate().get();
    assertThat(response.status()).isEqualTo(HttpStatus.BAD_REQUEST);
    assertNoRpcContent();
}
 
Example #28
Source File: HealthCheckServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void customError() {
    final WebClient client = WebClient.of(server.httpUri());

    // Use an unsupported method.
    final AggregatedHttpResponse res1 = client.execute(RequestHeaders.of(HttpMethod.PATCH, "/hc_custom"))
                                              .aggregate().join();
    assertThat(res1.status()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED);

    // Send a wrong command.
    final AggregatedHttpResponse res2 = client.execute(RequestHeaders.of(HttpMethod.PUT, "/hc_custom"),
                                                       "BAD").aggregate().join();
    assertThat(res2.status()).isEqualTo(HttpStatus.BAD_REQUEST);
}
 
Example #29
Source File: HealthCheckedEndpointGroupAuthorityTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@CsvSource({
        "foo, 127.0.0.1, foo",
        "foo:1, 127.0.0.1, foo:1",
        "foo:80, 127.0.0.1, foo",
        "foo, ::1, foo",
        "foo:1, ::1, foo:1",
        "foo:80, ::1, foo"
})
void hostAndIpAddr(String endpoint, String ipAddr, String expectedAuthority) throws Exception {
    try (HealthCheckedEndpointGroup ignored = build(Endpoint.parse(endpoint).withIpAddr(ipAddr))) {
        final RequestHeaders log = logs.take();
        assertThat(log.authority()).isEqualTo(expectedAuthority);
    }
}
 
Example #30
Source File: ArmeriaConfigurationUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Configures a decorator for encoding the content of the HTTP responses sent from the server.
 */
public static Function<? super HttpService, EncodingService> contentEncodingDecorator(
        @Nullable String[] mimeTypes, @Nullable String[] excludedUserAgents,
        int minBytesToForceChunkedAndEncoding) {
    final Predicate<MediaType> encodableContentTypePredicate;
    if (mimeTypes == null || mimeTypes.length == 0) {
        encodableContentTypePredicate = contentType -> true;
    } else {
        final List<MediaType> encodableContentTypes =
                Arrays.stream(mimeTypes).map(MediaType::parse).collect(toImmutableList());
        encodableContentTypePredicate = contentType ->
                encodableContentTypes.stream().anyMatch(contentType::is);
    }

    final Predicate<? super RequestHeaders> encodableRequestHeadersPredicate;
    if (excludedUserAgents == null || excludedUserAgents.length == 0) {
        encodableRequestHeadersPredicate = headers -> true;
    } else {
        final List<Pattern> patterns =
                Arrays.stream(excludedUserAgents).map(Pattern::compile).collect(toImmutableList());
        encodableRequestHeadersPredicate = headers -> {
            // No User-Agent header will be converted to an empty string.
            final String userAgent = headers.get(HttpHeaderNames.USER_AGENT, "");
            return patterns.stream().noneMatch(pattern -> pattern.matcher(userAgent).matches());
        };
    }

    return EncodingService.builder()
                          .encodableContentTypePredicate(encodableContentTypePredicate)
                          .encodableRequestHeadersPredicate(encodableRequestHeadersPredicate)
                          .minBytesToForceChunkedEncoding(minBytesToForceChunkedAndEncoding)
                          .newDecorator();
}