io.micronaut.http.MediaType Java Examples

The following examples show how to use io.micronaut.http.MediaType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MicronautAwsProxyResponse.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
/**
 * Encode the body.
 * @return The body encoded as a String
 * @throws InvalidResponseObjectException If the body couldn't be encoded
 */
String encodeBody() throws InvalidResponseObjectException {
    if (body instanceof CharSequence) {
        return body.toString();
    }
    byte[] encoded = encodeInternal(handler.getJsonCodec());
    if (encoded != null) {
        final String contentType = getContentType().map(MediaType::toString).orElse(null);
        if (!isBinary(contentType)) {
            return new String(encoded, getCharacterEncoding());
        } else {
            response.setBase64Encoded(true);
            return Base64.getMimeEncoder().encodeToString(encoded);
        }
    }
    return null;
}
 
Example #2
Source File: MicronautAwsProxyResponse.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
private byte[] encodeInternal(MediaTypeCodec codec) throws InvalidResponseObjectException {
    byte[] encoded = null;
    try {
        if (body != null) {
            if (body instanceof ByteBuffer) {
                encoded = ((ByteBuffer) body).toByteArray();
            } else if (body instanceof byte[]) {
                encoded = (byte[]) body;
            } else {
                final Optional<MediaType> contentType = getContentType();
                if (!contentType.isPresent()) {
                    contentType(MediaType.APPLICATION_JSON_TYPE);
                }
                encoded = codec.encode(body);
            }
        }
    } catch (Exception e) {
        throw new InvalidResponseObjectException("Invalid Response: " + e.getMessage() , e);
    }
    return encoded;
}
 
Example #3
Source File: AbstractMicronautLambdaRuntime.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param handlerResponse Handler response object
 * @return If the handlerResponseType and the responseType are identical just returns the supplied object. However,
 * if the response type is of type {@link APIGatewayProxyResponseEvent} it attempts to serialized the handler response
 * as a JSON String and set it in the response body. If the object cannot be serialized, a 400 response is returned
 */
@Nullable
protected ResponseType createResponse(HandlerResponseType handlerResponse) {
    if (handlerResponseType == responseType) {
        logn(LogLevel.TRACE, "HandlerResponseType and ResponseType are identical");
        return (ResponseType) handlerResponse;

    } else if (responseType == APIGatewayProxyResponseEvent.class) {
        logn(LogLevel.TRACE, "response type is APIGatewayProxyResponseEvent");
        String json = serializeAsJsonString(handlerResponse);
        if (json != null) {
            return (ResponseType) respond(HttpStatus.OK, json, MediaType.APPLICATION_JSON);
        }
        return (ResponseType) respond(HttpStatus.BAD_REQUEST,
                "Could not serialize " + handlerResponse.toString() + " as json",
                MediaType.TEXT_PLAIN);
    }
    return null;
}
 
Example #4
Source File: CustomLoginHandlerTest.java    From micronaut-microservices-poc with Apache License 2.0 6 votes vote down vote up
@Test
public void customLoginHandler() {
    //when:
    HttpRequest request = HttpRequest.create(HttpMethod.POST, "/login")
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .body(new UsernamePasswordCredentials("jimmy.solid", "secret"));
    HttpResponse<CustomBearerAccessRefreshToken> rsp = httpClient.toBlocking().exchange(request, CustomBearerAccessRefreshToken.class);

    //then:
    assertThat(rsp.getStatus().getCode()).isEqualTo(200);
    assertThat(rsp.body()).isNotNull();
    assertThat(rsp.body().getAccessToken()).isNotNull();
    assertThat(rsp.body().getRefreshToken()).isNotNull();
    assertThat(rsp.body().getAvatar()).isNotNull();
    assertThat(rsp.body().getAvatar()).isEqualTo("static/avatars/jimmy_solid.png");
}
 
Example #5
Source File: CustomClaimsTest.java    From micronaut-microservices-poc with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomClaimsArePresentInJwt() {
    //when:
    HttpRequest request = HttpRequest.create(HttpMethod.POST, "/login")
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .body(new UsernamePasswordCredentials("jimmy.solid", "secret"));
    HttpResponse<AccessRefreshToken> rsp = httpClient.toBlocking().exchange(request, AccessRefreshToken.class);

    //then:
    assertThat(rsp.getStatus().getCode()).isEqualTo(200);
    assertThat(rsp.body()).isNotNull();
    assertThat(rsp.body().getAccessToken()).isNotNull();
    assertThat(rsp.body().getRefreshToken()).isNotNull();

    //when:
    String accessToken = rsp.body().getAccessToken();
    JwtTokenValidator tokenValidator = server.getApplicationContext().getBean(JwtTokenValidator.class);
    Authentication authentication = Flowable.fromPublisher(tokenValidator.validateToken(accessToken)).blockingFirst();

    //then:
    assertThat(authentication.getAttributes()).isNotNull();
    assertThat(authentication.getAttributes()).containsKey("roles");
    assertThat(authentication.getAttributes()).containsKey("iss");
    assertThat(authentication.getAttributes()).containsKey("exp");
    assertThat(authentication.getAttributes()).containsKey("iat");
    assertThat(authentication.getAttributes()).containsKey("avatar");
    assertThat(authentication.getAttributes().get("avatar")).isEqualTo("static/avatars/jimmy_solid.png");
}
 
Example #6
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<MediaType> getMediaTypes() {
    List<MediaType> mediaTypes = new ArrayList<>();
    mediaTypes.add(PROTOBUFFER_ENCODED_TYPE);
    return mediaTypes;
}
 
Example #7
Source File: AbstractSqlRepositoryOperations.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
private MediaTypeCodec resolveJsonCodec(List<MediaTypeCodec> codecs) {
    return CollectionUtils.isNotEmpty(codecs) ? codecs.stream().filter(c -> c.getMediaTypes().contains(MediaType.APPLICATION_JSON_TYPE)).findFirst().orElse(null) : null;
}
 
Example #8
Source File: MathController.java    From micronaut-test with Apache License 2.0 4 votes vote down vote up
@Get(uri = "/compute/{number}", processes = MediaType.TEXT_PLAIN)
String compute(Integer number) {
    return String.valueOf(mathService.compute(number));
}
 
Example #9
Source File: GraphQLController.java    From micronaut-graphql with Apache License 2.0 4 votes vote down vote up
/**
 * 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<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 = "";
    }

    // https://graphql.org/learn/serving-over-http/#post-request
    //
    // A standard GraphQL POST request should use the application/json content type,
    // and include a JSON-encoded body of the following form:
    //
    // {
    //   "query": "...",
    //   "operationName": "...",
    //   "variables": { "myVariable": "someValue", ... }
    // }

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

    // In addition to the above, we recommend supporting two additional cases:
    //
    // * If the "query" query string parameter is present (as in the GET example above),
    //   it should be parsed and handled in the same way as the HTTP GET case.

    if (query != null) {
        return executeRequest(query, operationName, convertVariablesJson(variables), httpRequest);
    }

    // * If the "application/graphql" Content-Type header is present,
    //   treat the HTTP POST body contents as the GraphQL query string.

    if (APPLICATION_GRAPHQL_TYPE.equals(contentType)) {
        return executeRequest(body, null, null, httpRequest);
    }

    throw new HttpStatusException(UNPROCESSABLE_ENTITY, "Could not process GraphQL request");
}
 
Example #10
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<MediaType> getMediaTypes() {
    List<MediaType> mediaTypes = new ArrayList<>();
    mediaTypes.add(PROTOBUFFER_ENCODED_TYPE);
    return mediaTypes;
}
 
Example #11
Source File: SlackAppController.java    From java-slack-sdk with MIT License 4 votes vote down vote up
@Post(value = "/events", consumes = {MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON})
public HttpResponse<String> dispatch(HttpRequest<String> request, @Body String body) throws Exception {
    Request<?> slackRequest = adapter.toSlackRequest(request, body);
    return adapter.toMicronautResponse(slackApp.run(slackRequest));
}
 
Example #12
Source File: JsonRpcController.java    From consensusj with Apache License 2.0 4 votes vote down vote up
@Post(produces = MediaType.APPLICATION_JSON)
public CompletableFuture<JsonRpcResponse<Object>> index(@Body JsonRpcRequest req) {
    log.info("JSON-RPC call: {}", req.getMethod());
    return jsonRpcService.call(req);
}
 
Example #13
Source File: JsonRpcController.java    From consensusj with Apache License 2.0 4 votes vote down vote up
@Post(produces = MediaType.APPLICATION_JSON)
public CompletableFuture<JsonRpcResponse<Object>> index(@Body JsonRpcRequest req) {
    log.debug("JSON-RPC call: {}", req.getMethod());
    return jsonRpcService.call(req);
}
 
Example #14
Source File: HelloController.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Get("/")
@Produces(MediaType.TEXT_PLAIN)
public String index() {
  return "Hello World!";
}
 
Example #15
Source File: PlainText.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Get(value = "/", produces = MediaType.TEXT_PLAIN)
Single<String> getPlainText() {
    return Single.just(TEXT);
}
 
Example #16
Source File: GreetController.java    From tutorials with MIT License 4 votes vote down vote up
@Post(value = "/{name}", consumes = MediaType.TEXT_PLAIN)
public String setGreeting(@Body String name)
{
    return greetingService.getGreeting() + name;
}