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:org.trustedanalytics.metricsprovider.integrationtests.tests.MetricsIT.java

@Test
public void callMetricsEndpoint_orgSpecified_shouldReturnOrgMetrics() {

    String URL = BASE_URL + MetricsController.GET_APPS_METRICS_ASYNC;

    String ORG = "290f0c0e-3d2e-4222-b7aa-dc1b4870faec";
    ImmutableMap<String, Object> pathVars = ImmutableMap.of("org", ORG);

    TestRestTemplate testRestTemplate = new TestRestTemplate();
    ResponseEntity<String> response = RestOperationsHelpers.getForEntityWithToken(testRestTemplate, TOKEN, URL,
            String.class, pathVars);

    assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
    assertThat(response.getBody(), equalTo(
            // @formatter:off
            "{" + "\"" + MetricsSchema.PRIVATE_DATASETS + "\":12," + "\"" + MetricsSchema.DATASET_COUNT
                    + "\":24," + "\"" + MetricsSchema.SERVICE_USAGE_PERCENT + "\":{" + "\"numerator\":5,"
                    + "\"denominator\":50" + "}," + "\"" + MetricsSchema.MEMORY_USAGE_ABSOLUTE + "\":120,"
                    + "\"" + MetricsSchema.MEMORY_USAGE + "\":{" + "\"numerator\":120," + "\"denominator\":1200"
                    + "}," + "\"" + MetricsSchema.TOTAL_USERS + "\":17," + "\"" + MetricsSchema.SERVICE_USAGE
                    + "\":5," + "\"" + MetricsSchema.APPS_RUNNING + "\":2," + "\"" + MetricsSchema.LATEST_EVENTS
                    + "\":[{\"id\":\"id\",\"sourceId\":\"sourceId\","
                    + "\"sourceName\":\"sourceName\",\"timestamp\":123,\"category\":\"category\","
                    + "\"message\":\"message\"}]," + "\"" + MetricsSchema.DOMAINS_USAGE_PERCENT + "\":{"
                    + "\"numerator\":4," + "\"denominator\":100" + "}," + "\"" + MetricsSchema.APPS_DOWN
                    + "\":1," + "\"" + MetricsSchema.PUBLIC_DATASETS + "\":12," + "\""
                    + MetricsSchema.DOMAINS_USAGE + "\":4" + "}"));
    // @formatter:on
}

From source file:de.codecentric.boot.admin.AdminApplicationHazelcastTest.java

@Test
public void test() {
    Application app = Application.create("Hazelcast Test").withHealthUrl("http://127.0.0.1/health").build();
    Application app2 = Application.create("Hazelcast Test").withHealthUrl("http://127.0.0.1:2/health").build();
    Application app3 = Application.create("Do not find").withHealthUrl("http://127.0.0.1:3/health").build();

    // publish app on instance1
    ResponseEntity<Application> postResponse = registerApp(app, instance1);
    app = postResponse.getBody();/*from w w  w. j  a  v  a2 s.  c  om*/
    assertEquals(HttpStatus.CREATED, postResponse.getStatusCode());
    assertNotNull(app.getId());

    // publish app2 on instance2
    ResponseEntity<Application> postResponse2 = registerApp(app2, instance2);
    app2 = postResponse2.getBody();
    assertEquals(HttpStatus.CREATED, postResponse.getStatusCode());
    assertNotNull(app2.getId());

    // retrieve app from instance2
    ResponseEntity<Application> getResponse = getApp(app.getId(), instance2);
    assertEquals(HttpStatus.OK, getResponse.getStatusCode());
    assertEquals(app, getResponse.getBody());

    // retrieve app and app2 from instance1 (but not app3)
    app3 = registerApp(app3, instance1).getBody();
    Collection<Application> apps = getAppByName("Hazelcast Test", instance1).getBody();
    assertEquals(2, apps.size());
    assertTrue(apps.contains(app));
    assertTrue(apps.contains(app2));
    assertFalse(apps.contains(app3));
}

From source file:net.orpiske.tcs.service.rest.functional.DomainCreateTest.java

@Test
public void testAuthenticationError() {
    HttpEntity<Domain> requestEntity = new HttpEntity<Domain>(RestDataFixtures.customCsp(),
            getHeaders(USERNAME + ":" + BAD_PASSWORD));

    RestTemplate template = new RestTemplate();

    try {//from w ww.  j  a v  a  2s.c  o m
        ResponseEntity<Domain> responseEntity = template
                .postForEntity("http://localhost:8080/tcs/domain/terra.com.br", requestEntity, Domain.class);

        fail("Request Passed incorrectly with status " + responseEntity.getStatusCode());
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode());
    }
}

From source file:org.apache.knox.solr.ui.SearchController.java

/**
 * Do a solr search/*w w  w . j a v  a2  s .c  om*/
 * 
 * @param solrRequest
 *            the Solr request
 * @return the HTML response
 */
@RequestMapping("/search")
public @ResponseBody String search(@RequestBody SolrRequest solrRequest) {
    logger.debug("Received Solr Request: {}", solrRequest);
    final String solrUrl = buildSolrUrl(solrRequest);
    logger.debug("Executing with URL: {}", solrUrl);
    final RestTemplate restTemplate = new RestTemplate();

    final ResponseEntity<String> solrResult = restTemplate.getForEntity(solrUrl, String.class);
    logger.debug("Solr Result: {}", solrResult);
    if (HttpStatus.OK.equals(solrResult.getStatusCode())) {
        return solrResult.getBody();
    } else {
        logger.error("Error getting Solr Result - http status: {}", solrResult.getStatusCodeValue());
        return "";
    }
}

From source file:org.cloudfoundry.identity.uaa.integration.NativeApplicationIntegrationTests.java

/**
 * tests that an error occurs if you attempt to use bad client credentials.
 *//*from www. j  ava2  s .co m*/
@Test
// Need a custom auth entry point to get the correct JSON response here.
public void testInvalidClient() throws Exception {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("grant_type", "password");
    formData.add("username", resource.getUsername());
    formData.add("password", resource.getPassword());
    formData.add("scope", "cloud_controller.read");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Basic " + new String(Base64.encode("no-such-client:".getBytes("UTF-8"))));
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap("/oauth/token", formData, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    List<String> newCookies = response.getHeaders().get("Set-Cookie");
    if (newCookies != null && !newCookies.isEmpty()) {
        fail("No cookies should be set. Found: " + newCookies.get(0) + ".");
    }
    assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));

    @SuppressWarnings("unchecked")
    OAuth2Exception error = OAuth2Exception.valueOf(response.getBody());
    assertEquals("invalid_client", error.getOAuth2ErrorCode());
}

From source file:com.crazyacking.learn.spring.actuator.ManagementPortAndPathSampleActuatorApplicationTests.java

@Test
public void testHome() {
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
            .getForEntity("http://localhost:" + this.port, Map.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    @SuppressWarnings("unchecked")
    Map<String, Object> body = entity.getBody();
    assertThat(body.get("message")).isEqualTo("Hello Phil");
}

From source file:net.eusashead.hateoas.response.impl.PutResponseBuilderImplTest.java

@Test
public void testAllHeaders() throws Exception {
    Entity entity = new Entity("foo");
    Date now = new Date(1373571924000l);
    ResponseEntity<Void> response = builder.entity(entity).etag().lastModified(now).build();
    Assert.assertNotNull(response);/*from   ww w .  j a  va 2  s .c o  m*/
    Assert.assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());
    Assert.assertNull(response.getBody());
    Assert.assertNotNull(response.getHeaders().getETag());
    Assert.assertEquals("W/\"b0c689597eb9dd62c0a1fb90a7c5c5a5\"", response.getHeaders().getETag());
    Assert.assertEquals(now.getTime(), response.getHeaders().getLastModified());
}

From source file:org.opendatakit.api.admin.UserAdminServiceTest.java

@Test
public void testChangePlaintextPassword() {
    TestUtils.putGetOneUser(restTemplate, server, testUser3);
    String username = testUser3.getUserId().substring(SecurityConsts.USERNAME_COLON.length());
    String password = "mypass";

    String changePasswordUrl = ConstantsUtils.url(server) + "/admin/users/" + testUser3.getUserId()
            + "/password";

    logger.info("Updating password for " + username + " using " + changePasswordUrl);

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
    headers.add("Content-Type", "application/json");
    HttpEntity<?> request = new HttpEntity<>(password, headers);
    ResponseEntity<String> postResponse = restTemplate.postForEntity(changePasswordUrl, request, String.class);
    assertThat(postResponse.getStatusCode(), is(HttpStatus.OK));

    logger.info("Retrieving data using " + username + "'s new password");

    RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
    RestTemplate userRestTemplate = restTemplateBuilder.basicAuthorization(username, password).build();
    String getUserUrl = ConstantsUtils.url(server) + "/admin/users/" + testUser3.getUserId();
    ResponseEntity<UserEntity> getResponse = userRestTemplate.exchange(getUserUrl, HttpMethod.GET, null,
            UserEntity.class);
    UserEntity body = getResponse.getBody();
    assertThat(getResponse.getStatusCode(), is(HttpStatus.OK));
    assertThat(body.getUserId(), equalTo(testUser3.getUserId()));

    logger.info("Cleanup: deleting " + username);
    TestUtils.deleteGetOneUser(restTemplate, server, testUser3);
}

From source file:org.zaizi.SensefyResourceApplicationTests.java

@Test
public void testRootPathAuthorized() {
    RestTemplate template = new TestRestTemplate();
    final HttpHeaders headers = new HttpHeaders();
    String accessToken = TestOAuthUtils.getDefOAuth2AccessToken();
    TestOAuthUtils.addOAuth2AccessTokenToHeader(headers, accessToken);
    HttpEntity<String> httpEntity = new HttpEntity<>(headers);
    ResponseEntity<String> response = template.exchange(baseTestServerUrl(), HttpMethod.GET, httpEntity,
            String.class);
    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
}

From source file:com.cloudbees.jenkins.plugins.demo.actuator.NoManagementSampleActuatorApplicationTests.java

@Test
public void testMetricsNotAvailable() throws Exception {
    testHome(); // makes sure some requests have been made
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
            .getForEntity("http://localhost:" + this.port + "/metrics", Map.class);
    assertEquals(HttpStatus.NOT_FOUND, entity.getStatusCode());
}