com.linecorp.armeria.common.HttpStatus Java Examples

The following examples show how to use com.linecorp.armeria.common.HttpStatus. 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: 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 #2
Source File: HttpServerHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
private void respond(ChannelHandlerContext ctx, ServiceRequestContext reqCtx,
                     HttpStatus status,
                     @Nullable HttpData resContent,
                     @Nullable Throwable cause) {

    if (status.code() < 400) {
        respond(ctx, reqCtx, ResponseHeaders.builder(status), null, cause);
        return;
    }

    if (reqCtx.method() == HttpMethod.HEAD || status.isContentAlwaysEmpty()) {
        resContent = null;
    } else if (resContent == null) {
        resContent = status.toHttpData();
    } else {
        assert !resContent.isEmpty();
    }

    respond(ctx, reqCtx,
            ResponseHeaders.builder(status)
                           .addObject(HttpHeaderNames.CONTENT_TYPE, ERROR_CONTENT_TYPE),
            resContent, cause);
}
 
Example #3
Source File: TokenBucketThrottlingStrategyTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void serve1() throws Exception {
    final WebClient client = WebClient.of(serverRule.httpUri());
    final AggregatedHttpResponse response = client.get("/http-serve").aggregate().get();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);

    assertThat(response.headers().contains(HttpHeaderNames.RETRY_AFTER)).isFalse();
    assertThat(response.headers().contains("RateLimit-Remaining")).isFalse();
    assertThat(response.headers().contains("X-RateLimit-Remaining")).isFalse();
    assertThat(response.headers().contains("X-Rate-Limit-Remaining")).isFalse();
    assertThat(response.headers().contains("RateLimit-Reset")).isFalse();
    assertThat(response.headers().contains("X-RateLimit-Reset")).isFalse();
    assertThat(response.headers().contains("X-Rate-Limit-Reset")).isFalse();
    assertThat(response.headers().contains("RateLimit-Limit")).isFalse();
    assertThat(response.headers().contains("X-RateLimit-Limit")).isFalse();
    assertThat(response.headers().contains("X-Rate-Limit-Limit")).isFalse();
}
 
Example #4
Source File: HttpServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testHeaders(WebClient client) throws Exception {
    final CompletableFuture<AggregatedHttpResponse> f = client.get("/headers").aggregate();

    final AggregatedHttpResponse res = f.get();

    assertThat(res.status()).isEqualTo(HttpStatus.OK);

    // Verify all header names are in lowercase
    for (AsciiString headerName : res.headers().names()) {
        headerName.chars().filter(Character::isAlphabetic)
                  .forEach(c -> assertThat(Character.isLowerCase(c)).isTrue());
    }

    assertThat(res.headers().get(HttpHeaderNames.of("x-custom-header1"))).isEqualTo("custom1");
    assertThat(res.headers().get(HttpHeaderNames.of("x-custom-header2"))).isEqualTo("custom2");
    assertThat(res.contentUtf8()).isEqualTo("headers");
}
 
Example #5
Source File: CreateApiResponseConverter.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse convertResponse(ServiceRequestContext ctx, ResponseHeaders headers,
                                    @Nullable Object resObj,
                                    HttpHeaders trailingHeaders) throws Exception {
    try {
        final ResponseHeadersBuilder builder = headers.toBuilder();
        if (builder.contentType() == null) {
            builder.contentType(MediaType.JSON_UTF_8);
        }

        final JsonNode jsonNode = Jackson.valueToTree(resObj);
        if (builder.get(HttpHeaderNames.LOCATION) == null) {
            final String url = jsonNode.get("url").asText();

            // Remove the url field and send it with the LOCATION header.
            ((ObjectNode) jsonNode).remove("url");
            builder.add(HttpHeaderNames.LOCATION, url);
        }

        return HttpResponse.of(builder.build(), HttpData.wrap(Jackson.writeValueAsBytes(jsonNode)),
                               trailingHeaders);
    } catch (JsonProcessingException e) {
        logger.debug("Failed to convert a response:", e);
        return HttpApiUtil.newResponse(ctx, HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
}
 
Example #6
Source File: HttpApiExceptionHandler.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse handleException(ServiceRequestContext ctx, HttpRequest req, Throwable cause) {

    if (cause instanceof HttpStatusException ||
        cause instanceof HttpResponseException) {
        return ExceptionHandlerFunction.fallthrough();
    }

    // Use precomputed map if the cause is instance of CentralDogmaException to access in a faster way.
    final ExceptionHandlerFunction func = exceptionHandlers.get(cause.getClass());
    if (func != null) {
        return func.handleException(ctx, req, cause);
    }

    if (cause instanceof IllegalArgumentException) {
        return newResponse(ctx, HttpStatus.BAD_REQUEST, cause);
    }

    if (cause instanceof RequestAlreadyTimedOutException) {
        return newResponse(ctx, HttpStatus.SERVICE_UNAVAILABLE, cause);
    }

    return newResponse(ctx, HttpStatus.INTERNAL_SERVER_ERROR, cause);
}
 
Example #7
Source File: RequiresPermissionDecorator.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private HttpResponse serveInternalRepo(ServiceRequestContext ctx, HttpRequest req,
                                       MetadataService mds, User user,
                                       String projectName) throws Exception {
    if (user.isAdmin()) {
        return unwrap().serve(ctx, req);
    }
    // We do not manage permission for the internal repository. Actually we do not have a metadata of that.
    // So we need to check whether the current user is an 'administrator' or not when the request is
    // accessing to the internal repository.
    return HttpResponse.from(mds.findRole(projectName, user).handle((role, cause) -> {
        if (cause != null) {
            return handleException(ctx, cause);
        }
        if (!user.isAdmin()) {
            return HttpApiUtil.throwResponse(
                    ctx, HttpStatus.FORBIDDEN,
                    "Repository '%s/%s' can be accessed only by an administrator.",
                    projectName, Project.REPO_DOGMA);
        }
        try {
            return unwrap().serve(ctx, req);
        } catch (Exception e) {
            return Exceptions.throwUnsafely(e);
        }
    }));
}
 
Example #8
Source File: MockWebServiceExtensionTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void delay() {
    server.enqueue(HttpResponse.delayed(AggregatedHttpResponse.of(HttpStatus.OK).toHttpResponse(),
                                        Duration.ofSeconds(1)));
    server.enqueue(HttpResponse.delayed(AggregatedHttpResponse.of(HttpStatus.OK), Duration.ofSeconds(1)));

    final WebClient client =
            WebClient.builder(server.httpUri())
                     .option(ClientOption.RESPONSE_TIMEOUT_MILLIS.newValue(50L))
                     .build();

    assertThatThrownBy(() -> client.get("/").aggregate().join())
            .hasCauseInstanceOf(ResponseTimeoutException.class);
    assertThatThrownBy(() -> client.get("/").aggregate().join())
            .hasCauseInstanceOf(ResponseTimeoutException.class);
}
 
Example #9
Source File: AnnotatedServiceHandlersOrderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void requestConverterOrder() throws Exception {
    final String body = "{\"foo\":\"bar\"}";
    final AggregatedHttpRequest aReq = AggregatedHttpRequest.of(
            HttpMethod.POST, "/1/requestConverterOrder", MediaType.JSON, body);

    final AggregatedHttpResponse aRes = executeRequest(aReq);

    assertThat(aRes.status()).isEqualTo(HttpStatus.OK);
    // Converted from the default converter which is JacksonRequestConverterFunction.
    assertThat(aRes.contentUtf8()).isEqualTo(body);

    // parameter level(+1) -> method level(+1) -> class level(+1) -> service level(+1) -> server level(+1)
    // -> default
    assertThat(requestCounter.get()).isEqualTo(5);
}
 
Example #10
Source File: ServerBuilderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void treatAsSeparatePortIfZeroIsSpecifiedManyTimes() throws Exception {
    final Server server = Server.builder()
                                .http(0)
                                .http(0)
                                .https(0)
                                .tlsSelfSigned()
                                .service("/", (ctx, req) -> HttpResponse.of(HttpStatus.OK))
                                .build();

    final List<ServerPort> ports = server.config().ports();
    assertThat(ports.size()).isEqualTo(3);
    assertThat(ports.get(0).protocols()).containsOnly(SessionProtocol.HTTP);
    assertThat(ports.get(1).protocols()).containsOnly(SessionProtocol.HTTP);
    assertThat(ports.get(2).protocols()).containsOnly(SessionProtocol.HTTPS);
}
 
Example #11
Source File: RouteDecoratingTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.decorator(Route.builder().path("/")
                      .matchesHeaders("dest=headers-decorator").build(),
                 (delegate, ctx, req) -> HttpResponse.of("headers-decorator"))
      .service(Route.builder().methods(HttpMethod.GET).path("/")
                    .matchesHeaders("dest=headers-service").build(),
               (ctx, req) -> HttpResponse.of("headers-service"))
      .decorator(Route.builder().path("/")
                      .matchesParams("dest=params-decorator").build(),
                 (delegate, ctx, req) -> HttpResponse.of("params-decorator"))
      .service(Route.builder().methods(HttpMethod.GET).path("/")
                    .matchesParams("dest=params-service").build(),
               (ctx, req) -> HttpResponse.of("params-service"))
      .service(Route.builder().methods(HttpMethod.GET).path("/").build(),
               (ctx, req) -> HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR));
}
 
Example #12
Source File: MainTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testFavicon() {
    // Download the favicon.
    final AggregatedHttpResponse res = client.get("/favicon.ico").aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.headers().contentType()).isEqualTo(MediaType.parse("image/x-icon"));
}
 
Example #13
Source File: HttpServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testPrefixPathNotCached(WebClient client) throws Exception {
    assertThat(client.get("/not-cached-paths/hoge")
                     .aggregate().get().status()).isEqualTo(HttpStatus.OK);
    assertThat(PathAndQuery.cachedPaths()).doesNotContain("/not-cached-paths/hoge");
}
 
Example #14
Source File: HelloServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("MultipleExceptionsDeclaredOnTestMethod")
@Test
void testHelloService_JSON() throws ExecutionException, InterruptedException {
    // When
    final HttpResponse res = service.helloJson();

    // Then
    final AggregatedHttpResponse aggregatedHttpResponse = res.aggregate().get();
    assertThat(aggregatedHttpResponse.status()).isEqualTo(HttpStatus.OK);
    assertThat(aggregatedHttpResponse.contentType()).isEqualTo(JSON_UTF_8);
    assertThat(aggregatedHttpResponse.contentUtf8()).isEqualTo("{ \"name\": \"Armeria\" }");
}
 
Example #15
Source File: FallbackService.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static HttpStatusException getStatusException(RoutingContext routingCtx) {
    if (routingCtx.isCorsPreflight()) {
        // '403 Forbidden' is better for a CORS preflight request than other statuses.
        return HttpStatusException.of(HttpStatus.FORBIDDEN);
    }

    final HttpStatusException cause = routingCtx.deferredStatusException();
    if (cause == null) {
        return HttpStatusException.of(HttpStatus.NOT_FOUND);
    }

    return cause;
}
 
Example #16
Source File: LocalArmeriaPortsTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpServiceRegistrationBean() throws Exception {
    for (Integer port : ports) {
        final WebClient client = WebClient.of(newUrl("h1c", port));
        final HttpResponse response = client.get("/ok");
        final AggregatedHttpResponse res = response.aggregate().get();
        assertThat(res.status()).isEqualTo(HttpStatus.OK);
        assertThat(res.contentUtf8()).isEqualTo("ok");
    }
}
 
Example #17
Source File: FallbackService.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    final RoutingContext routingCtx = ctx.routingContext();
    final HttpStatusException cause = getStatusException(routingCtx);
    if (cause.httpStatus() == HttpStatus.NOT_FOUND) {
        return handleNotFound(ctx, routingCtx, cause);
    } else {
        throw cause;
    }
}
 
Example #18
Source File: RetryRuleWithContentBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the specified {@code statusFilter} for a {@link RetryRuleWithContent} which will retry
 * if a response status matches the specified {@code statusFilter}.
 *
 * @deprecated Use {@link #onStatus(BiPredicate)}.
 */
@Deprecated
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onStatus(Predicate<? super HttpStatus> statusFilter) {
    return (RetryRuleWithContentBuilder<T>) super.onStatus(statusFilter);
}
 
Example #19
Source File: StorageClient.java    From curiostack with MIT License 5 votes vote down vote up
/**
 * Reads the contents of a file from cloud storage. Ownership of the returned {@link ByteBuf} is
 * transferred to the caller, which must release it. The future will complete with {@code null} if
 * the file is not found.
 */
public CompletableFuture<ByteBuf> readFile(
    String filename, EventLoop eventLoop, ByteBufAllocator alloc) {
  String url = objectUrlPrefix + urlPathSegmentEscaper().escape(filename) + "?alt=media";

  return httpClient
      .get(url)
      .aggregateWithPooledObjects(eventLoop, alloc)
      .thenApply(
          msg -> {
            if (msg.status().equals(HttpStatus.NOT_FOUND)) {
              ReferenceCountUtil.safeRelease(msg.content());
              return null;
            }
            if (!msg.status().equals(HttpStatus.OK)) {
              String response = msg.contentUtf8();
              ReferenceCountUtil.safeRelease(msg.content());
              throw new InvalidResponseException(
                  "Could not fetch file at " + filename + ": " + response);
            }
            HttpData data = msg.content();
            if (data instanceof ByteBufHolder) {
              return ((ByteBufHolder) msg.content()).content();
            } else {
              ByteBuf buf = alloc.buffer(data.length());
              buf.writeBytes(data.array());
              return buf;
            }
          });
}
 
Example #20
Source File: ArmeriaHttpUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static ServerConfig serverConfig() {
    final Server server = Server.builder()
                                .defaultHostname("foo")
                                .service("/", (ctx, req) -> HttpResponse.of(HttpStatus.OK))
                                .build();
    return server.config();
}
 
Example #21
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void multipleRule() {
    final RetryRule retryRule =
            RetryRule.builder().onUnprocessed().thenBackoff(unprocessBackOff)
                     .orElse(RetryRule.onException())
                     .orElse((ctx, cause) -> {
                         if (ctx.log().isAvailable(
                                 RequestLogProperty.RESPONSE_HEADERS)) {
                             final HttpStatus status = ctx.log().partial().responseHeaders().status();
                             if (status.isClientError()) {
                                 return CompletableFuture.completedFuture(
                                         RetryDecision.retry(clientErrorBackOff));
                             }
                         }
                         return CompletableFuture.completedFuture(RetryDecision.next());
                     })
                     .orElse(RetryRule.builder().onServerErrorStatus().thenBackoff(statusErrorBackOff))
                     .orElse(RetryRule.builder().onStatus(HttpStatus.TOO_MANY_REQUESTS)
                                      .thenBackoff(statusBackOff));

    final ClientRequestContext ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx1.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.INTERNAL_SERVER_ERROR));
    assertBackoff(retryRule.shouldRetry(ctx1, null)).isSameAs(statusErrorBackOff);

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.TOO_MANY_REQUESTS));
    assertBackoff(retryRule.shouldRetry(ctx2, null)).isSameAs(clientErrorBackOff);

    final ClientRequestContext ctx3 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    final CompletionException ex =
            new CompletionException(UnprocessedRequestException.of(ClosedStreamException.get()));
    assertBackoff(retryRule.shouldRetry(ctx3, ex)).isSameAs(unprocessBackOff);

    final ClientRequestContext ctx4 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    assertBackoff(retryRule.shouldRetry(ctx4, new RuntimeException())).isSameAs(Backoff.ofDefault());

    final ClientRequestContext ctx5 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx5.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.CONFLICT));
    assertBackoff(retryRule.shouldRetry(ctx5, null)).isSameAs(clientErrorBackOff);
}
 
Example #22
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void buildFluently() {
    final Backoff idempotentBackoff = Backoff.fixed(100);
    final Backoff unprocessedBackoff = Backoff.fixed(200);
    final RetryRule retryRule =
            RetryRule.of(RetryRule.builder(HttpMethod.idempotentMethods())
                                  .onStatus(HttpStatus.INTERNAL_SERVER_ERROR)
                                  .onException(ClosedChannelException.class)
                                  .onStatusClass(HttpStatusClass.CLIENT_ERROR)
                                  .thenBackoff(idempotentBackoff),
                         RetryRule.builder()
                                  .onUnprocessed()
                                  .thenBackoff(unprocessedBackoff));

    final ClientRequestContext ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx1.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.INTERNAL_SERVER_ERROR));

    assertBackoff(retryRule.shouldRetry(ctx1, null)).isSameAs(idempotentBackoff);

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.POST, "/"));
    ctx2.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.INTERNAL_SERVER_ERROR));
    assertBackoff(retryRule.shouldRetry(ctx2, null)).isNull();

    final ClientRequestContext ctx3 = ClientRequestContext.of(HttpRequest.of(HttpMethod.PUT, "/"));
    assertBackoff(retryRule.shouldRetry(ctx3, new ClosedChannelException())).isSameAs(idempotentBackoff);

    final ClientRequestContext ctx4 = ClientRequestContext.of(HttpRequest.of(HttpMethod.PUT, "/"));
    assertBackoff(retryRule.shouldRetry(ctx4,
                                        UnprocessedRequestException.of(new ClosedChannelException())))
            .isSameAs(unprocessedBackoff);
}
 
Example #23
Source File: ObservableResponseConverterFunctionTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void streaming() {
    final WebClient client = WebClient.of(server.httpUri() + "/streaming");
    final AtomicBoolean isFinished = new AtomicBoolean();
    client.get("/json").subscribe(new DefaultSubscriber<HttpObject>() {
        final ImmutableList.Builder<HttpObject> received = new Builder<>();

        @Override
        public void onNext(HttpObject httpObject) {
            received.add(httpObject);
        }

        @Override
        public void onError(Throwable t) {
            throw new Error("Should not reach here.");
        }

        @Override
        public void onComplete() {
            final Iterator<HttpObject> it = received.build().iterator();
            final ResponseHeaders headers = (ResponseHeaders) it.next();
            assertThat(headers.status()).isEqualTo(HttpStatus.OK);
            assertThat(headers.contentType()).isEqualTo(MediaType.JSON_SEQ);
            // JSON Text Sequences: *(Record Separator[0x1E] JSON-text Line Feed[0x0A])
            assertThat(((HttpData) it.next()).array())
                    .isEqualTo(new byte[] { 0x1E, '\"', 'a', '\"', 0x0A });
            assertThat(((HttpData) it.next()).array())
                    .isEqualTo(new byte[] { 0x1E, '\"', 'b', '\"', 0x0A });
            assertThat(((HttpData) it.next()).array())
                    .isEqualTo(new byte[] { 0x1E, '\"', 'c', '\"', 0x0A });
            assertThat(((HttpData) it.next()).isEmpty()).isTrue();
            assertThat(it.hasNext()).isFalse();
            isFinished.set(true);
        }
    });
    await().until(isFinished::get);
}
 
Example #24
Source File: HttpServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testExactPathCached(WebClient client) throws Exception {
    assertThat(client.get("/cached-exact-path")
                     .aggregate().get().status()).isEqualTo(HttpStatus.OK);
    assertThat(PathAndQuery.cachedPaths()).contains("/cached-exact-path");
}
 
Example #25
Source File: AnnotatedService.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse handleException(ServiceRequestContext ctx, HttpRequest req, Throwable cause) {
    final Throwable peeledCause = Exceptions.peel(cause);

    if (Flags.annotatedServiceExceptionVerbosity() == ExceptionVerbosity.ALL &&
        logger.isWarnEnabled()) {
        logger.warn("{} Exception raised by method '{}' in '{}':",
                    ctx, methodName, className, peeledCause);
    }

    for (final ExceptionHandlerFunction func : functions) {
        try {
            final HttpResponse response = func.handleException(ctx, req, peeledCause);
            // Check the return value just in case, then pass this exception to the default handler
            // if it is null.
            if (response == null) {
                break;
            }
            return response;
        } catch (FallthroughException ignore) {
            // Do nothing.
        } catch (Exception e) {
            logger.warn("{} Unexpected exception from an exception handler {}:",
                        ctx, func.getClass().getName(), e);
        }
    }

    return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR);
}
 
Example #26
Source File: ClientAuthIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void normal() {
    final ClientFactory clientFactory =
            ClientFactory.builder()
                         .tlsCustomizer(ctx -> ctx.keyManager(clientCert.certificateFile(),
                                                              clientCert.privateKeyFile()))
                         .tlsNoVerify()
                         .build();
    final WebClient client = WebClient.builder(rule.httpsUri())
                                      .factory(clientFactory)
                                      .decorator(LoggingClient.builder().newDecorator())
                                      .build();
    assertThat(client.get("/").aggregate().join().status()).isEqualTo(HttpStatus.OK);
}
 
Example #27
Source File: ArmeriaCompressionConfigurationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void compressedResponse() {
    final AggregatedHttpResponse res =
            WebClient.of(newUrl()).execute(request(2048)).aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isEqualTo("gzip");
}
 
Example #28
Source File: HealthCheckServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void custom() {
    final WebClient client = WebClient.of(server.httpUri());

    // Make unhealthy.
    final AggregatedHttpResponse res1 = client.execute(RequestHeaders.of(HttpMethod.PUT, "/hc_custom"),
                                                       "KO").aggregate().join();
    assertThat(res1).isEqualTo(AggregatedHttpResponse.of(
            ResponseHeaders.of(HttpStatus.SERVICE_UNAVAILABLE,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8,
                               "armeria-lphc", "60, 5"),
            HttpData.ofUtf8("not ok")));

    // Make healthy.
    final AggregatedHttpResponse res2 = client.execute(RequestHeaders.of(HttpMethod.PUT, "/hc_custom"),
                                                       "OK").aggregate().join();
    assertThat(res2).isEqualTo(AggregatedHttpResponse.of(
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8,
                               "armeria-lphc", "60, 5"),
            HttpData.ofUtf8("ok")));

    // Send a no-op request.
    final AggregatedHttpResponse res3 = client.execute(RequestHeaders.of(HttpMethod.PUT, "/hc_custom"),
                                                       "NOOP").aggregate().join();
    assertThat(res3).isEqualTo(AggregatedHttpResponse.of(
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8,
                               "armeria-lphc", "60, 5"),
            HttpData.ofUtf8("ok")));
}
 
Example #29
Source File: UnframedGrpcServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void noContent() throws Exception {
    final UnframedGrpcService unframedGrpcService = buildUnframedGrpcService(new TestServiceImplBase() {
        @Override
        public void emptyCall(Empty request, StreamObserver<Empty> responseObserver) {
            // Note that 'responseObserver.onNext()' is not called.
            responseObserver.onCompleted();
        }
    });
    final HttpResponse response = unframedGrpcService.serve(ctx, request);
    final AggregatedHttpResponse res = response.aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.content().isEmpty()).isTrue();
}
 
Example #30
Source File: HttpServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testTimeout(WebClient client) throws Exception {
    serverRequestTimeoutMillis = 100L;
    final AggregatedHttpResponse res = client.get("/delay/2000").aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
    assertThat(res.contentType()).isEqualTo(MediaType.PLAIN_TEXT_UTF_8);
    assertThat(res.contentUtf8()).isEqualTo("503 Service Unavailable");
    assertThat(requestLogs.take().responseHeaders().status()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
}