Search in sources :

Example 1 with MediaTypeCodec

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

the class GooglePartBinder method bind.

@Override
public BindingResult<T> bind(ArgumentConversionContext<T> context, HttpRequest<?> source) {
    if (source instanceof GoogleFunctionHttpRequest) {
        GoogleFunctionHttpRequest<?> googleRequest = (GoogleFunctionHttpRequest<?>) source;
        final com.google.cloud.functions.HttpRequest nativeRequest = googleRequest.getNativeRequest();
        final Argument<T> argument = context.getArgument();
        final String partName = context.getAnnotationMetadata().stringValue(Part.class).orElse(argument.getName());
        final HttpPart part = nativeRequest.getParts().get(partName);
        if (part != null) {
            final Class<T> type = argument.getType();
            if (HttpPart.class.isAssignableFrom(type)) {
                // noinspection unchecked
                return () -> (Optional<T>) Optional.of(part);
            } else if (String.class.isAssignableFrom(type)) {
                try (BufferedReader reader = part.getReader()) {
                    final String content = IOUtils.readText(reader);
                    return () -> (Optional<T>) Optional.of(content);
                } catch (IOException e) {
                    throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Unable to read part [" + partName + "]: " + e.getMessage());
                }
            } else if (byte[].class.isAssignableFrom(type)) {
                try (InputStream is = part.getInputStream()) {
                    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                    int nRead;
                    byte[] data = new byte[16384];
                    while ((nRead = is.read(data, 0, data.length)) != -1) {
                        buffer.write(data, 0, nRead);
                    }
                    final byte[] content = buffer.toByteArray();
                    return () -> (Optional<T>) Optional.of(content);
                } catch (IOException e) {
                    throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Unable to read part [" + partName + "]: " + e.getMessage());
                }
            } else {
                final MediaType contentType = part.getContentType().map(MediaType::new).orElse(null);
                if (contentType != null) {
                    final MediaTypeCodec codec = codecRegistry.findCodec(contentType, type).orElse(null);
                    if (codec != null) {
                        try (InputStream inputStream = part.getInputStream()) {
                            final T content = codec.decode(argument, inputStream);
                            return () -> (Optional<T>) Optional.of(content);
                        } catch (IOException e) {
                            throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Unable to read part [" + partName + "]: " + e.getMessage());
                        }
                    }
                }
            }
        }
    }
    return BindingResult.UNSATISFIED;
}
Also used : Optional(java.util.Optional) InputStream(java.io.InputStream) HttpStatusException(io.micronaut.http.exceptions.HttpStatusException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpPart(com.google.cloud.functions.HttpRequest.HttpPart) Part(io.micronaut.http.annotation.Part) HttpPart(com.google.cloud.functions.HttpRequest.HttpPart) BufferedReader(java.io.BufferedReader) MediaType(io.micronaut.http.MediaType) MediaTypeCodec(io.micronaut.http.codec.MediaTypeCodec)

Example 2 with MediaTypeCodec

use of io.micronaut.http.codec.MediaTypeCodec 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)

Example 3 with MediaTypeCodec

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

the class HttpFunction method toGoogleRequest.

private HttpRequest toGoogleRequest(io.micronaut.http.HttpRequest<?> request) {
    Map<String, List<String>> headers = new LinkedHashMap<>();
    Map<String, List<String>> parameters = new LinkedHashMap<>();
    request.getHeaders().forEach(headers::put);
    request.getParameters().forEach(parameters::put);
    Object body = request.getBody().orElse(null);
    try {
        Cookies cookies = request.getCookies();
        cookies.forEach((s, cookie) -> {
            if (cookie instanceof NettyCookie) {
                headers.computeIfAbsent(HttpHeaders.COOKIE, s1 -> new ArrayList<>()).add(ClientCookieEncoder.STRICT.encode(((NettyCookie) cookie).getNettyCookie()));
            }
        });
    } catch (UnsupportedOperationException e) {
    // not all request types support retrieving cookies
    }
    return new HttpRequest() {

        @Override
        public String getMethod() {
            return request.getMethodName();
        }

        @Override
        public String getUri() {
            return request.getUri().toString();
        }

        @Override
        public String getPath() {
            return request.getPath();
        }

        @Override
        public Optional<String> getQuery() {
            return Optional.of(request.getUri().getQuery());
        }

        @Override
        public Map<String, List<String>> getQueryParameters() {
            return parameters;
        }

        @Override
        public Map<String, HttpPart> getParts() {
            return Collections.emptyMap();
        }

        @Override
        public Optional<String> getContentType() {
            List<String> values = headers.get(HttpHeaders.CONTENT_TYPE);
            if (values != null) {
                Iterator<String> i = values.iterator();
                if (i.hasNext()) {
                    return Optional.ofNullable(i.next());
                }
            }
            return Optional.empty();
        }

        @Override
        public long getContentLength() {
            List<String> values = headers.get(HttpHeaders.CONTENT_LENGTH);
            if (values != null) {
                Iterator<String> i = values.iterator();
                if (i.hasNext()) {
                    return Long.parseLong(i.next());
                }
            }
            return 0;
        }

        @Override
        public Optional<String> getCharacterEncoding() {
            List<String> values = headers.get(HttpHeaders.CONTENT_ENCODING);
            if (values != null) {
                Iterator<String> i = values.iterator();
                if (i.hasNext()) {
                    return Optional.ofNullable(i.next());
                }
            }
            return Optional.empty();
        }

        @Override
        public InputStream getInputStream() {
            if (body != null) {
                if (body instanceof byte[]) {
                    return new ByteArrayInputStream((byte[]) body);
                } else {
                    MediaType mediaType = getContentType().map(MediaType::new).orElse(null);
                    if (mediaType != null) {
                        MediaTypeCodec codec = httpHandler.getMediaTypeCodecRegistry().findCodec(mediaType).orElse(null);
                        if (codec != null) {
                            byte[] bytes = codec.encode(body);
                            return new ByteArrayInputStream(bytes);
                        }
                    } else {
                        return new ByteArrayInputStream(body.toString().getBytes(StandardCharsets.UTF_8));
                    }
                }
            }
            return new ByteArrayInputStream(new byte[0]);
        }

        @Override
        public BufferedReader getReader() {
            return new BufferedReader(new InputStreamReader(getInputStream(), StandardCharsets.UTF_8));
        }

        @Override
        public Map<String, List<String>> getHeaders() {
            return headers;
        }
    };
}
Also used : ServletExchange(io.micronaut.servlet.http.ServletExchange) Environment(io.micronaut.context.env.Environment) MediaTypeCodec(io.micronaut.http.codec.MediaTypeCodec) java.util(java.util) Logger(org.slf4j.Logger) ApplicationContextBuilder(io.micronaut.context.ApplicationContextBuilder) DefaultServletExchange(io.micronaut.servlet.http.DefaultServletExchange) HttpRequest(com.google.cloud.functions.HttpRequest) LoggerFactory(org.slf4j.LoggerFactory) HttpResponse(com.google.cloud.functions.HttpResponse) FunctionInitializer(io.micronaut.function.executor.FunctionInitializer) io.micronaut.http(io.micronaut.http) MacAddressUtil(io.netty.util.internal.MacAddressUtil) StandardCharsets(java.nio.charset.StandardCharsets) ServletHttpHandler(io.micronaut.servlet.http.ServletHttpHandler) NonNull(io.micronaut.core.annotation.NonNull) ApplicationContext(io.micronaut.context.ApplicationContext) PlatformDependent(io.netty.util.internal.PlatformDependent) java.io(java.io) NettyCookie(io.micronaut.http.netty.cookies.NettyCookie) ClientCookieEncoder(io.netty.handler.codec.http.cookie.ClientCookieEncoder) Argument(io.micronaut.core.type.Argument) ConversionService(io.micronaut.core.convert.ConversionService) Cookies(io.micronaut.http.cookie.Cookies) HttpRequest(com.google.cloud.functions.HttpRequest) NettyCookie(io.micronaut.http.netty.cookies.NettyCookie) Cookies(io.micronaut.http.cookie.Cookies) MediaTypeCodec(io.micronaut.http.codec.MediaTypeCodec)

Aggregations

MediaTypeCodec (io.micronaut.http.codec.MediaTypeCodec)3 NonNull (io.micronaut.core.annotation.NonNull)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 HttpRequest (com.google.cloud.functions.HttpRequest)1 HttpPart (com.google.cloud.functions.HttpRequest.HttpPart)1 HttpResponse (com.google.cloud.functions.HttpResponse)1 ApplicationContext (io.micronaut.context.ApplicationContext)1 ApplicationContextBuilder (io.micronaut.context.ApplicationContextBuilder)1 Environment (io.micronaut.context.env.Environment)1 ConversionService (io.micronaut.core.convert.ConversionService)1 MutableConvertibleValuesMap (io.micronaut.core.convert.value.MutableConvertibleValuesMap)1 Argument (io.micronaut.core.type.Argument)1 FunctionInitializer (io.micronaut.function.executor.FunctionInitializer)1 io.micronaut.http (io.micronaut.http)1 MediaType (io.micronaut.http.MediaType)1 Part (io.micronaut.http.annotation.Part)1 CodecException (io.micronaut.http.codec.CodecException)1 Cookies (io.micronaut.http.cookie.Cookies)1 HttpStatusException (io.micronaut.http.exceptions.HttpStatusException)1