com.linecorp.armeria.common.ResponseHeaders Java Examples

The following examples show how to use com.linecorp.armeria.common.ResponseHeaders. 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: StreamingCallSubscriberTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void cancel_duringReadingData() throws Exception {
    when(armeriaCall.tryFinish()).thenReturn(false);
    when(armeriaCall.isCanceled()).thenReturn(false, false, false, true);

    final ManualMockCallback callback = new ManualMockCallback();
    final StreamingCallSubscriber subscriber = new StreamingCallSubscriber(
            armeriaCall, callback, new Request.Builder().url("http://foo.com").build(),
            MoreExecutors.directExecutor());
    subscriber.onSubscribe(subscription);
    subscriber.onNext(ResponseHeaders.of(200));
    subscriber.onNext(HttpData.ofUtf8("{\"name\":"));
    subscriber.onNext(HttpData.ofUtf8("\"foo\"}"));
    subscriber.onComplete();

    verify(subscription, times(2)).request(1L);

    await().untilAsserted(() -> assertThat(callback.callbackCallingCount).isEqualTo(1));
    await().untilAsserted(() -> assertThat(callback.exception).isNull());
    await().untilAsserted(
            () -> assertThatThrownBy(() -> callback.response.body().string()).hasMessage("closed"));
}
 
Example #2
Source File: ServerHttp2ObjectEncoder.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture doWriteHeaders(int id, int streamId, ResponseHeaders headers, boolean endStream,
                                    boolean isTrailersEmpty) {
    if (!isStreamPresentAndWritable(streamId)) {
        // One of the following cases:
        // - Stream has been closed already.
        // - (bug) Server tried to send a response HEADERS frame before receiving a request HEADERS frame.
        return newFailedFuture(ClosedStreamException.get());
    }

    if (!isGoAwaySent && keepAliveHandler != null && keepAliveHandler.isMaxConnectionAgeExceeded()) {
        final int lastStreamId = encoder().connection().remote().lastStreamCreated();
        encoder().writeGoAway(ctx(), lastStreamId, Http2Error.NO_ERROR.code(),
                              MAX_CONNECTION_AGE_DEBUG.retain(), ctx().newPromise());
        isGoAwaySent = true;
    }

    final Http2Headers converted = convertHeaders(headers, isTrailersEmpty);
    onKeepAliveReadOrWrite();
    return encoder().writeHeaders(ctx(), streamId, converted, 0, endStream, ctx().newPromise());
}
 
Example #3
Source File: HttpResponseWrapperTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void dataIsIgnoreAfterSecondHeaders() throws Exception {
    final DecodedHttpResponse res = new DecodedHttpResponse(CommonPools.workerGroup().next());
    final HttpResponseWrapper wrapper = httpResponseWrapper(res);

    assertThat(wrapper.tryWrite(ResponseHeaders.of(200))).isTrue();
    assertThat(wrapper.tryWrite(
            HttpHeaders.of(HttpHeaderNames.of("bar"), "baz"))).isTrue(); // Second header is trailers.
    assertThat(wrapper.tryWrite(HttpData.ofUtf8("foo"))).isFalse();
    wrapper.close();

    StepVerifier.create(res)
                .expectNext(ResponseHeaders.of(200))
                .expectNext(HttpHeaders.of(HttpHeaderNames.of("bar"), "baz"))
                .expectComplete()
                .verify();
}
 
Example #4
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 #5
Source File: TestConverters.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static HttpResponse httpResponse(HttpData data) {
    final HttpResponseWriter res = HttpResponse.streaming();
    final long current = System.currentTimeMillis();
    final ResponseHeadersBuilder headers = ResponseHeaders.builder(HttpStatus.OK);
    headers.setInt(HttpHeaderNames.CONTENT_LENGTH, data.length());
    headers.setTimeMillis(HttpHeaderNames.DATE, current);

    final MediaType contentType = ServiceRequestContext.current().negotiatedResponseMediaType();
    if (contentType != null) {
        headers.contentType(contentType);
    }

    res.write(headers.build());
    res.write(data);
    res.close();
    return res;
}
 
Example #6
Source File: HealthCheckServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void updateUsingPatch() {
    final WebClient client = WebClient.of(server.httpUri());

    // Make unhealthy.
    final AggregatedHttpResponse res1 = client.execute(
            RequestHeaders.of(HttpMethod.PATCH, "/hc_updatable"),
            "[{\"op\":\"replace\",\"path\":\"/healthy\",\"value\":false}]").aggregate().join();
    assertThat(res1).isEqualTo(AggregatedHttpResponse.of(
            ResponseHeaders.of(HttpStatus.SERVICE_UNAVAILABLE,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                               "armeria-lphc", "60, 5"),
            HttpData.ofUtf8("{\"healthy\":false}")));

    // Make healthy.
    final AggregatedHttpResponse res2 = client.execute(
            RequestHeaders.of(HttpMethod.PATCH, "/hc_updatable"),
            "[{\"op\":\"replace\",\"path\":\"/healthy\",\"value\":true}]").aggregate().join();
    assertThat(res2).isEqualTo(AggregatedHttpResponse.of(
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                               "armeria-lphc", "60, 5"),
            HttpData.ofUtf8("{\"healthy\":true}")));
}
 
Example #7
Source File: TokenService.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
/**
 * POST /tokens
 *
 * <p>Returns a newly-generated token belonging to the current login user.
 */
@Post("/tokens")
@StatusCode(201)
@ResponseConverter(CreateApiResponseConverter.class)
public CompletableFuture<HttpResult<Token>> createToken(@Param String appId,
                                                        @Param boolean isAdmin,
                                                        Author author, User loginUser) {
    checkArgument(!isAdmin || loginUser.isAdmin(),
                  "Only administrators are allowed to create an admin-level token.");
    return mds.createToken(author, appId, isAdmin)
              .thenCompose(unused -> mds.findTokenByAppId(appId))
              .thenApply(token -> {
                  final ResponseHeaders headers = ResponseHeaders.of(HttpStatus.CREATED,
                                                                     HttpHeaderNames.LOCATION,
                                                                     "/tokens/" + appId);
                  return HttpResult.of(headers, token);
              });
}
 
Example #8
Source File: HttpEncodedResponseTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void doNotEncodeWhenContentShouldBeEmpty() {
    final ResponseHeaders headers = ResponseHeaders.builder(HttpStatus.NO_CONTENT).contentType(
            MediaType.PLAIN_TEXT_UTF_8).build();
    // Add CONTINUE not to validate when creating HttpResponse.
    final HttpResponse orig = HttpResponse.of(ResponseHeaders.of(HttpStatus.CONTINUE), headers,
                                              HttpData.ofUtf8("foo"));
    final HttpEncodedResponse encoded = new HttpEncodedResponse(
            orig, HttpEncodingType.DEFLATE, mediaType -> true, 1);
    StepVerifier.create(encoded)
                .expectNext(ResponseHeaders.of(HttpStatus.CONTINUE))
                .expectNext(headers)
                .expectNext(HttpData.ofUtf8("foo"))
                .expectComplete()
                .verify();
}
 
Example #9
Source File: FramedGrpcServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void pathMissingSlash() throws Exception {
    final HttpRequest req = HttpRequest.of(
            RequestHeaders.of(HttpMethod.POST, "/grpc.testing.TestService.UnaryCall",
                              HttpHeaderNames.CONTENT_TYPE, "application/grpc+proto"));
    final RoutingResult routingResult = RoutingResult.builder()
                                                     .path("grpc.testing.TestService.UnaryCall")
                                                     .build();
    final ServiceRequestContext ctx = ServiceRequestContext.builder(req)
                                                           .routingResult(routingResult)
                                                           .build();
    final HttpResponse response = grpcService.doPost(ctx, PooledHttpRequest.of(req));
    assertThat(response.aggregate().get()).isEqualTo(AggregatedHttpResponse.of(
            ResponseHeaders.of(HttpStatus.BAD_REQUEST,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8,
                               HttpHeaderNames.CONTENT_LENGTH, 13),
            HttpData.ofUtf8("Invalid path.")));
}
 
Example #10
Source File: HealthCheckServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void waitUntilHealthy() throws Exception {
    // Make the server unhealthy.
    checker.setHealthy(false);

    final CompletableFuture<AggregatedHttpResponse> f = sendLongPollingGet("unhealthy");

    // Should not wake up until the server becomes unhealthy.
    assertThatThrownBy(() -> f.get(1, TimeUnit.SECONDS))
            .isInstanceOf(TimeoutException.class);

    // Make the server healthy so the response comes in.
    checker.setHealthy(true);
    assertThat(f.get()).isEqualTo(AggregatedHttpResponse.of(
            ImmutableList.of(ResponseHeaders.builder(HttpStatus.PROCESSING)
                                            .set("armeria-lphc", "60, 5")
                                            .build()),
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                               "armeria-lphc", "60, 5"),
            HttpData.ofUtf8("{\"healthy\":true}"),
            HttpHeaders.of()));
}
 
Example #11
Source File: JsonTextSequences.java    From armeria with Apache License 2.0 6 votes vote down vote up
static ResponseHeaders ensureHttpStatus(ResponseHeaders headers) {
    final HttpStatus status = headers.status();
    if (status.equals(HttpStatus.OK)) {
        return headers;
    }

    if (!warnedStatusCode) {
        logger.warn(
                "Overwriting the HTTP status code from '{}' to '{}' for JSON Text Sequences. " +
                "Do not set an HTTP status code on the HttpHeaders when calling factory methods in '{}', " +
                "or set '{}' if you want to specify its status code. " +
                "Please refer to https://tools.ietf.org/html/rfc7464 for more information.",
                status, HttpStatus.OK, JsonTextSequences.class.getSimpleName(), HttpStatus.OK);
        warnedStatusCode = true;
    }
    return headers.toBuilder().status(HttpStatus.OK).build();
}
 
Example #12
Source File: MetadataUtilTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void copyFromHeadersTest() {
    final HttpHeaders trailers =
            ResponseHeaders.builder()
                           .endOfStream(true)
                           .add(HttpHeaderNames.STATUS, HttpStatus.OK.codeAsText())
                           .add(HttpHeaderNames.CONTENT_TYPE, "application/grpc+proto")
                           .add(GrpcHeaderNames.GRPC_STATUS, "3")
                           .add(GrpcHeaderNames.GRPC_MESSAGE, "test_grpc_message")
                           .add(TEST_ASCII_KEY.originalName(), "test_message")
                           .add(GrpcHeaderNames.ARMERIA_GRPC_THROWABLEPROTO_BIN,
                                Base64.getEncoder().encodeToString(THROWABLE_PROTO.toByteArray()))
                           .build();

    final Metadata metadata = MetadataUtil.copyFromHeaders(trailers);

    assertThat(metadata.get(TEST_ASCII_KEY)).isEqualTo("test_message");
    // MUST not copy values of :status, grpc-status, grpc-message, armeria.grpc.ThrowableProto-bin
    assertThat(metadata.get(STATUS_KEY)).isNull();
    assertThat(metadata.get(InternalStatus.CODE_KEY)).isNull();
    assertThat(metadata.get(InternalStatus.MESSAGE_KEY)).isNull();
    assertThat(metadata.get(THROWABLE_PROTO_METADATA_KEY)).isNull();
}
 
Example #13
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void onStatus() {
    final Backoff backoff500 = Backoff.fixed(1000);
    final Backoff backoff502 = Backoff.fixed(1000);
    final RetryRule rule =
            RetryRule.builder()
                     .onStatus(HttpStatus.INTERNAL_SERVER_ERROR)
                     .thenBackoff(backoff500)
                     .orElse(RetryRule.builder()
                                      .onStatus((unused, status) -> HttpStatus.BAD_GATEWAY.equals(status))
                                      .thenBackoff(backoff502));

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

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.BAD_GATEWAY));
    assertBackoff(rule.shouldRetry(ctx2, null)).isSameAs(backoff502);

    final ClientRequestContext ctx3 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx3.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.GATEWAY_TIMEOUT));
    assertBackoff(rule.shouldRetry(ctx3, null)).isNull();
}
 
Example #14
Source File: StreamingCallSubscriberTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void cancel() throws Exception {
    when(armeriaCall.tryFinish()).thenReturn(false);
    when(armeriaCall.isCanceled()).thenReturn(false, false, true);

    final ManualMockCallback callback = new ManualMockCallback();
    final StreamingCallSubscriber subscriber = new StreamingCallSubscriber(
            armeriaCall, callback, new Request.Builder().url("http://foo.com").build(),
            MoreExecutors.directExecutor());
    subscriber.onSubscribe(subscription);
    subscriber.onNext(ResponseHeaders.of(200));
    subscriber.onNext(HttpData.ofUtf8("{\"name\":\"foo\"}"));
    subscriber.onComplete();

    verify(subscription, times(2)).request(1L);

    await().untilAsserted(() -> assertThat(callback.callbackCallingCount).isEqualTo(1));
    await().untilAsserted(() -> assertThat(callback.exception.getMessage()).isEqualTo("cancelled"));
}
 
Example #15
Source File: ServerHttp1ObjectEncoder.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture doWriteHeaders(int id, int streamId, ResponseHeaders headers, boolean endStream,
                                    boolean isTrailersEmpty) {
    if (!isWritable(id)) {
        return newClosedSessionFuture();
    }

    final HttpResponse converted = convertHeaders(headers, endStream, isTrailersEmpty);
    if (headers.status().isInformational()) {
        return write(id, converted, false);
    }

    if (keepAliveHandler != null && keepAliveHandler.isMaxConnectionAgeExceeded()) {
        converted.headers().set(HttpHeaderNames.CONNECTION, "close");
        sentConnectionCloseHeader = true;
    }
    return writeNonInformationalHeaders(id, converted, endStream);
}
 
Example #16
Source File: ArmeriaEurekaClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static <T> EurekaHttpResponse<T> convertResponse(HttpResponse response, Class<T> type) {
    final AggregatedHttpResponse aggregatedRes = response.aggregate().join();
    T t = null;
    final ResponseHeaders headers = aggregatedRes.headers();
    if (headers.status() == HttpStatus.OK) {
        final EntityBodyConverter converter = new EntityBodyConverter();
        try {
            // noinspection unchecked
            t = (T) converter.read(
                    aggregatedRes.content().toInputStream(), type,
                    MediaType.valueOf(headers.contentType().toString()));
        } catch (IOException e) {
            throw new RuntimeException("Unexpected exception while converting response body:", e);
        }
    }

    return anEurekaHttpResponse(aggregatedRes.status().code(), t)
            .headers(headersOf(headers))
            .build();
}
 
Example #17
Source File: ContentServiceV1Test.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Test
void deleteFile() throws IOException {
    final WebClient client = dogma.httpClient();
    addFooJson(client);
    addBarTxt(client);

    final String body =
            '{' +
            "   \"path\": \"/foo.json\"," +
            "   \"type\": \"REMOVE\"," +
            "   \"commitMessage\" : {" +
            "       \"summary\" : \"Delete foo.json\"" +
            "   }" +
            '}';
    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, CONTENTS_PREFIX,
                                                     HttpHeaderNames.CONTENT_TYPE, MediaType.JSON);
    final AggregatedHttpResponse res1 = client.execute(headers, body).aggregate().join();
    assertThat(ResponseHeaders.of(res1.headers()).status()).isEqualTo(HttpStatus.OK);

    final AggregatedHttpResponse res2 = client.get(CONTENTS_PREFIX + "/**").aggregate().join();
    // /a directory and /a/bar.txt file are left
    assertThat(Jackson.readTree(res2.contentUtf8()).size()).isEqualTo(2);
}
 
Example #18
Source File: ArmeriaClientHttpResponseTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void getCookies() {
    final HttpHeaders httpHeaders = ResponseHeaders.of(HttpStatus.OK,
                                                       HttpHeaderNames.of("blahblah"), "armeria",
                                                       HttpHeaderNames.SET_COOKIE, "a=1; b=2");
    final HttpResponse httpResponse = HttpResponse.of(httpHeaders);
    final ArmeriaClientHttpResponse response =
            response(new ArmeriaHttpClientResponseSubscriber(httpResponse), httpHeaders);

    // HttpResponse would be completed after ResponseHeader is completed, because there's no body.
    assertThat(httpResponse.whenComplete().isDone()).isTrue();

    assertThat(response.getStatusCode()).isEqualTo(org.springframework.http.HttpStatus.OK);
    assertThat(response.getHeaders().getFirst("blahblah")).isEqualTo("armeria");

    final ResponseCookie cookie = response.getCookies().getFirst("a");
    assertThat(cookie).isNotNull();
    assertThat(cookie.getValue()).isEqualTo("1");
}
 
Example #19
Source File: LoggingServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void infoLevel() throws Exception {
    final ServiceRequestContext ctx = ServiceRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx.logBuilder().responseHeaders(ResponseHeaders.of(200));

    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)
                          .newDecorator().apply(delegate);

    service.serve(ctx, ctx.request());

    verify(logger).info(eq(REQUEST_FORMAT), same(ctx),
                        matches(".*headers=\\[:method=GET, :path=/].*"));
    verify(logger).info(eq(RESPONSE_FORMAT), same(ctx),
                        matches(".*headers=\\[:status=200].*"));
}
 
Example #20
Source File: TomcatService.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static ResponseHeaders convertResponse(Response coyoteRes) {
    final ResponseHeadersBuilder headers = ResponseHeaders.builder();
    headers.status(coyoteRes.getStatus());

    final String contentType = coyoteRes.getContentType();
    if (contentType != null && !contentType.isEmpty()) {
        headers.set(HttpHeaderNames.CONTENT_TYPE, contentType);
    }

    final long contentLength = coyoteRes.getBytesWritten(true); // 'true' will trigger flush.
    final String method = coyoteRes.getRequest().method().toString();
    if (!"HEAD".equals(method)) {
        headers.setLong(HttpHeaderNames.CONTENT_LENGTH, contentLength);
    }

    final MimeHeaders cHeaders = coyoteRes.getMimeHeaders();
    final int numHeaders = cHeaders.size();
    for (int i = 0; i < numHeaders; i++) {
        final AsciiString name = toHeaderName(cHeaders.getName(i));
        if (name == null) {
            continue;
        }

        final String value = toHeaderValue(cHeaders.getValue(i));
        if (value == null) {
            continue;
        }

        headers.add(name.toLowerCase(), value);
    }

    return headers.build();
}
 
Example #21
Source File: EurekaUpdatingListener.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void serverStarted(Server server) throws Exception {
    final InstanceInfo newInfo = fillAndCreateNewInfo(instanceInfo, server);

    try (ClientRequestContextCaptor contextCaptor = Clients.newContextCaptor()) {
        final HttpResponse response = client.register(newInfo);
        final ClientRequestContext ctx = contextCaptor.get();
        response.aggregate().handle((res, cause) -> {
            if (closed) {
                return null;
            }
            if (cause != null) {
                logger.warn("Failed to register {} to Eureka: {}",
                            newInfo.getHostName(), client.uri(), cause);
                return null;
            }
            final ResponseHeaders headers = res.headers();
            if (headers.status() != HttpStatus.NO_CONTENT) {
                logger.warn("Failed to register {} to Eureka: {}. (status: {}, content: {})",
                            newInfo.getHostName(), client.uri(), headers.status(), res.contentUtf8());
            } else {
                logger.info("Registered {} to Eureka: {}", newInfo.getHostName(), client.uri());
                scheduleHeartBeat(ctx.eventLoop(), newInfo);
            }
            return null;
        });
    }
}
 
Example #22
Source File: ObservableResponseConverterFunction.java    From armeria with Apache License 2.0 5 votes vote down vote up
private HttpResponse onSuccess(ServiceRequestContext ctx,
                               ResponseHeaders headers,
                               @Nullable Object result,
                               HttpHeaders trailers) {
    try {
        return responseConverter.convertResponse(ctx, headers, result, trailers);
    } catch (Exception e) {
        return onError(ctx, e);
    }
}
 
Example #23
Source File: HttpServerAdditionalHeadersTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void informationalHeadersDoNotContainAdditionalHeaders() {
    final WebClient client = WebClient.of(server.httpUri());
    final AggregatedHttpResponse res = client.get("/informational").aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    final List<ResponseHeaders> informationals = res.informationals();
    assertThat(informationals).hasSize(1);
    final ResponseHeaders informationalHeaders = informationals.get(0);
    assertThat(informationalHeaders.status()).isEqualTo(HttpStatus.CONTINUE);
    assertThat(informationalHeaders.names()).doesNotContain(HttpHeaderNames.of("foo"));
    assertThat(res.headers().names()).contains(HttpHeaderNames.of("foo"));
}
 
Example #24
Source File: ArmeriaClientHttpResponseTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static ArmeriaClientHttpResponse response(ArmeriaHttpClientResponseSubscriber subscriber,
                                                  HttpHeaders expectedHttpHeaders) {
    await().until(() -> subscriber.headersFuture().isDone());

    final ResponseHeaders h = subscriber.headersFuture().join();
    assertThat(h).isEqualTo(expectedHttpHeaders);

    return new ArmeriaClientHttpResponse(h, subscriber.toResponseBodyPublisher(),
                                         DataBufferFactoryWrapper.DEFAULT);
}
 
Example #25
Source File: AccessLogFormatsTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void requestLogAvailabilityException() {
    final String fullName = AccessLogFormatsTest.class.getSimpleName() + "/rpcMethod";
    final String expectedLogMessage = "\"GET /armeria/log#" + fullName + " h2c\" 200 1024";

    final ServiceRequestContext ctx = ServiceRequestContext.builder(
            HttpRequest.of(RequestHeaders.of(HttpMethod.GET, "/armeria/log",
                                             HttpHeaderNames.USER_AGENT, "armeria/x.y.z",
                                             HttpHeaderNames.REFERER, "http://log.example.com",
                                             HttpHeaderNames.COOKIE, "a=1;b=2"))).build();
    final RequestLog log = ctx.log().partial();
    final RequestLogBuilder logBuilder = ctx.logBuilder();

    // AccessLogger#format will be called after response is finished.
    final AtomicReference<RequestLog> logHolder = new AtomicReference<>();
    log.whenComplete().thenAccept(logHolder::set);

    // RequestLogAvailabilityException will be raised inside AccessLogger#format before injecting each
    // component to RequestLog. So we cannot get the expected log message here.
    assertThat(AccessLogger.format(AccessLogFormats.COMMON, log)).doesNotEndWith(expectedLogMessage);
    logBuilder.requestContent(RpcRequest.of(AccessLogFormatsTest.class, "rpcMethod"), null);
    assertThat(AccessLogger.format(AccessLogFormats.COMMON, log)).doesNotEndWith(expectedLogMessage);
    logBuilder.endRequest();
    assertThat(AccessLogger.format(AccessLogFormats.COMMON, log)).doesNotEndWith(expectedLogMessage);
    logBuilder.responseHeaders(ResponseHeaders.of(HttpStatus.OK));
    assertThat(AccessLogger.format(AccessLogFormats.COMMON, log)).doesNotEndWith(expectedLogMessage);
    logBuilder.responseLength(1024);
    assertThat(AccessLogger.format(AccessLogFormats.COMMON, log)).doesNotEndWith(expectedLogMessage);
    logBuilder.endResponse();

    assertThat(AccessLogger.format(AccessLogFormats.COMMON, logHolder.get()))
            .endsWith(expectedLogMessage);
}
 
Example #26
Source File: ArmeriaHttpUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the specified Netty HTTP/2 into Armeria HTTP/2 headers.
 */
public static HttpHeaders toArmeria(Http2Headers headers, boolean request, boolean endOfStream) {
    final HttpHeadersBuilder builder;
    if (request) {
        builder = headers.contains(HttpHeaderNames.METHOD) ? RequestHeaders.builder()
                                                           : HttpHeaders.builder();
    } else {
        builder = headers.contains(HttpHeaderNames.STATUS) ? ResponseHeaders.builder()
                                                           : HttpHeaders.builder();
    }

    toArmeria(builder, headers, endOfStream);
    return builder.build();
}
 
Example #27
Source File: ArmeriaServerHttpResponse.java    From armeria with Apache License 2.0 5 votes vote down vote up
private ResponseHeaders buildResponseHeaders() {
    if (!armeriaHeaders.contains(HttpHeaderNames.STATUS)) {
        // If there is no status code specified, set 200 OK by default.
        armeriaHeaders.status(com.linecorp.armeria.common.HttpStatus.OK);
    }
    return armeriaHeaders.build();
}
 
Example #28
Source File: ArmeriaClientHttpResponse.java    From armeria with Apache License 2.0 5 votes vote down vote up
ArmeriaClientHttpResponse(ResponseHeaders headers,
                          ResponseBodyPublisher publisher,
                          DataBufferFactoryWrapper<?> factoryWrapper) {
    this.headers = requireNonNull(headers, "headers");
    status = headers.status();

    body = Flux.from(publisher).cast(HttpData.class).map(factoryWrapper::toDataBuffer);
}
 
Example #29
Source File: HttpServerAbortingInfiniteStreamTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/infinity", (ctx, req) -> {
        // Ensure that the protocol is expected one.
        assertThat(ctx.sessionProtocol()).isEqualTo(expectedProtocol.get());

        final HttpResponseWriter writer = HttpResponse.streaming();
        writer.write(ResponseHeaders.of(HttpStatus.OK));

        // Do not close the response writer because it returns data infinitely.
        writer.whenConsumed().thenRun(new Runnable() {
            @Override
            public void run() {
                writer.write(HttpData.ofUtf8("infinite stream"));
                writer.whenConsumed().thenRun(this);
            }
        });
        writer.whenComplete().whenComplete((unused, cause) -> {
            // We are not expecting that this stream is successfully finished.
            if (cause != null) {
                if (ctx.sessionProtocol() == H1C) {
                    assertThat(cause).isInstanceOf(CancelledSubscriptionException.class);
                } else {
                    assertThat(cause).isInstanceOf(AbortedStreamException.class);
                }
                if (isCompleted.compareAndSet(false, true)) {
                    logger.debug("Infinite stream is completed", cause);
                }
            }
        });
        return writer;
    });
}
 
Example #30
Source File: AbstractRuleBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the specified {@code responseHeadersFilter}.
 */
public AbstractRuleBuilder onResponseHeaders(
        BiPredicate<? super ClientRequestContext, ? super ResponseHeaders> responseHeadersFilter) {
    requireNonNull(responseHeadersFilter, "responseHeadersFilter");
    if (this.responseHeadersFilter != null) {
        this.responseHeadersFilter = this.responseHeadersFilter.or(responseHeadersFilter);
    } else {
        @SuppressWarnings("unchecked")
        final BiPredicate<ClientRequestContext, ResponseHeaders> cast =
                (BiPredicate<ClientRequestContext, ResponseHeaders>) responseHeadersFilter;
        this.responseHeadersFilter = cast;
    }
    return this;
}