Search in sources :

Example 1 with CodecException

use of io.micronaut.http.codec.CodecException in project micronaut-gcp by micronaut-projects.

the class GoogleFunctionHttpRequest method getBody.

@NonNull
@Override
public <T> Optional<T> getBody(@NonNull Argument<T> arg) {
    if (arg != null) {
        final Class<T> type = arg.getType();
        final MediaType contentType = getContentType().orElse(MediaType.APPLICATION_JSON_TYPE);
        if (body == null) {
            if (isFormSubmission(contentType)) {
                body = getParameters();
                if (ConvertibleValues.class == type) {
                    return (Optional<T>) Optional.of(body);
                } else {
                    return Optional.empty();
                }
            } else {
                final MediaTypeCodec codec = codecRegistry.findCodec(contentType, type).orElse(null);
                if (codec != null) {
                    try (InputStream inputStream = googleRequest.getInputStream()) {
                        if (ConvertibleValues.class == type) {
                            final Map map = codec.decode(Map.class, inputStream);
                            body = ConvertibleValues.of(map);
                            return (Optional<T>) Optional.of(body);
                        } else {
                            final T value = codec.decode(arg, inputStream);
                            body = value;
                            return Optional.ofNullable(value);
                        }
                    } catch (IOException e) {
                        throw new CodecException("Error decoding request body: " + e.getMessage(), e);
                    }
                }
            }
        } else {
            if (type.isInstance(body)) {
                return (Optional<T>) Optional.of(body);
            } else {
                if (body != httpParameters) {
                    final T result = ConversionService.SHARED.convertRequired(body, arg);
                    return Optional.ofNullable(result);
                }
            }
        }
    }
    return Optional.empty();
}
Also used : InputStream(java.io.InputStream) CodecException(io.micronaut.http.codec.CodecException) IOException(java.io.IOException) MutableConvertibleValuesMap(io.micronaut.core.convert.value.MutableConvertibleValuesMap) MediaTypeCodec(io.micronaut.http.codec.MediaTypeCodec) NonNull(io.micronaut.core.annotation.NonNull)

Aggregations

NonNull (io.micronaut.core.annotation.NonNull)1 MutableConvertibleValuesMap (io.micronaut.core.convert.value.MutableConvertibleValuesMap)1 CodecException (io.micronaut.http.codec.CodecException)1 MediaTypeCodec (io.micronaut.http.codec.MediaTypeCodec)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1