Java Code Examples for com.linecorp.armeria.common.ResponseHeaders#of()

The following examples show how to use com.linecorp.armeria.common.ResponseHeaders#of() . 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: ArmeriaClientHttpResponseTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void readBodyStream() {
    final ResponseHeaders httpHeaders = ResponseHeaders.of(HttpStatus.OK);
    final HttpResponse httpResponse = HttpResponse.of(
            Flux.concat(Mono.just(httpHeaders),
                        Flux.just("a", "b", "c", "d", "e")
                            .map(HttpData::ofUtf8)));
    final ArmeriaClientHttpResponse response =
            response(new ArmeriaHttpClientResponseSubscriber(httpResponse), httpHeaders);

    assertThat(response.getStatusCode()).isEqualTo(org.springframework.http.HttpStatus.OK);

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

    final Flux<String> body = response.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(() -> httpResponse.whenComplete().isDone());
}
 
Example 2
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 3
Source File: StringResponseConverterFunctionTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void aggregatedText() throws Exception {
    final ResponseHeaders expectedHeadersWithoutContentLength =
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8);
    final ResponseHeaders expectedHeadersWithContentLength =
            expectedHeadersWithoutContentLength.withMutations(h -> {
                h.addInt(HttpHeaderNames.CONTENT_LENGTH, 11);
            });

    final List<String> contents = ImmutableList.of("foo", ",", "bar", ",", "baz");
    for (final Object result : ImmutableList.of(Flux.fromIterable(contents),    // publisher
                                                contents.stream(),              // stream
                                                contents)) {                    // iterable
        StepVerifier.create(from(result))
                    .expectNext(result instanceof Iterable ? expectedHeadersWithContentLength
                                                           : expectedHeadersWithoutContentLength)
                    .expectNext(HttpData.wrap("foo,bar,baz".getBytes()))
                    .expectComplete()
                    .verify();
    }
}
 
Example 4
Source File: ProjectServiceV1Test.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void createProject() throws IOException {
    final WebClient client = dogma.httpClient();
    final AggregatedHttpResponse aRes = createProject(client, "myPro");
    final ResponseHeaders headers = ResponseHeaders.of(aRes.headers());
    assertThat(headers.status()).isEqualTo(HttpStatus.CREATED);

    final String location = headers.get(HttpHeaderNames.LOCATION);
    assertThat(location).isEqualTo("/api/v1/projects/myPro");

    final JsonNode jsonNode = Jackson.readTree(aRes.contentUtf8());
    assertThat(jsonNode.get("name").asText()).isEqualTo("myPro");
    assertThat(jsonNode.get("createdAt").asText()).isNotNull();
}
 
Example 5
Source File: ProjectServiceV1Test.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void removeProject() {
    final WebClient client = dogma.httpClient();
    createProject(client, "foo");
    final AggregatedHttpResponse aRes = client.delete(PROJECTS_PREFIX + "/foo")
                                              .aggregate().join();
    final ResponseHeaders headers = ResponseHeaders.of(aRes.headers());
    assertThat(ResponseHeaders.of(headers).status()).isEqualTo(HttpStatus.NO_CONTENT);
}
 
Example 6
Source File: ProjectServiceV1Test.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void purgeProject() {
    removeProject();

    final WebClient client = dogma.httpClient();
    final AggregatedHttpResponse aRes = client.delete(PROJECTS_PREFIX + "/foo/removed")
                                              .aggregate().join();
    final ResponseHeaders headers = ResponseHeaders.of(aRes.headers());
    assertThat(ResponseHeaders.of(headers).status()).isEqualTo(HttpStatus.NO_CONTENT);
}
 
Example 7
Source File: ArmeriaClientHttpResponseTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void cancel() {
    final AtomicBoolean completedWithError = new AtomicBoolean();
    final Flux<HttpData> bodyPub = Flux.just("a", "b", "c", "d", "e")
                                       .map(HttpData::ofUtf8)
                                       .doOnCancel(() -> completedWithError.set(true));

    final ResponseHeaders httpHeaders = ResponseHeaders.of(HttpStatus.OK);
    final HttpResponse httpResponse = HttpResponse.of(Flux.concat(Mono.just(httpHeaders), bodyPub));
    final ArmeriaClientHttpResponse response =
            response(new ArmeriaHttpClientResponseSubscriber(httpResponse), httpHeaders);

    assertThat(response.getStatusCode()).isEqualTo(org.springframework.http.HttpStatus.OK);

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

    final Flux<String> body = response.getBody().map(TestUtil::bufferToString);
    StepVerifier.create(body, 1)
                .expectNext("a").thenRequest(1)
                .expectNext("b")
                .thenCancel()
                .verify();

    final CompletableFuture<Void> f = httpResponse.whenComplete();
    await().until(f::isDone);
    assertThat(f.isCompletedExceptionally()).isTrue();
    assertThatThrownBy(f::get).isInstanceOf(ExecutionException.class)
                              .hasCauseInstanceOf(CancelledSubscriptionException.class);

    // Check whether the cancellation has been propagated to the original publisher.
    await().untilTrue(completedWithError);
}
 
Example 8
Source File: HttpRedirectBindingUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link ResponseHeaders} with the specified {@code location}, the default {@code cache-control}
 * and the default {@code pragma} headers.
 */
static ResponseHeaders headersWithLocation(String location) {
    return ResponseHeaders.of(HttpStatus.FOUND,
                              HttpHeaderNames.LOCATION, location,
                              HttpHeaderNames.CACHE_CONTROL, DEFAULT_CACHE_CONTROL,
                              HttpHeaderNames.PRAGMA, DEFAULT_PRAGMA);
}
 
Example 9
Source File: RepositoryServiceV1Test.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void createRepository() throws IOException {
    final WebClient client = dogma.httpClient();
    final AggregatedHttpResponse aRes = createRepository(client, "myRepo");
    final ResponseHeaders headers = ResponseHeaders.of(aRes.headers());
    assertThat(headers.status()).isEqualTo(HttpStatus.CREATED);

    final String location = headers.get(HttpHeaderNames.LOCATION);
    assertThat(location).isEqualTo("/api/v1/projects/myPro/repos/myRepo");

    final JsonNode jsonNode = Jackson.readTree(aRes.contentUtf8());
    assertThat(jsonNode.get("name").asText()).isEqualTo("myRepo");
    assertThat(jsonNode.get("headRevision").asInt()).isOne();
    assertThat(jsonNode.get("createdAt").asText()).isNotNull();
}
 
Example 10
Source File: CachingHttpFileTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Makes sure a large file is not cached.
 */
@Test
public void largeFile() throws Exception {
    final HttpFileAttributes attrs = new HttpFileAttributes(5, 0);
    final ResponseHeaders headers = ResponseHeaders.of(200);
    final HttpResponse res = HttpResponse.of("large");
    final AggregatedHttpFile aggregated = HttpFile.of(HttpData.ofUtf8("large"), 0);
    final AggregatedHttpFile aggregatedWithPooledObjs = HttpFile.of(HttpData.ofUtf8("large"), 0);
    final HttpFile uncached = mock(HttpFile.class);
    when(uncached.readAttributes(executor)).thenReturn(UnmodifiableFuture.completedFuture(attrs));
    when(uncached.readHeaders(executor)).thenReturn(UnmodifiableFuture.completedFuture(headers));
    when(uncached.read(any(), any())).thenReturn(UnmodifiableFuture.completedFuture(res));
    when(uncached.aggregate(any())).thenReturn(UnmodifiableFuture.completedFuture(aggregated));
    when(uncached.aggregateWithPooledObjects(any(), any()))
            .thenReturn(UnmodifiableFuture.completedFuture(aggregatedWithPooledObjs));

    final HttpFile cached = HttpFile.ofCached(uncached, 4);

    // read() should be delegated to 'uncached'.
    assertThat(cached.read(executor, alloc).join()).isSameAs(res);
    verify(uncached, times(1)).readAttributes(executor);
    verify(uncached, times(1)).read(executor, alloc);
    verifyNoMoreInteractions(uncached);
    clearInvocations(uncached);

    // aggregate() should be delegated to 'uncached'.
    assertThat(cached.aggregate(executor).join()).isSameAs(aggregated);
    verify(uncached, times(1)).readAttributes(executor);
    verify(uncached, times(1)).aggregate(executor);
    verifyNoMoreInteractions(uncached);
    clearInvocations(uncached);

    // aggregateWithPooledObjects() should be delegated to 'uncached'.
    assertThat(cached.aggregateWithPooledObjects(executor, alloc).join())
            .isSameAs(aggregatedWithPooledObjs);
    verify(uncached, times(1)).readAttributes(executor);
    verify(uncached, times(1)).aggregateWithPooledObjects(executor, alloc);
    verifyNoMoreInteractions(uncached);
    clearInvocations(uncached);
}
 
Example 11
Source File: StringResponseConverterFunctionTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void charset() throws Exception {
    final ResponseHeaders headers = ResponseHeaders.of(HttpStatus.OK,
                                                       HttpHeaderNames.CONTENT_TYPE,
                                                       "text/plain; charset=euc-kr");
    StepVerifier.create(function.convertResponse(ctx, headers, "한글", DEFAULT_TRAILERS))
                .expectNext(headers.toBuilder()
                                   .addInt(HttpHeaderNames.CONTENT_LENGTH, 4)
                                   .build())
                .expectNext(HttpData.of(Charset.forName("euc-kr"), "한글"))
                .expectComplete()
                .verify();
}
 
Example 12
Source File: ContentPreviewerFactoryTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static ResponseHeaders resHeaders(MediaType contentType) {
    return ResponseHeaders.of(HttpStatus.OK, HttpHeaderNames.CONTENT_TYPE, contentType);
}
 
Example 13
Source File: DefaultRequestLogTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void addChild() {
    when(ctx.method()).thenReturn(HttpMethod.GET);
    final DefaultRequestLog child = new DefaultRequestLog(ctx);
    log.addChild(child);
    child.startRequest();
    child.session(channel, SessionProtocol.H2C, null, null);
    assertThat(log.requestStartTimeMicros()).isEqualTo(child.requestStartTimeMicros());
    assertThat(log.channel()).isSameAs(channel);
    assertThat(log.sessionProtocol()).isSameAs(SessionProtocol.H2C);

    child.serializationFormat(SerializationFormat.NONE);
    assertThat(log.scheme().serializationFormat()).isSameAs(SerializationFormat.NONE);

    child.requestFirstBytesTransferred();
    assertThat(log.requestFirstBytesTransferredTimeNanos())
            .isEqualTo(child.requestFirstBytesTransferredTimeNanos());

    final RequestHeaders foo = RequestHeaders.of(HttpMethod.GET, "/foo");
    child.requestHeaders(foo);
    assertThat(log.requestHeaders()).isSameAs(foo);

    final String requestContent = "baz";
    final String rawRequestContent = "qux";

    child.requestContent(requestContent, rawRequestContent);
    assertThat(log.requestContent()).isSameAs(requestContent);
    assertThat(log.rawRequestContent()).isSameAs(rawRequestContent);

    child.endRequest();
    assertThat(log.requestDurationNanos()).isEqualTo(child.requestDurationNanos());

    // response-side log are propagated when RequestLogBuilder.endResponseWithLastChild() is invoked
    child.startResponse();
    assertThatThrownBy(() -> log.responseStartTimeMicros())
            .isExactlyInstanceOf(RequestLogAvailabilityException.class);

    child.responseFirstBytesTransferred();
    assertThatThrownBy(() -> log.responseFirstBytesTransferredTimeNanos())
            .isExactlyInstanceOf(RequestLogAvailabilityException.class);

    final ResponseHeaders bar = ResponseHeaders.of(200);
    child.responseHeaders(bar);
    assertThatThrownBy(() -> log.responseHeaders())
            .isExactlyInstanceOf(RequestLogAvailabilityException.class);

    log.endResponseWithLastChild();
    assertThat(log.responseStartTimeMicros()).isEqualTo(child.responseStartTimeMicros());

    assertThat(log.responseFirstBytesTransferredTimeNanos())
            .isEqualTo(child.responseFirstBytesTransferredTimeNanos());
    assertThat(log.responseHeaders()).isSameAs(bar);

    final String responseContent = "baz1";
    final String rawResponseContent = "qux1";
    child.responseContent(responseContent, rawResponseContent);

    child.endResponse(new AnticipatedException("Oops!"));
    assertThat(log.responseContent()).isSameAs(responseContent);
    assertThat(log.rawResponseContent()).isSameAs(rawResponseContent);
    assertThat(log.responseDurationNanos()).isEqualTo(child.responseDurationNanos());
    assertThat(log.totalDurationNanos()).isEqualTo(child.totalDurationNanos());
}
 
Example 14
Source File: CachingHttpFileTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Makes sure a regular file is handled as expected, including proper cache invalidation.
 */
@Test
public void existentFile() throws Exception {
    final HttpFileAttributes attrs = new HttpFileAttributes(3, 0);
    final ResponseHeaders headers = ResponseHeaders.of(200);
    final HttpFile uncached = mock(HttpFile.class);
    when(uncached.readAttributes(executor)).thenReturn(UnmodifiableFuture.completedFuture(attrs));
    when(uncached.readHeaders(executor)).thenReturn(UnmodifiableFuture.completedFuture(headers));
    when(uncached.read(any(), any())).thenAnswer(invocation -> HttpResponse.of("foo"));
    when(uncached.aggregate(any())).thenAnswer(
            invocation -> UnmodifiableFuture.completedFuture(HttpFile.of(HttpData.ofUtf8("foo"), 0)));

    final HttpFile cached = HttpFile.ofCached(uncached, 3);

    // Ensure readAttributes() is not cached.
    assertThat(cached.readAttributes(executor).join()).isSameAs(attrs);
    verify(uncached, times(1)).readAttributes(executor);
    verifyNoMoreInteractions(uncached);
    clearInvocations(uncached);

    assertThat(cached.readAttributes(executor).join()).isSameAs(attrs);
    verify(uncached, times(1)).readAttributes(executor);
    verifyNoMoreInteractions(uncached);
    clearInvocations(uncached);

    // Ensure readHeaders() is not cached.
    assertThat(cached.readHeaders(executor).join()).isSameAs(headers);
    verify(uncached, times(1)).readHeaders(executor);
    verifyNoMoreInteractions(uncached);
    clearInvocations(uncached);

    assertThat(cached.readHeaders(executor).join()).isSameAs(headers);
    verify(uncached, times(1)).readHeaders(executor);
    verifyNoMoreInteractions(uncached);
    clearInvocations(uncached);

    // First read() should trigger uncached.aggregate().
    HttpResponse res = cached.read(executor, alloc).join();
    assertThat(res).isNotNull();
    assertThat(res.aggregate().join().contentUtf8()).isEqualTo("foo");
    verify(uncached, times(1)).readAttributes(executor);
    verify(uncached, times(1)).aggregate(executor);
    verifyNoMoreInteractions(uncached);
    clearInvocations(uncached);

    // Second read() should not trigger uncached.aggregate().
    res = cached.read(executor, alloc).join();
    assertThat(res).isNotNull();
    assertThat(res.aggregate().join().contentUtf8()).isEqualTo("foo");
    verify(uncached, times(1)).readAttributes(executor);
    verifyNoMoreInteractions(uncached);
    clearInvocations(uncached);

    // Update the uncached file's attributes to invalidate the cache.
    final HttpFileAttributes newAttrs = new HttpFileAttributes(3, 1);
    when(uncached.readAttributes(executor)).thenReturn(UnmodifiableFuture.completedFuture(newAttrs));
    when(uncached.aggregate(any())).thenAnswer(
            invocation -> UnmodifiableFuture.completedFuture(HttpFile.of(HttpData.ofUtf8("bar"), 1)));

    // Make sure read() invalidates the cache and triggers uncached.aggregate().
    res = cached.read(executor, alloc).join();
    assertThat(res).isNotNull();
    assertThat(res.aggregate().join().contentUtf8()).isEqualTo("bar");
    verify(uncached, times(1)).readAttributes(executor);
    verify(uncached, times(1)).aggregate(executor);
    verifyNoMoreInteractions(uncached);
    clearInvocations(uncached);
}
 
Example 15
Source File: StringResponseConverterFunctionTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static HttpResponse from(Object result) throws Exception {
    final ResponseHeaders headers =
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8);
    return function.convertResponse(ctx, headers, result, DEFAULT_TRAILERS);
}
 
Example 16
Source File: HttpResult.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link HttpResult} with the specified content and the {@link HttpStatus#OK} status.
 *
 * @param content the content of the response
 */
static <T> HttpResult<T> of(T content) {
    return new DefaultHttpResult<>(ResponseHeaders.of(HttpStatus.OK),
                                   requireNonNull(content, "content"));
}
 
Example 17
Source File: HttpResult.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link HttpResult} with the specified {@link HttpStatus}, content and trailers.
 *
 * @param status the HTTP status
 * @param content the content of the response
 * @param trailers the HTTP trailers
 */
static <T> HttpResult<T> of(HttpStatus status, T content, HttpHeaders trailers) {
    return new DefaultHttpResult<>(ResponseHeaders.of(status), requireNonNull(content, "content"),
                                   trailers);
}
 
Example 18
Source File: HttpResult.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link HttpResult} with the specified {@link HttpStatus} and content.
 *
 * @param status the HTTP status
 * @param content the content of the response
 */
static <T> HttpResult<T> of(HttpStatus status, T content) {
    return new DefaultHttpResult<>(ResponseHeaders.of(status), requireNonNull(content, "content"));
}
 
Example 19
Source File: HttpResult.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link HttpResult} with the specified {@link HttpStatus} and without content.
 *
 * @param status the HTTP status
 */
static <T> HttpResult<T> of(HttpStatus status) {
    return new DefaultHttpResult<>(ResponseHeaders.of(status));
}