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.example.clienttest.AbstractGreenhouseActivity.java

protected void processException(Exception e) {
    if (e != null) {
        if (e instanceof ResourceAccessException) {
            displayNetworkError();//from w  w  w .j ava2s  . c om
        } else if (e instanceof HttpClientErrorException) {
            HttpClientErrorException httpError = (HttpClientErrorException) e;
            if (httpError.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                displayAuthorizationError();
            }
        } else if (e instanceof MissingAuthorizationException) {
            displayAuthorizationError();
        }
    }
}

From source file:com.bose.aem.spring.config.ConfigServicePropertySourceLocator.java

private Environment getRemoteEnvironment(RestTemplate restTemplate, String uri, String name, String profile,
        String label) {/*from w ww  .ja va 2s . c o  m*/
    String path = "/{name}/{profile}";
    Object[] args = new String[] { name, profile };
    if (StringUtils.hasText(label)) {
        args = new String[] { name, profile, label };
        path = path + "/{label}";
    }
    ResponseEntity<Environment> response = null;

    try {
        response = restTemplate.exchange(uri + path, HttpMethod.GET, new HttpEntity<Void>((Void) null),
                Environment.class, args);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() != HttpStatus.NOT_FOUND) {
            throw e;
        }
    }

    if (response == null || response.getStatusCode() != HttpStatus.OK) {
        return null;
    }
    Environment result = response.getBody();
    return result;
}

From source file:org.icgc.dcc.metadata.client.core.MetadataClient.java

private Entity createEntity(String gnosId, String fileName) {
    val url = baseUrl + "/" + "entities";
    val entity = new Entity().setGnosId(gnosId).setFileName(fileName);

    try {//from   w w w  . j  a  v a2s  .  c  o m
        log.info("Posting: {}", entity);
        val response = restTemplate.postForEntity(url, entity, Entity.class);
        log.info("Entity: {}", response);

        return response.getBody();
    } catch (HttpClientErrorException e) {
        log.error("Unexpected response code {} creating entity {}", e.getStatusCode(), entity);

        throw e;
    }
}

From source file:it.infn.mw.iam.authn.oidc.DefaultOidcTokenRequestor.java

@Override
public String requestTokens(OidcProviderConfiguration conf, MultiValueMap<String, String> tokenRequestParams) {

    RestOperations restTemplate = restTemplateFactory.newRestTemplate();

    try {//from w  ww . j  a  va  2  s  . c om

        return restTemplate.postForObject(conf.serverConfig.getTokenEndpointUri(),
                prepareTokenRequest(conf, tokenRequestParams), String.class);

    } catch (HttpClientErrorException e) {

        if (e.getStatusCode() != null && e.getStatusCode().equals(BAD_REQUEST)) {
            parseErrorResponse(e).ifPresent(er -> {

                String errorMessage = String.format("Token request error: %s '%s'", er.getError(),
                        er.getErrorDescription());
                LOG.error(errorMessage);

                throw new OidcClientError(e.getMessage(), er.getError(), er.getErrorDescription(),
                        er.getErrorUri());

            });
        }

        String errorMessage = String.format("Token request error: %s", e.getMessage());
        LOG.error(errorMessage, e);
        throw new OidcClientError(errorMessage, e);
    } catch (Exception e) {
        String errorMessage = String.format("Token request error: %s", e.getMessage());
        LOG.error(errorMessage, e);
        throw new OidcClientError(errorMessage, e);
    }

}

From source file:com.salmon.security.xacml.demo.springmvc.rest.HTTPPopulatorsTest.java

@Test
public void badUserPrevented() {
    HttpHeaders headers = this.getHeaders("wrongusername" + ":" + "wrongpwd");

    RestTemplate template = new RestTemplate();

    HttpEntity<String> requestEntity = new HttpEntity<String>(DriverFixtures.standardDriverJSON(), headers);

    try {//from w  w  w .j  a  v a  2  s . c  om
        ResponseEntity<Driver> entity = template.postForEntity(
                "http://localhost:8085/xacml/populators/dvla/driveradd", requestEntity, Driver.class);
        fail("Request Passed incorrectly with status " + entity.getStatusCode());
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.UNAUTHORIZED, ex.getStatusCode());
    }

}

From source file:de.zib.gndms.gndmc.gorfx.Test.TaskFlowClientTest.java

@Test(groups = { "TaskFlowClientTest" }, dependsOnMethods = { "createTask" })
public void deleteTaskFlow() throws InterruptedException {
    Thread.sleep(5000);/*from w w  w  .  j av a2 s  . com*/

    // delete task flow
    {
        final ResponseEntity<Integer> responseEntity = taskFlowClient
                .deleteTaskflow(FailureTaskFlowMeta.TASK_FLOW_TYPE_KEY, taskFlowId, admindn, TASKFLOW_WID);

        Assert.assertNotNull(responseEntity);
        Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.OK);
    }

    // try to not find taskflow
    {
        try {
            final ResponseEntity<Facets> responseEntity = taskFlowClient
                    .getFacets(FailureTaskFlowMeta.TASK_FLOW_TYPE_KEY, taskFlowId, admindn);

            Assert.assertNotNull(responseEntity);
            Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.NOT_FOUND);
        } catch (HttpClientErrorException e) {
            Assert.assertEquals(e.getStatusCode(), HttpStatus.NOT_FOUND);
        }
    }
}

From source file:com.alexshabanov.springrestapi.ControllerMockTest.java

@Test
public void shouldGetBadRequest() throws IOException {
    doThrow(IllegalArgumentException.class).when(profileController).deleteProfile(id);
    when(profileController.handleIllegalArgumentException()).thenReturn(errorDesc);

    try {//from ww w.j av a2s . c  om
        restClient.delete(path(CONCRETE_PROFILE_RESOURCE), id);
        fail();
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode());
        final ErrorDesc actual = getObjectMapper().reader(ErrorDesc.class)
                .readValue(e.getResponseBodyAsString());
        assertEquals(errorDesc, actual);
    }
}

From source file:com.companyname.plat.commons.client.HttpRestfulClient.java

public Object getObject(Map<String, String> params, Class clz) {
    RestTemplate restTemplate = new RestTemplate();

    try {//from   w ww .  j  a v a2s  .c o  m
        ResponseEntity<Object> entity = restTemplate.exchange(getEndPoint(), HttpMethod.GET,
                getHttpRequest(params), clz);

        setResponseStatus(entity.getStatusCode().toString());
        return entity.getBody();
    } catch (HttpClientErrorException ex) {
        if (HttpStatus.UNAUTHORIZED == ex.getStatusCode()) {
            System.out
                    .println("Unauthorized call to " + this.getEndPoint() + "\nWrong login and/or password (\""
                            + this.getUserName() + "\" / \"" + this.getPassword() + "\")");

            System.out.println("Cause: \n" + ex.getMessage());
        }
    }

    return null;
}

From source file:se.sawano.scala.examples.scalaspringmvc.ValidationTestIT.java

@Test
public void javaPostWithInvalidAge() {
    try {//  w  w w  .  jav  a 2 s.  c o m
        JavaIndata indata = new JavaIndata("Daniel", -1);
        restTemplate.postForObject(baseUrl + "java/indata", indata, Void.class, (Object) null);
        fail("Expected JSR-303 validation to fail");
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode());
    }
}