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

The following examples show how to use com.linecorp.armeria.common.HttpResponse#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: RestfulJsonResponseConverter.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 HttpRequest request = RequestContext.current().request();
        final HttpData httpData =
                resObj != null &&
                resObj.getClass() == Object.class ? EMPTY_RESULT
                                                  : HttpData.wrap(Jackson.writeValueAsBytes(resObj));

        final ResponseHeadersBuilder builder = headers.toBuilder();
        if (HttpMethod.POST == request.method()) {
            builder.status(HttpStatus.CREATED);
        }
        if (builder.contentType() == null) {
            builder.contentType(MediaType.JSON_UTF_8);
        }
        return HttpResponse.of(builder.build(), httpData, trailingHeaders);
    } catch (JsonProcessingException e) {
        return HttpApiUtil.newResponse(ctx, HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
}
 
Example 2
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 3
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 4
Source File: AbstractPooledHttpService.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Serves the specified {@link PooledHttpRequest} by delegating it to the matching {@code 'doMETHOD()'}
 * method.
 */
@Override
public final PooledHttpResponse serve(ServiceRequestContext ctx, PooledHttpRequest req) throws Exception {
    final HttpResponse response;
    switch (req.method()) {
        case OPTIONS:
            response = doOptions(ctx, req);
            break;
        case GET:
            response = doGet(ctx, req);
            break;
        case HEAD:
            response = doHead(ctx, req);
            break;
        case POST:
            response = doPost(ctx, req);
            break;
        case PUT:
            response = doPut(ctx, req);
            break;
        case PATCH:
            response = doPatch(ctx, req);
            break;
        case DELETE:
            response = doDelete(ctx, req);
            break;
        case TRACE:
            response = doTrace(ctx, req);
            break;
        default:
            response = HttpResponse.of(HttpStatus.METHOD_NOT_ALLOWED);
            break;
    }
    return PooledHttpResponse.of(response);
}
 
Example 5
Source File: ExceptionHandlerService.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse handleException(ServiceRequestContext ctx, HttpRequest req, Throwable cause) {
    if (cause instanceof GloballyGeneralException) {
        return HttpResponse.of(HttpStatus.FORBIDDEN);
    }
    // To the next exception handler.
    return ExceptionHandlerFunction.fallthrough();
}
 
Example 6
Source File: AnnotatedService.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse convertResponse(ServiceRequestContext ctx,
                                    ResponseHeaders headers,
                                    @Nullable Object result,
                                    HttpHeaders trailers) throws Exception {
    if (result instanceof HttpResponse) {
        return (HttpResponse) result;
    }
    try (SafeCloseable ignored = ctx.push()) {
        for (final ResponseConverterFunction func : functions) {
            try {
                return func.convertResponse(ctx, headers, result, trailers);
            } catch (FallthroughException ignore) {
                // Do nothing.
            } catch (Exception e) {
                throw new IllegalStateException(
                        "Response converter " + func.getClass().getName() +
                        " cannot convert a result to HttpResponse: " + result, e);
            }
        }
    }
    // There is no response converter which is able to convert 'null' result to a response.
    // In this case, a response with the specified HTTP headers would be sent.
    // If you want to force to send '204 No Content' for this case, add
    // 'NullToNoContentResponseConverterFunction' to the list of response converters.
    if (result == null) {
        return HttpResponse.of(headers, HttpData.empty(), trailers);
    }
    throw new IllegalStateException(
            "No response converter exists for a result: " + result.getClass().getName());
}
 
Example 7
Source File: AnnotatedServiceFactoryTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Put
public HttpResponse put() {
    return HttpResponse.of(HttpStatus.OK);
}
 
Example 8
Source File: AnnotatedServiceExceptionHandlerTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Get("/handler3")
@Decorator(ExceptionThrowingDecorator.class)
public HttpResponse handler3(ServiceRequestContext ctx, HttpRequest req) {
    return HttpResponse.of(HttpStatus.OK);
}
 
Example 9
Source File: TokenBucketThrottlingStrategyTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req)
        throws Exception {
    return HttpResponse.of(HttpStatus.OK);
}
 
Example 10
Source File: AnnotatedServiceFactoryTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Get
@Post
public HttpResponse noGetPostMapping() {
    return HttpResponse.of(HttpStatus.OK);
}
 
Example 11
Source File: AbstractPooledHttpServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected HttpResponse doPost(ServiceRequestContext ctx, PooledHttpRequest req) {
    return HttpResponse.of("post");
}
 
Example 12
Source File: ThrottlingServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req)
        throws Exception {
    return HttpResponse.of(HttpStatus.OK);
}
 
Example 13
Source File: HelloService.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Get("/plaintext")
public HttpResponse plaintext() {
  return HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, PLAINTEXT);
}
 
Example 14
Source File: CompositeServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) {
    return HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8,
                           "%s:%s:%s:%s", name, ctx.path(), ctx.mappedPath(), ctx.decodedMappedPath());
}
 
Example 15
Source File: AbstractPooledHttpServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected HttpResponse doOptions(ServiceRequestContext ctx, PooledHttpRequest req) {
    return HttpResponse.of("options");
}
 
Example 16
Source File: AnnotatedServiceFactoryTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Post("/")
public HttpResponse post() {
    return HttpResponse.of(HttpStatus.OK);
}
 
Example 17
Source File: AnnotatedServiceFactoryTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Patch
public HttpResponse patch() {
    return HttpResponse.of(HttpStatus.OK);
}
 
Example 18
Source File: RedirectServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    return HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, "SERVICE_BRANCH_2");
}
 
Example 19
Source File: AnnotatedServiceFactoryTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Get("/getMapping")
public HttpResponse getMapping() {
    return HttpResponse.of(HttpStatus.OK);
}
 
Example 20
Source File: AbstractHttpService.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Handles a {@link HttpMethod#POST POST} request.
 * This method sends a {@link HttpStatus#METHOD_NOT_ALLOWED 405 Method Not Allowed} response by default.
 */
protected HttpResponse doPost(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    return HttpResponse.of(HttpStatus.METHOD_NOT_ALLOWED);
}