Search in sources :

Example 1 with Collector

use of io.helidon.common.reactive.Collector in project helidon by oracle.

the class RestApiBase method handleBytesResponse.

/**
 * Handle bytes response for optional bytes entity.
 * This method checks if this was a success and if the response should contain an entity.
 * For success, it returns a response using the provided response builder.
 * For failures, returns an error.
 *
 * @param path requested path
 * @param request API request
 * @param method HTTP method
 * @param requestId request ID
 * @param response the web client response
 * @param responseBuilder builder to configure success response
 * @param <R> type of the optional part of the response
 * @param <T> type of the response
 *
 * @return future with response
 */
protected <R, T extends ApiOptionalResponse<R>> Single<T> handleBytesResponse(String path, ApiRequest<?> request, Http.RequestMethod method, String requestId, WebClientResponse response, ApiOptionalResponse.BuilderBase<?, T, byte[], R> responseBuilder) {
    Http.ResponseStatus status = response.status();
    boolean success = (Http.Status.Family.of(status.code()) == Http.ResponseStatus.Family.SUCCESSFUL) || isSuccess(path, request, method, requestId, status);
    boolean isEntityExpected = (Http.Status.Family.of(status.code()) == Http.ResponseStatus.Family.SUCCESSFUL) || isEntityExpected(path, request, method, requestId, status);
    if (success) {
        if (isEntityExpected) {
            return response.content().map(DataChunk::bytes).collect(new Collector<byte[], byte[]>() {

                private final ByteArrayOutputStream baos = new ByteArrayOutputStream();

                @Override
                public void collect(byte[] item) {
                    baos.writeBytes(item);
                }

                @Override
                public byte[] value() {
                    return baos.toByteArray();
                }
            }).map(it -> responseBuilder.headers(response.headers()).status(status).requestId(requestId).entity(it).build());
        } else {
            return emptyResponse(path, request, method, requestId, response, responseBuilder);
        }
    } else {
        return errorResponse(path, request, method, requestId, response);
    }
}
Also used : Collector(io.helidon.common.reactive.Collector) Http(io.helidon.common.http.Http) DataChunk(io.helidon.common.http.DataChunk) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Aggregations

DataChunk (io.helidon.common.http.DataChunk)1 Http (io.helidon.common.http.Http)1 Collector (io.helidon.common.reactive.Collector)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1