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:com.ge.predix.acceptance.test.zone.admin.DefaultZoneAuthorizationIT.java

/**
 * 1. Create a token from zone issuer with scopes for accessing: a. zone specific resources, AND b.
 * acs.zones.admin/*from  w ww.j a  va 2s .  c  o  m*/
 *
 * 2. Try to access a zone specific resource . This should work 3. Try to access /v1/zone - THIS SHOULD FAIL
 *
 * @throws Exception
 */
public void testAccessGlobalResourceWithZoneIssuer() throws Exception {
    OAuth2RestTemplate zone2AcsTemplate = this.acsRestTemplateFactory.getACSZone2RogueTemplate();

    HttpHeaders zoneTwoHeaders = new HttpHeaders();
    zoneTwoHeaders.set(PolicyHelper.PREDIX_ZONE_ID, this.zoneHelper.getZone2Name());

    // Write a resource to zone2. This should work
    ResponseEntity<Object> responseEntity = this.privilegeHelper.postResources(zone2AcsTemplate,
            zoneHelper.getAcsBaseURL(), zoneTwoHeaders, new BaseResource("/sites/sanramon"));
    Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.NO_CONTENT);

    // Try to get global resource from global/baseUrl. This should FAIL
    try {
        zone2AcsTemplate.exchange(this.zoneHelper.getAcsBaseURL() + "/v1/zone/" + this.zone2Name,
                HttpMethod.GET, null, Zone.class);
        Assert.fail("Able to access non-zone specific resource with a zone specific issuer token!");
    } catch (OAuth2AccessDeniedException e) {
        // expected
    }

    // Try to get global resource from zone2Url. This should FAIL
    try {
        zone2AcsTemplate.exchange(this.zoneHelper.getAcsBaseURL() + "/v1/zone/" + this.zone2Name,
                HttpMethod.GET, new HttpEntity<>(zoneTwoHeaders), Zone.class);
        Assert.fail("Able to access non-zone specific resource from a zone specific URL, "
                + "with a zone specific issuer token!");
    } catch (InvalidRequestException e) {
        // expected
    }

}

From source file:com.fredhopper.core.connector.index.upload.impl.RestPublishingStrategy.java

@Override
public String uploadDataSet(final InstanceConfig config, final File file) throws ResponseStatusException {
    Preconditions.checkArgument(config != null);
    Preconditions.checkArgument(file != null);

    final RestTemplate restTemplate = restTemplateProvider.createTemplate(config.getHost(), config.getPort(),
            config.getUsername(), config.getPassword());
    final String checkSum = createCheckSum(file);

    final List<NameValuePair> params = Arrays
            .asList(new NameValuePair[] { new BasicNameValuePair("checksum", checkSum) });
    final URI url = createUri(config.getScheme(), config.getHost(), config.getPort(), config.getServername(),
            UPLOAD_PATH, params);/* ww  w  . ja  v  a2  s .c  o  m*/

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf("application/zip"));
    final HttpEntity<Resource> httpEntity = new HttpEntity<>(new FileSystemResource(file), headers);

    final ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity,
            String.class);

    final HttpStatus status = response.getStatusCode();
    if (status.equals(HttpStatus.CREATED)) {
        return response.getBody().trim();
    } else {
        throw new ResponseStatusException(
                "HttpStatus " + status.toString() + " response received. File upload failed.");
    }
}

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

@Test
public void testHealth() {
    ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
            .getForEntity("/actuator/health", String.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(entity.getBody()).contains("\"status\":\"UP\"");
    assertThat(entity.getBody()).doesNotContain("\"hello\":\"1\"");
}

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

@Test
public void testInfo() {
    ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
            .getForEntity("/actuator/info", String.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(entity.getBody()).contains("\"artifact\":\"spring-boot-sample-actuator\"");
    assertThat(entity.getBody()).contains("\"someKey\":\"someValue\"");
    assertThat(entity.getBody()).contains("\"java\":{", "\"source\":\"1.8\"", "\"target\":\"1.8\"");
    assertThat(entity.getBody()).contains("\"encoding\":{", "\"source\":\"UTF-8\"", "\"reporting\":\"UTF-8\"");
}

From source file:be.boyenvaesen.EmployeeControllerTest.java

@Test
public void testScenarioPostOneGetList() {

    //Check if list is the list from setup
    ResponseEntity<Employee[]> responseEntity = restTemplate.getForEntity("/employees", Employee[].class);
    Employee[] employees = responseEntity.getBody();
    assertEquals("Boyen", employees[0].getFirstName());
    assertEquals(4, employees.length);// w  ww  .  j a  v  a 2  s . c  o m

    //Post a new employee
    ResponseEntity<Employee> postedEntity = restTemplate.postForEntity("/employees",
            new Employee("newFirst", "newLast", "newDescr"), Employee.class);
    Employee postedEmployee = postedEntity.getBody();
    assertEquals(HttpStatus.CREATED, postedEntity.getStatusCode());
    assertEquals("newFirst", postedEmployee.getFirstName());

    //Check if list is now changed with the new value
    responseEntity = restTemplate.getForEntity("/employees", Employee[].class);
    employees = responseEntity.getBody();
    assertEquals("Boyen", employees[0].getFirstName());
    assertEquals(postedEmployee.getFirstName(), employees[4].getFirstName());

    assertEquals(5, employees.length);

}

From source file:com.atwelm.aezwidget.data.ConfigurationServer.java

/**
 * Loads the layouts from the server and provides them in the callback if provided
 * @param callback Contains the layouts or error information
 *//*from  ww w .  j a  v  a2  s  .  c o m*/
public void loadLayouts(final LoadLayoutCallback callback) {
    final ConfigurationServer self = this;
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());

                ResponseEntity<AEZFetchLayoutResponseInterface> responseEntity = restTemplate
                        .getForEntity(mServerAddress, mServerType.getResponseClass());

                int returnStatus = responseEntity.getStatusCode().value();

                if (returnStatus <= 200 && returnStatus < 300) {
                    AEZFetchLayoutResponseInterface response = responseEntity.getBody();

                    List<AEZLayout> receivedLayouts = response.getLayouts();

                    callback.success(receivedLayouts);

                } else {
                    callback.failure(returnStatus, null);
                }

            } catch (HttpStatusCodeException rsce) {
                Log.e(LOG_IDENTIFIER, rsce.toString());
                callback.failure(rsce.getStatusCode().value(), rsce.toString());

            } catch (RestClientException rce) {
                Log.e(LOG_IDENTIFIER, rce.toString());
                callback.failure(-1, rce.toString());
            }
        }
    });
    t.start();
}

From source file:com.capside.enterpriseseminar.DemoAPIIT.java

@Test
public void testGetStatisticsWithDTO() {
    final String localTeamName = "R. Madrid";
    final String visitorTeamName = "Barcelona";
    ResponseEntity<ApiCtrl.StatisticsDTO> response = restTemplate.exchange(
            "/games/stats/{firstTeam:.*}-vs-{secondTeam:.*}", HttpMethod.GET, null, ApiCtrl.StatisticsDTO.class,
            localTeamName, visitorTeamName);

    assertEquals("Invocation was a success.", HttpStatus.OK, response.getStatusCode());
    assertEquals("Local team", localTeamName, response.getBody().getStatistics().getFirstTeam());
    assertEquals("Visitor team", visitorTeamName, response.getBody().getStatistics().getSecondTeam());
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrService.java

public JsonNode getMetadata() throws Exception {
    if (metadata == null) {
        // set connection timeouts
        timeoutFromPrefs();/* w  w  w  .  j a  va  2 s.  co  m*/
        // prepare request
        final String serviceUrl = NbPreferences.forModule(PrefConstants.class).get(PREF_INITIALIZR_URL,
                "http://start.spring.io");
        RequestEntity<Void> req = RequestEntity.get(new URI(serviceUrl))
                .accept(MediaType.valueOf("application/vnd.initializr.v2.1+json"))
                .header("User-Agent", REST_USER_AGENT).build();
        // connect
        logger.log(INFO, "Getting Spring Initializr metadata from: {0}", serviceUrl);
        logger.log(INFO, "Asking metadata as: {0}", REST_USER_AGENT);
        long start = System.currentTimeMillis();
        ResponseEntity<String> respEntity = rt.exchange(req, String.class);
        // analyze response
        final HttpStatus statusCode = respEntity.getStatusCode();
        if (statusCode == OK) {
            ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
            metadata = mapper.readTree(respEntity.getBody());
            logger.log(INFO, "Retrieved Spring Initializr service metadata. Took {0} msec",
                    System.currentTimeMillis() - start);
            if (logger.isLoggable(FINE)) {
                logger.fine(mapper.writeValueAsString(metadata));
            }
        } else {
            // log status code
            final String errMessage = String.format(
                    "Spring initializr service connection problem. HTTP status code: %s",
                    statusCode.toString());
            logger.severe(errMessage);
            // throw exception in order to set error message
            throw new RuntimeException(errMessage);
        }
    }
    return metadata;
}