Search in sources :

Example 1 with MediaType

use of io.micronaut.http.MediaType 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 MediaType

use of io.micronaut.http.MediaType in project micronaut-views by micronaut-projects.

the class ViewsFilter method resolveMediaType.

/**
 * Resolves the response content type for the matched route.
 * @param response HTTP response
 * @param responseBody HTTP Response body
 * @return The resolved content type
 */
@NonNull
protected MediaType resolveMediaType(@NonNull HttpResponse<?> response, @Nullable Object responseBody) {
    Optional<AnnotationMetadata> routeMatch = response.getAttribute(HttpAttributes.ROUTE_MATCH, AnnotationMetadata.class);
    if (!routeMatch.isPresent()) {
        return MediaType.APPLICATION_JSON_TYPE;
    }
    AnnotationMetadata route = routeMatch.get();
    return route.getValue(Produces.class, MediaType.class).orElse((route.getValue(View.class).isPresent() || responseBody instanceof ModelAndView) ? MediaType.TEXT_HTML_TYPE : MediaType.APPLICATION_JSON_TYPE);
}
Also used : Produces(io.micronaut.http.annotation.Produces) MediaType(io.micronaut.http.MediaType) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) NonNull(io.micronaut.core.annotation.NonNull)

Example 3 with MediaType

use of io.micronaut.http.MediaType in project micronaut-graphql by micronaut-projects.

the class GraphQLController method post.

/**
 * Handles GraphQL {@code POST} requests.
 *
 * @param query         the GraphQL query
 * @param operationName the GraphQL operation name
 * @param variables     the GraphQL variables
 * @param body          the GraphQL request body
 * @param httpRequest   the HTTP request
 * @return the GraphQL response
 */
@Post(consumes = ALL, produces = APPLICATION_JSON, single = true)
public Publisher<MutableHttpResponse<String>> post(@Nullable @QueryValue("query") String query, @Nullable @QueryValue("operationName") String operationName, @Nullable @QueryValue("variables") String variables, @Nullable @Body String body, HttpRequest httpRequest) {
    Optional<MediaType> opt = httpRequest.getContentType();
    MediaType contentType = opt.orElse(null);
    if (body == null) {
        body = "";
    }
    if (APPLICATION_JSON_TYPE.equals(contentType)) {
        GraphQLRequestBody request = graphQLJsonSerializer.deserialize(body, GraphQLRequestBody.class);
        if (request.getQuery() == null) {
            request.setQuery("");
        }
        return executeRequest(request.getQuery(), request.getOperationName(), request.getVariables(), httpRequest);
    }
    if (query != null) {
        return executeRequest(query, operationName, convertVariablesJson(variables), httpRequest);
    }
    if (APPLICATION_GRAPHQL_TYPE.equals(contentType)) {
        return executeRequest(body, null, null, httpRequest);
    }
    throw new HttpStatusException(UNPROCESSABLE_ENTITY, "Could not process GraphQL request");
}
Also used : MediaType(io.micronaut.http.MediaType) HttpStatusException(io.micronaut.http.exceptions.HttpStatusException) Post(io.micronaut.http.annotation.Post)

Example 4 with MediaType

use of io.micronaut.http.MediaType in project micronaut-views by micronaut-projects.

the class ViewsFilter method doFilter.

@Override
public final Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
    return Flux.from(chain.proceed(request)).switchMap(response -> {
        Optional<String> optionalView = viewsResolver.resolveView(request, response);
        if (!optionalView.isPresent()) {
            LOG.debug("no view found");
            return Flux.just(response);
        }
        Object body = response.body();
        MediaType type = resolveMediaType(response, body);
        String view = optionalView.get();
        try {
            Optional<ViewsRenderer> optionalViewsRenderer = viewsRendererLocator.resolveViewsRenderer(view, type, body);
            if (!optionalViewsRenderer.isPresent()) {
                LOG.debug("no view renderer found for media type: {}, ignoring", type.toString());
                return Flux.just(response);
            }
            ModelAndView<?> modelAndView = new ModelAndView<>(view, body instanceof ModelAndView ? ((ModelAndView<?>) body).getModel().orElse(null) : body);
            viewsModelDecorator.decorate(request, modelAndView);
            Writable writable = optionalViewsRenderer.get().render(view, modelAndView.getModel().orElse(null), request);
            response.contentType(type);
            response.body(writable);
            return Flux.just(response);
        } catch (ViewNotFoundException e) {
            return Flux.error(e);
        }
    });
}
Also used : MediaType(io.micronaut.http.MediaType) Writable(io.micronaut.core.io.Writable) ViewNotFoundException(io.micronaut.views.exceptions.ViewNotFoundException)

Example 5 with MediaType

use of io.micronaut.http.MediaType in project micronaut-starter by micronaut-projects.

the class ApplicationController method home.

/**
 * Provides a description of the API.
 * @param request The request
 * @return A description of the API.
 */
@Get("/")
@Produces(MediaType.TEXT_PLAIN)
@ApiResponse(responseCode = "200", description = "A textual description of the API", content = @Content(mediaType = MediaType.TEXT_PLAIN))
HttpResponse<Writable> home(HttpRequest<?> request, @Parameter(hidden = true) RequestInfo info) {
    Collection<MediaType> accept = request.accept();
    URI redirectURI = configuration.getRedirectUri().orElse(null);
    if (accept.contains(MediaType.TEXT_HTML_TYPE) && redirectURI != null) {
        return HttpResponse.permanentRedirect(redirectURI);
    } else {
        return HttpResponse.ok(new Writable() {

            @Override
            public void writeTo(Writer out) {
            // no-op
            }

            @Override
            public void writeTo(OutputStream outputStream, @Nullable Charset charset) {
                new RockerWritable(new starterApi().serverURL(info.getServerURL()).micronautVersion(VersionInfo.getMicronautVersion())).write(outputStream);
            }
        });
    }
}
Also used : RockerWritable(io.micronaut.starter.template.RockerWritable) io.micronaut.starter.template.api.starterApi(io.micronaut.starter.template.api.starterApi) OutputStream(java.io.OutputStream) MediaType(io.micronaut.http.MediaType) RockerWritable(io.micronaut.starter.template.RockerWritable) Writable(io.micronaut.core.io.Writable) Charset(java.nio.charset.Charset) URI(java.net.URI) Writer(java.io.Writer) Produces(io.micronaut.http.annotation.Produces) Get(io.micronaut.http.annotation.Get) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse)

Aggregations

MediaType (io.micronaut.http.MediaType)5 Writable (io.micronaut.core.io.Writable)2 Produces (io.micronaut.http.annotation.Produces)2 HttpStatusException (io.micronaut.http.exceptions.HttpStatusException)2 HttpPart (com.google.cloud.functions.HttpRequest.HttpPart)1 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)1 NonNull (io.micronaut.core.annotation.NonNull)1 Get (io.micronaut.http.annotation.Get)1 Part (io.micronaut.http.annotation.Part)1 Post (io.micronaut.http.annotation.Post)1 MediaTypeCodec (io.micronaut.http.codec.MediaTypeCodec)1 RockerWritable (io.micronaut.starter.template.RockerWritable)1 io.micronaut.starter.template.api.starterApi (io.micronaut.starter.template.api.starterApi)1 ViewNotFoundException (io.micronaut.views.exceptions.ViewNotFoundException)1 ApiResponse (io.swagger.v3.oas.annotations.responses.ApiResponse)1 BufferedReader (java.io.BufferedReader)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1