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;
}
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);
}
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");
}
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);
}
});
}
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);
}
});
}
}
Aggregations