io.micronaut.http.HttpResponse Java Examples

The following examples show how to use io.micronaut.http.HttpResponse. 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: SkillController.java    From micronaut-aws with Apache License 2.0 8 votes vote down vote up
/**
 * Handles a POST request. Based on the request parameters, invokes the right method on the {@code Skill}.
 *
 * @param httpHeaders HTTP Headers
 * @param body HTTP Request Body byte array
 * @return response object that contains the response the servlet sends to the client
 */
@Post
public HttpResponse doPost(HttpHeaders httpHeaders,
                           @Body String body) {
    try {
        byte[] serializedRequestEnvelope = body.getBytes(AskHttpServerConstants.CHARACTER_ENCODING);
        final RequestEnvelope requestEnvelope = objectMapper.readValue(serializedRequestEnvelope, RequestEnvelope.class);
        requestEnvelopeVerificationService.verify(httpHeaders, serializedRequestEnvelope, requestEnvelope);
        ResponseEnvelope responseEnvelope = requestEnvelopeService.process(requestEnvelope);
        if (responseEnvelope != null) {
            return HttpResponse.ok(responseEnvelope);
        }

    } catch (IOException e) {

        if (LOG.isErrorEnabled()) {
            LOG.error("Unable to parse a byte array to RequestEnvelope");
        }
    }
    return HttpResponse.badRequest();
}
 
Example #2
Source File: AdapterTest.java    From java-slack-sdk with MIT License 6 votes vote down vote up
@Test
public void toMicronautResponse() {
    AppConfig config = AppConfig.builder().build();
    SlackAppMicronautAdapter adapter = new SlackAppMicronautAdapter(config);

    String body = "{\"text\":\"Hi there!\"}";
    Response slackResponse = Response.json(200, body);
    Map<String, List<String>> headers = new HashMap<>();
    headers.put("Set-Cookie", Arrays.asList("foo=bar", "id=123"));
    slackResponse.setHeaders(headers);
    HttpResponse<String> response = adapter.toMicronautResponse(slackResponse);
    assertNotNull(response);
    assertEquals(200, response.getStatus().getCode());
    assertEquals(body.length(), response.getContentLength());
    assertEquals("application/json; charset=utf-8", response.getHeaders().getContentType().get());
}
 
Example #3
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 #4
Source File: SlackAppMicronautAdapter.java    From java-slack-sdk with MIT License 6 votes vote down vote up
public HttpResponse<String> toMicronautResponse(Response resp) {
    HttpStatus status = HttpStatus.valueOf(resp.getStatusCode());
    MutableHttpResponse<String> response = micronautResponseFactory.status(status);
    for (Map.Entry<String, List<String>> header : resp.getHeaders().entrySet()) {
        String name = header.getKey();
        for (String value : header.getValue()) {
            response.header(name, value);
        }
    }
    response.body(resp.getBody());
    response.contentType(resp.getContentType());
    if (resp.getBody() != null) {
        response.contentLength(resp.getBody().length());
    } else {
        response.contentLength(0);
    }
    return response;
}
 
Example #5
Source File: CommandsTest.java    From java-slack-sdk with MIT License 5 votes vote down vote up
@Test
public void regexp_matching() {
    MutableHttpRequest<String> request = HttpRequest.POST("/slack/events", "");
    request.header("Content-Type", "application/x-www-form-urlencoded");
    String timestamp = "" + (System.currentTimeMillis() / 1000);
    request.header(SlackSignature.HeaderNames.X_SLACK_REQUEST_TIMESTAMP, timestamp);
    String signature = signatureGenerator.generate(timestamp, submissionBody);
    request.header(SlackSignature.HeaderNames.X_SLACK_SIGNATURE, signature);
    request.body(submissionBody);
    HttpResponse<String> response = client.toBlocking().exchange(request, String.class);
    Assertions.assertEquals(200, response.getStatus().getCode());
    Assertions.assertEquals("{\"text\":\"/submission-no.2019\"}", response.getBody().get());
}
 
Example #6
Source File: GoogleAuthFilter.java    From micronaut-gcp with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<? extends HttpResponse<?>> doFilter(MutableHttpRequest<?> request, ClientFilterChain chain) {
    Flowable<String> token = Flowable.fromCallable(() -> encodeURI(request))
            .flatMap(authURI -> authClient.retrieve(HttpRequest.GET(authURI).header(
                    METADATA_FLAVOR, GOOGLE
            )));

    return token.flatMap(t -> chain.proceed(request.bearerAuth(t)));
}
 
Example #7
Source File: CommandsTest.java    From java-slack-sdk with MIT License 5 votes vote down vote up
@Test
public void command() {
    MutableHttpRequest<String> request = HttpRequest.POST("/slack/events", "");
    request.header("Content-Type", "application/x-www-form-urlencoded");
    String timestamp = "" + (System.currentTimeMillis() / 1000);
    request.header(SlackSignature.HeaderNames.X_SLACK_REQUEST_TIMESTAMP, timestamp);
    String signature = signatureGenerator.generate(timestamp, helloBody);
    request.header(SlackSignature.HeaderNames.X_SLACK_SIGNATURE, signature);
    request.body(helloBody);
    HttpResponse<String> response = client.toBlocking().exchange(request, String.class);
    Assertions.assertEquals(200, response.getStatus().getCode());
    Assertions.assertEquals("{\"text\":\"Thanks!\"}", response.getBody().get());
}
 
Example #8
Source File: ControllerTest.java    From java-slack-sdk with MIT License 5 votes vote down vote up
@Test
public void test() throws Exception {
    AppConfig config = AppConfig.builder().signingSecret("secret").build();
    SlackAppController controller = new SlackAppController(new App(config), new SlackAppMicronautAdapter(config));
    assertNotNull(controller);

    HttpRequest<String> req = mock(HttpRequest.class);
    SimpleHttpHeaders headers = new SimpleHttpHeaders(new HashMap<>(), new DefaultConversionService());
    when(req.getHeaders()).thenReturn(headers);
    SimpleHttpParameters parameters = new SimpleHttpParameters(new HashMap<>(), new DefaultConversionService());
    when(req.getParameters()).thenReturn(parameters);

    HttpResponse<String> response = controller.dispatch(req, "token=random&ssl_check=1");
    assertEquals(200, response.getStatus().getCode());
}
 
Example #9
Source File: MusicController.java    From kyoko with MIT License 5 votes vote down vote up
@Get("/{id}/queue")
public Single<HttpResponse> queue(@RequestAttribute("session") Session session, long id) {
    if (!session.hasGuild(id)) {
        return Single.just(ErrorResponse.get(ErrorCode.UNKNOWN_GUILD));
    }

    return channel.send(new JsonObject().put("cmd", "queue").put("guild", id))
            .singleOrError()
            .timeout(10, TimeUnit.SECONDS)
            .flatMap(reply -> Single.<HttpResponse>just(HttpResponse.ok(reply.encode())))
            .onErrorResumeNext(err -> Single.just(HttpResponse.ok("{\"queue\":[],\"repeating\":false}")));
}
 
Example #10
Source File: AuthController.java    From kyoko with MIT License 5 votes vote down vote up
@Get("/oauth2exchange")
Single<HttpResponse> oauth2exchange(@Nullable String code, @Nullable Boolean bot) {
    var scope = "identify guilds" + (bot != null && bot ? " bot" : "");
    return sessionManager.exchangeCode(code, Settings.instance().apiUrls().get("redirect"), scope)
            .switchIfEmpty(Maybe.error(new NoSuchElementException("no element returned")))
            .doOnError(err -> logger.error("Error while exchanging OAuth2 code!", err))
            .flatMapSingle(session -> Single.<HttpResponse>just(HttpResponse.ok(new OAuth2ExchangeResponse(session.getToken()))))
            .onErrorReturnItem(ErrorResponse.get(ErrorCode.INVALID_OAUTH2_CODE));
}
 
Example #11
Source File: UserController.java    From kyoko with MIT License 5 votes vote down vote up
@Get("/guilds/{id}")
Single<HttpResponse> guild(@RequestAttribute("session") Session session, long id) {
    if (!session.hasGuild(id)) {
        return Single.just(ErrorResponse.get(ErrorCode.UNKNOWN_GUILD));
    }

    return Flowable.fromFuture(Main.getCatnip().rest().guild()
            .getGuild(String.valueOf(id))
            .thenApply(KGuildExt::new)
            .toCompletableFuture())
            .singleOrError()
            .flatMap(guild -> Single.<MutableHttpResponse<?>>just(HttpResponse.ok(guild))
                    .onErrorReturn(err -> ErrorResponse.get(ErrorCode.UNKNOWN_GUILD)));
}
 
Example #12
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 #13
Source File: LoginTest.java    From micronaut-microservices-poc with Apache License 2.0 5 votes vote down vote up
@Test
public void cantLoginWithInvalidCredentials() {
    try {
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials("jimmy.solid","secret111");
        HttpRequest loginRequest = HttpRequest.POST("/login", upc);
        HttpResponse<BearerAccessRefreshToken> rsp = httpClient.toBlocking().exchange(loginRequest, BearerAccessRefreshToken.class);
        fail();
    } catch (HttpClientResponseException ex) {
        assertThat(ex.getStatus().getCode()).isEqualTo(HttpStatus.UNAUTHORIZED.getCode());
    }
    
}
 
Example #14
Source File: LoginTest.java    From micronaut-microservices-poc with Apache License 2.0 5 votes vote down vote up
@Test
public void canLoginWithValidCredentials() {
    UsernamePasswordCredentials upc = new UsernamePasswordCredentials("jimmy.solid","secret");
    HttpRequest loginRequest = HttpRequest.POST("/login", upc);
    HttpResponse<BearerAccessRefreshToken> rsp = httpClient.toBlocking().exchange(loginRequest, BearerAccessRefreshToken.class);
    
    assertThat(rsp.getStatus().getCode()).isEqualTo(200);
    assertThat(rsp.getBody().get().getUsername()).isEqualTo("jimmy.solid");
}
 
Example #15
Source File: HelloWorldMicronautTest.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
@Get("/multi-cookie")
HttpResponse<String> multiCookie() {
    final MutableHttpResponse<String> response = HttpResponse.ok(BODY_TEXT_RESPONSE);
    response.cookie(Cookie.of(COOKIE_NAME, COOKIE_VALUE).domain(COOKIE_DOMAIN).path(COOKIE_PATH))
            .cookie(Cookie.of(COOKIE_NAME + "2", COOKIE_VALUE + "2").domain(COOKIE_DOMAIN).path(COOKIE_PATH));
    return response;
}
 
Example #16
Source File: GreetingClient.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
@GetMapping("/greeting-status{?name}")
HttpResponse<Greeting> greetWithStatus(@Nullable String name);
 
Example #17
Source File: ErrorResponse.java    From kyoko with MIT License 4 votes vote down vote up
public static MutableHttpResponse<?> get(HttpStatus status) {
    return HttpResponse.status(status).body(new Response("Unknown error", 0));
}
 
Example #18
Source File: ErrorResponse.java    From kyoko with MIT License 4 votes vote down vote up
public static MutableHttpResponse<?> get(HttpStatus status, String message, int code) {
    return HttpResponse.status(status).body(new Response(message, code));
}
 
Example #19
Source File: ErrorResponse.java    From kyoko with MIT License 4 votes vote down vote up
public static MutableHttpResponse<?> get(ErrorCode code) {
    return HttpResponse.status(code.getStatus()).body(new Response(code.getMessage(), code.getCode()));
}
 
Example #20
Source File: GreetingClient.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
@DeleteMapping("/greeting")
HttpResponse<?> deletePost();
 
Example #21
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 #22
Source File: HelloWorldMicronautTest.java    From micronaut-aws with Apache License 2.0 4 votes vote down vote up
@Get("/cookie")
HttpResponse<String> cookie() {
    final MutableHttpResponse<String> response = HttpResponse.ok(BODY_TEXT_RESPONSE);
    response.cookie(Cookie.of(COOKIE_NAME, COOKIE_VALUE).domain(COOKIE_DOMAIN).path(COOKIE_PATH));
    return response;
}
 
Example #23
Source File: HelloWorldMicronautTest.java    From micronaut-aws with Apache License 2.0 4 votes vote down vote up
@Get("/hello")
HttpResponse<String> hello() {
    return HttpResponse.ok(BODY_TEXT_RESPONSE)
            .header(CUSTOM_HEADER_KEY, CUSTOM_HEADER_VALUE);
}
 
Example #24
Source File: HelloWorldMicronautTest.java    From micronaut-aws with Apache License 2.0 4 votes vote down vote up
@Get("/")
HttpResponse<String> index() {
    return HttpResponse.ok(BODY_TEXT_RESPONSE)
                .header(CUSTOM_HEADER_KEY, CUSTOM_HEADER_VALUE);
}