Example usage for org.springframework.web.client HttpClientErrorException getStatusCode

List of usage examples for org.springframework.web.client HttpClientErrorException getStatusCode

Introduction

In this page you can find the example usage for org.springframework.web.client HttpClientErrorException getStatusCode.

Prototype

public HttpStatus getStatusCode() 

Source Link

Document

Return the HTTP status code.

Usage

From source file:com.ge.predix.integration.test.PrivilegeManagementAccessControlServiceIT.java

public void testCreateBatchSubjectsWithMalformedJSON() {
    try {/*from w ww  .j  av a  2 s .  com*/
        String badSubject = "{\"subject\":{\"name\" : \"good-subject-brittany\"},"
                + "{\"subject\": bad-subject-sarah\"}";
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-type", "application/json");
        headers.add(PolicyHelper.PREDIX_ZONE_ID, this.acsZone1Name);
        HttpEntity<String> httpEntity = new HttpEntity<String>(badSubject, headers);
        this.acsAdminRestTemplate.postForEntity(this.acsUrl + PrivilegeHelper.ACS_SUBJECT_API_PATH, httpEntity,
                Subject[].class);
    } catch (HttpClientErrorException e) {
        Assert.assertEquals(e.getStatusCode(), HttpStatus.BAD_REQUEST);
        return;
    }
    this.acsAdminRestTemplate.exchange(
            this.acsUrl + PrivilegeHelper.ACS_SUBJECT_API_PATH + "/bad-subject-sarah", HttpMethod.DELETE,
            new HttpEntity<>(this.zone1Headers), ResponseEntity.class);
    this.acsAdminRestTemplate.exchange(
            this.acsUrl + PrivilegeHelper.ACS_SUBJECT_API_PATH + "/good-subject-brittany", HttpMethod.DELETE,
            new HttpEntity<>(this.zone1Headers), ResponseEntity.class);
    Assert.fail("testCreateBatchSubjectsWithMalformedJSON should have failed!");
}

From source file:com.ge.predix.integration.test.PrivilegeManagementAccessControlServiceIT.java

@Test
public void testBatchResourcesDataConstraintViolationResourceIdentifier() {
    List<BaseResource> resources = new ArrayList<BaseResource>();
    resources.add(this.privilegeHelper.createResource("dupResourceIdentifier"));
    resources.add(this.privilegeHelper.createResource("dupResourceIdentifier"));

    try {/*  ww  w  .  j  ava  2 s. c o m*/
        // This POST causes a data constraint violation on the service bcos
        // of duplicate
        // resource_identifiers which returns a HTTP 422 error.
        this.acsAdminRestTemplate.postForEntity(this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH,
                new HttpEntity<>(resources, this.zone1Headers), ResponseEntity.class);
    } catch (HttpClientErrorException e) {
        Assert.assertEquals(e.getStatusCode(), HttpStatus.UNPROCESSABLE_ENTITY);
        return;
    }
    this.acsAdminRestTemplate.exchange(this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH + "/marissa",
            HttpMethod.DELETE, new HttpEntity<>(this.zone1Headers), ResponseEntity.class);
    Assert.fail(
            "Expected unprocessable entity http client error on post for 2 resources with duplicate resource"
                    + "identifiers.");
}

From source file:com.wavemaker.tools.deployment.cloudfoundry.CloudFoundryDeploymentTarget.java

private Boolean appNameInUse(CloudFoundryClient client, String appName) {
    try {//from w  w w. ja  v a2s  .c  om
        if (client.getApplication(appName) != null) {
            log.info("ApplicationName: " + appName + " is already in use");
            return true;
        } else {
            log.info("ApplicatonName with name: " + appName + "was NOT found");
            return false;
        }
    } catch (HttpClientErrorException e) {
        log.info("Failed to find aplicatonName with name: " + appName + ". Response was: "
                + e.getLocalizedMessage());
        if (e.getStatusCode() != HttpStatus.NOT_FOUND) {
            return true;
        } else {
            return false;
        }
    }
}

From source file:io.pivotal.cla.service.github.MylynGitHubApi.java

private boolean isAuthor(String username, String accessToken) {
    try {//from w  ww. j  av  a 2 s  . c om
        ResponseEntity<String> entity = rest.getForEntity(
                oauthConfig.getGitHubApiBaseUrl() + "/teams/{id}/memberships/{username}?access_token={token}",
                String.class, "2006839", username, accessToken);
        return entity.getStatusCode().value() == 200;
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            return false;
        }
        throw e;
    }
}

From source file:org.terasoluna.gfw.functionaltest.app.exceptionhandling.ExceptionHandlingTest.java

@Test
public void test03_07_servletFrameworkHandling() {

    driver.findElement(By.id("servletFrameworkHandling_03_07")).click();

    // TODO Assert Output Log

    // Error Code assert
    assertThat(driver.findElement(By.id("exceptionCode")).getText(), is("w.xx.0001"));

    // screen capture
    screenCapture.save(driver);//from www . j  ava2 s. c  o m

    try {
        restTemplate.getForEntity(applicationContextUrl + "/exceptionhandling/3_7", String.class);
    } catch (HttpClientErrorException e) {
        // Response Header Error Code assert
        assertThat(e.getResponseHeaders().get("X-Exception-Code").get(0).toString(), is("w.xx.0001"));
        // Response Code assert
        assertThat(e.getStatusCode().toString(), is("404"));
    }
}

From source file:org.terasoluna.gfw.functionaltest.app.exceptionhandling.ExceptionHandlingTest.java

@Test
public void test03_10_servletFrameworkHandling() {

    driver.findElement(By.id("servletFrameworkHandling_03_10")).click();

    // TODO Assert Output Log

    // Error Code assert
    assertThat(driver.findElement(By.id("exceptionCode")).getText(), is("i.xx.0010"));

    // screen capture
    screenCapture.save(driver);/*from ww  w  .java  2  s.  c  o  m*/

    try {
        restTemplate.getForEntity(applicationContextUrl + "/exceptionhandling/3_10", String.class);
    } catch (HttpClientErrorException e) {
        // Response Header Error Code assert
        assertThat(e.getResponseHeaders().get("X-Exception-Code").get(0).toString(), is("i.xx.0010"));
        // Response Code assert
        assertThat(e.getStatusCode().toString(), is("409"));
    }
}

From source file:com.rabbitmq.http.client.Client.java

private <T> T getForObjectReturningNullOn404(final URI uri, final Class<T> klass) {
    try {//www  .  j  a  va2 s.co  m
        return this.rt.getForObject(uri, klass);
    } catch (final HttpClientErrorException ce) {
        if (ce.getStatusCode() == HttpStatus.NOT_FOUND) {
            return null;
        } else {
            throw ce;
        }
    }
}

From source file:com.rabbitmq.http.client.Client.java

private void deleteIgnoring404(URI uri) {
    try {/* w ww  .  jav  a2  s. co m*/
        this.rt.delete(uri);
    } catch (final HttpClientErrorException ce) {
        if (!(ce.getStatusCode() == HttpStatus.NOT_FOUND)) {
            throw ce;
        }
    }
}

From source file:org.alfresco.dropbox.service.DropboxServiceImpl.java

private Connection<Dropbox> getConnection() throws DropboxAuthenticationException {
    Connection<Dropbox> connection = null;

    OAuth1CredentialsInfo credentialsInfo = oauth1CredentialsStoreService
            .getPersonalOAuth1Credentials(DropboxConstants.REMOTE_SYSTEM);

    if (credentialsInfo != null) {
        OAuthToken accessToken = new OAuthToken(credentialsInfo.getOAuthToken(),
                credentialsInfo.getOAuthSecret());

        try {//from w ww. j a v a  2  s  .c  o m
            connection = connectionFactory.createConnection(accessToken);
        } catch (HttpClientErrorException hcee) {
            if (hcee.getStatusCode().ordinal() == Status.STATUS_FORBIDDEN) {
                throw new DropboxAuthenticationException();
            }

        }
    }

    logger.debug("Dropbox Connection made for " + AuthenticationUtil.getRunAsUser());

    return connection;
}

From source file:org.syncope.core.rest.AuthenticationTestITCase.java

@Test
public void testUserSchemaAuthorization() {
    // 0. create a role that can only read schemas
    RoleTO authRoleTO = new RoleTO();
    authRoleTO.setName("authRole");
    authRoleTO.setParent(8L);//  w w  w  .  j  a va  2 s. c om
    authRoleTO.addEntitlement("SCHEMA_READ");

    authRoleTO = restTemplate.postForObject(BASE_URL + "role/create", authRoleTO, RoleTO.class);
    assertNotNull(authRoleTO);

    // 1. create a schema (as admin)
    SchemaTO schemaTO = new SchemaTO();
    schemaTO.setName("authTestSchema");
    schemaTO.setMandatoryCondition("false");
    schemaTO.setType(SchemaType.String);

    SchemaTO newSchemaTO = restTemplate.postForObject(BASE_URL + "schema/user/create", schemaTO,
            SchemaTO.class);
    assertEquals(schemaTO, newSchemaTO);

    // 2. create an user with the role created above (as admin)
    UserTO userTO = UserTestITCase.getSampleTO("auth@test.org");

    MembershipTO membershipTO = new MembershipTO();
    membershipTO.setRoleId(authRoleTO.getId());
    AttributeTO testAttributeTO = new AttributeTO();
    testAttributeTO.setSchema("testAttribute");
    testAttributeTO.addValue("a value");
    membershipTO.addAttribute(testAttributeTO);
    userTO.addMembership(membershipTO);

    userTO = restTemplate.postForObject(BASE_URL + "user/create", userTO, UserTO.class);
    assertNotNull(userTO);

    // 3. read the schema created above (as admin) - success
    schemaTO = restTemplate.getForObject(BASE_URL + "schema/user/read/authTestSchema.json", SchemaTO.class);
    assertNotNull(schemaTO);

    // 4. read the schema created above (as user) - success
    PreemptiveAuthHttpRequestFactory requestFactory = ((PreemptiveAuthHttpRequestFactory) restTemplate
            .getRequestFactory());
    ((DefaultHttpClient) requestFactory.getHttpClient()).getCredentialsProvider().setCredentials(
            requestFactory.getAuthScope(),
            new UsernamePasswordCredentials(userTO.getUsername(), "password123"));

    schemaTO = restTemplate.getForObject(BASE_URL + "schema/user/read/authTestSchema.json", SchemaTO.class);
    assertNotNull(schemaTO);

    // 5. update the schema create above (as user) - failure
    HttpClientErrorException exception = null;
    try {
        restTemplate.postForObject(BASE_URL + "schema/role/update", schemaTO, SchemaTO.class);
    } catch (HttpClientErrorException e) {
        exception = e;
    }
    assertNotNull(exception);
    assertEquals(HttpStatus.FORBIDDEN, exception.getStatusCode());

    // reset admin credentials for restTemplate
    super.setupRestTemplate();

    userTO = restTemplate.getForObject(BASE_URL + "user/read/{userId}.json", UserTO.class, userTO.getId());

    assertNotNull(userTO);
    assertNotNull(userTO.getLastLoginDate());
    assertEquals(Integer.valueOf(0), userTO.getFailedLogins());
}