Example usage for org.springframework.http ResponseEntity getStatusCode

List of usage examples for org.springframework.http ResponseEntity getStatusCode

Introduction

In this page you can find the example usage for org.springframework.http ResponseEntity getStatusCode.

Prototype

public HttpStatus getStatusCode() 

Source Link

Document

Return the HTTP status code of the response.

Usage

From source file:comsat.sample.actuator.ui.SampleActuatorUiApplicationPortTests.java

@Test
public void testMetrics() throws Exception {
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate()
            .getForEntity("http://localhost:" + this.managementPort + "/metrics", Map.class);
    assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
}

From source file:de.pentasys.playground.springbootexample.ManagementPortSampleActuatorApplicationTests.java

@Test
public void testHealth() throws Exception {
    ResponseEntity<String> entity = new TestRestTemplate("admin", getPassword())
            .getForEntity("http://localhost:" + this.managementPort + "/health", String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertTrue(entity.getBody().contains("\"status\" : \"UP\""));
}

From source file:io.jmnarloch.spring.cloud.ribbon.RibbonDiscoveryFilterTest.java

@Test
public void shouldRouteRequests() {

    // when//from ww w.ja v a2 s  . c om
    ResponseEntity<String> response = restOperations.getForEntity("http://local/message", String.class);

    // then
    assertEquals(HttpStatus.OK, response.getStatusCode());
}

From source file:io.kahu.hawaii.rest.DefaultResponseManagerTest.java

@Test
public void testToResponseWithRuntimeException() throws Exception {
    ResponseEntity<?> response = responseManager.toResponse(new Throwable());
    assertThat(response.getStatusCode(), is(equalTo(HttpStatus.OK)));

    response = responseManager.toResponse(new AssertionError());
    assertThat(response.getStatusCode(), is(equalTo(HttpStatus.OK)));

    response = responseManager.toResponse(new NullPointerException());
    assertThat(response.getStatusCode(), is(equalTo(HttpStatus.OK)));

    verify(logManager, times(3))//w w  w  . ja v  a2s .c o m
            .logIncomingCallEnd(Mockito.argThat(new TestInstanceOfMatcher<>(HawaiiException.class)));
}

From source file:org.workspace7.moviestore.utils.MovieDBHelper.java

/**
 * This method queries the external API and caches the movies, for the demo purpose we just query only first page
 *
 * @return - the status code of the invocation
 *//*from w  w w  .  ja  va 2s  .c  o  m*/
protected int queryAndCache() {

    if (this.moviesCache.isEmpty()) {

        log.info("No movies exist in cache, loading cache ..");

        UriComponentsBuilder moviesUri = UriComponentsBuilder
                .fromUriString(movieStoreProps.getApiEndpointUrl() + "/movie/popular")
                .queryParam("api_key", movieStoreProps.getApiKey());

        final URI requestUri = moviesUri.build().toUri();

        log.info("Request URI:{}", requestUri);

        ResponseEntity<String> response = restTemplate.getForEntity(requestUri, String.class);

        log.info("Response Status:{}", response.getStatusCode());

        Map<String, Movie> movieMap = new HashMap<>();

        if (200 == response.getStatusCode().value()) {
            String jsonBody = response.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode root = objectMapper.readTree(jsonBody);
                JsonNode results = root.path("results");
                results.elements().forEachRemaining(movieNode -> {
                    String id = movieNode.get("id").asText();
                    Movie movie = Movie.builder().id(id).overview(movieNode.get("overview").asText())
                            .popularity(movieNode.get("popularity").floatValue())
                            .posterPath("http://image.tmdb.org/t/p/w92" + movieNode.get("poster_path").asText())
                            .logoPath("http://image.tmdb.org/t/p/w45" + movieNode.get("poster_path").asText())
                            .title(movieNode.get("title").asText())
                            .price(ThreadLocalRandom.current().nextDouble(1.0, 10.0)).build();
                    movieMap.put(id, movie);
                });
            } catch (IOException e) {
                log.error("Error reading response:", e);
            }

            log.debug("Got {} movies", movieMap);
            moviesCache.putAll(movieMap);
        }
        return response.getStatusCode().value();
    } else {
        log.info("Cache already loaded with movies ... will use cache");
        return 200;
    }
}

From source file:comsat.sample.mustache.SampleWebMustacheApplicationTests.java

@Test
public void testMustacheErrorTemplate() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    HttpEntity<String> requestEntity = new HttpEntity<String>(headers);

    ResponseEntity<String> responseEntity = new TestRestTemplate().exchange(
            "http://localhost:" + this.port + "/does-not-exist", HttpMethod.GET, requestEntity, String.class);

    assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
    assertTrue("Wrong body:\n" + responseEntity.getBody(),
            responseEntity.getBody().contains("Something went wrong: 404 Not Found"));
}

From source file:io.pivotal.ecosystem.service.HelloControllerTest.java

@Test
public void testIt() {
    ResponseEntity<String> greeting = helloController.greeting(USER);
    assertNotNull(greeting);/*from w ww. jav  a 2  s .c  o  m*/
    assertEquals("Sorry, I don't think we've met.", greeting.getBody());
    assertEquals(HttpStatus.UNAUTHORIZED, greeting.getStatusCode());

    ResponseEntity<User> in = helloController.createUser(new User(USER, ROLE));

    assertNotNull(in);
    assertEquals(HttpStatus.CREATED, in.getStatusCode());
    User u = in.getBody();
    assertNotNull(u);
    assertEquals(USER, u.getName());
    assertNotNull(u.getPassword());

    greeting = helloController.greeting(USER);
    assertNotNull(greeting);
    assertEquals("Hello, foo !", greeting.getBody());
    assertEquals(HttpStatus.OK, greeting.getStatusCode());

    ResponseEntity<Void> out = helloController.deleteUser(USER);
    assertNotNull(out);
    assertEquals(HttpStatus.OK, out.getStatusCode());

    greeting = helloController.greeting(USER);
    assertNotNull(greeting);
    assertEquals("Sorry, I don't think we've met.", greeting.getBody());
    assertEquals(HttpStatus.UNAUTHORIZED, greeting.getStatusCode());
}

From source file:org.kuali.mobility.sakai.controllers.PrivateMessagesController.java

@RequestMapping(value = "/compose", method = RequestMethod.POST)
public String postMesssage(HttpServletRequest request, Model uiModel,
        @ModelAttribute("message") Message message, BindingResult result,
        @PathVariable("siteId") String siteId) {
    if (isValidMessage(message, result)) {
        User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY);
        ResponseEntity<String> response = sakaiPrivateTopicService.postMessage(message, siteId,
                user.getUserId());/* w  ww  . j a  va 2s.c  o m*/

        if (response.getStatusCode().value() < 200 || response.getStatusCode().value() >= 300) {
            Errors errors = ((Errors) result);
            errors.rejectValue("body", "", "There was an error posting your message. Please try again later.");
            uiModel.addAttribute("siteId", siteId);
            return "sakai/forums/privatemessagecreate";
        }

        return getMessages(request, siteId, uiModel);
    } else {
        return "sakai/forums/privatemessagecreate";
    }
}

From source file:com.alcatel.hello.actuator.ui.SampleActuatorUIApplicationTests.java

@Test
public void testError() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    ResponseEntity<String> entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/error",
            HttpMethod.GET, new HttpEntity<Void>(headers), String.class);

    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("<html>"));
    assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("<body>"));
    assertTrue("Wrong body:\n" + entity.getBody(),
            entity.getBody().contains("Please contact the operator with the above information"));
}

From source file:com.intel.databackend.handlers.Data.java

@RequestMapping(value = "/v1/accounts/{accountId}/dataInquiry/advanced", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody//  ww  w .j  av a2s  .  c  om
public ResponseEntity advancedDataInquiry(@PathVariable String accountId,
        @RequestBody final AdvDataInquiryRequest request) throws ServiceException, VcapEnvironmentException {
    logger.info(REQUEST_LOG_ENTRY, accountId);
    logger.debug(DEBUG_LOG, request);

    requestValidator = new AdvanceDataRequestValidator(request);
    requestValidator.validate();

    advancedDataInquiryService.withParams(accountId, request);
    AdvDataInquiryResponse dataInquiryResponse = advancedDataInquiryService.invoke();

    ResponseEntity res = new ResponseEntity<AdvDataInquiryResponse>(dataInquiryResponse, HttpStatus.OK);
    logger.info(RESPONSE_LOG_ENTRY, res.getStatusCode());
    logger.debug(DEBUG_LOG, dataInquiryResponse);
    return res;
}