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

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

Introduction

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

Prototype

public HttpStatus getStatusCode() 

Source Link

Document

Return the HTTP status code.

Usage

From source file:com.wolkabout.hexiwear.activity.ResetPasswordActivity.java

@Background
void submitResetPassword() {
    showResetPending();/*from w  ww . j a  v a2 s .  c o m*/
    try {
        authenticationService.resetPassword(new ResetPasswordRequest(email.getValue()));
        hideResetPending();
        showInfoDialog(R.string.reset_password_success);
    } catch (HttpStatusCodeException e) {
        Log.e(TAG, "Couldn't reset password", e);
        hideResetPending();
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            showWarningDialog(R.string.reset_password_no_such_email_error);
            return;
        }

        showWarningDialog(R.string.reset_password_error);
    } catch (Exception e) {
        Log.e(TAG, "Couldn't reset password", e);
        hideResetPending();
        showWarningDialog(R.string.reset_password_error);
    }
}

From source file:com.wolkabout.hexiwear.activity.PasswordChangeActivity.java

@Click
@Background//from   w  w  w. ja va 2s . co  m
void changePassword() {
    if (!validate()) {
        return;
    }

    showChangePasswordPending();

    try {
        final ChangePasswordRequest requestDto = new ChangePasswordRequest(currentPassword.getValue(),
                newPassword.getValue());
        userService.changePassword(requestDto);
        onPasswordChanged(requestDto);
    } catch (HttpStatusCodeException e) {
        hideChangePasswordPending();
        if (e.getStatusCode() == HttpStatus.BAD_REQUEST || e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            showWarningDialog(R.string.change_password_old_invalid);
            return;
        }

        showWarningDialog(R.string.change_password_error);
    } catch (Exception e) {
        hideChangePasswordPending();
        showWarningDialog(R.string.change_password_error);
    }
}

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  w  w w . j  a v  a2  s . co  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:org.syncope.core.rest.ReportTestITCase.java

@Test
public void delete() {
    ReportTO report = new ReportTO();
    report.setName("testReportForDelete");
    report.addReportletConf(new UserReportletConf("first"));
    report.addReportletConf(new UserReportletConf("second"));

    report = restTemplate.postForObject(BASE_URL + "report/create", report, ReportTO.class);
    assertNotNull(report);//from   ww w  . ja va 2  s .  co  m

    restTemplate.delete(BASE_URL + "report/delete/{reportId}", report.getId());

    try {
        restTemplate.getForObject(BASE_URL + "report/read/{reportId}", UserTO.class, report.getId());
        fail();
    } catch (HttpStatusCodeException e) {
        assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode());
    }
}

From source file:org.openlmis.fulfillment.service.ObjReferenceExpander.java

private <T> T retrieve(String href, Class<T> type) {
    HttpEntity<Object> entity = createEntity(RequestHeaders.init().setAuth(authService.obtainAccessToken()));
    try {/*from  ww  w.j  a v  a  2 s.  c  o m*/
        return restTemplate.exchange(createUri(href), HttpMethod.GET, entity, type).getBody();
    } catch (HttpStatusCodeException ex) {
        // We don't want to stop processing if the referenced instance does not exist.
        if (HttpStatus.NOT_FOUND == ex.getStatusCode()) {
            LOGGER.warn("The instance referenced under {} does not exist.", href);
            return null;
        }

        throw new DataRetrievalException(href, ex);
    }
}

From source file:org.springframework.cloud.config.server.environment.VaultEnvironmentRepository.java

String read(String key) {
    String url = String.format("%s://%s:%s/v1/{backend}/{key}", this.scheme, this.host, this.port);

    HttpHeaders headers = new HttpHeaders();

    String token = request.getHeader(TOKEN_HEADER);
    if (!StringUtils.hasLength(token)) {
        throw new IllegalArgumentException("Missing required header: " + TOKEN_HEADER);
    }//from ww  w .  j  av a 2s  .c  o m
    headers.add(VAULT_TOKEN, token);
    try {
        ResponseEntity<VaultResponse> response = this.rest.exchange(url, HttpMethod.GET,
                new HttpEntity<>(headers), VaultResponse.class, this.backend, key);

        HttpStatus status = response.getStatusCode();
        if (status == HttpStatus.OK) {
            return response.getBody().getData();
        }
    } catch (HttpStatusCodeException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            return null;
        }
        throw e;
    }

    return null;
}

From source file:eu.cloudwave.wp5.feedbackhandler.metricsources.NewRelicClient.java

/**
 * {@inheritDoc}//  w  ww .ja  va 2s .co m
 */
@Override
protected void handleHttpServerException(final HttpStatusCodeException serverError)
        throws MetricSourceClientException, IOException {
    // if the status code is 401 UNAUTHORIZED -> the API key is not valid
    if (serverError.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
        throw new MetricSourceClientException(ErrorType.NEW_RELIC__INVALID_API_KEY,
                Messages.ERRORS__NEW_RELIC__INVALID_API_KEY);
    }

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode errorNode = mapper.readTree(serverError.getResponseBodyAsString());
    final JsonNode titleNode = errorNode.findValue(JSON__TITLE);
    if (titleNode != null) {
        final String message = titleNode.asText();
        ErrorType type = ErrorType.NEW_RELIC__GENERAL;

        if (message.contains(ERROR__INVALID_APPLICATION_ID)
                || message.equals(ERROR__INVALID_PARAMETER_APPLICATION_ID)) {
            type = ErrorType.NEW_RELIC__INVALID_APPLICATION_ID;
        } else if (message.contains(ERROR__UNKNOWN_METRIC)) {
            type = ErrorType.UNKNOWN_METRIC;
        } else if (message.contains(ERROR__INVALID_PARAMETER)) {
            type = ErrorType.INVALID_PARAMETER;
        }
        throw new MetricSourceClientException(type, message);
    }
}

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

@Test
public void delete() {
    try {/*from  w  ww.j a v  a2  s .c o m*/
        restTemplate.delete(BASE_URL + "role/delete/{roleId}", 0);
    } catch (HttpStatusCodeException e) {
        assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode());
    }

    restTemplate.delete(BASE_URL + "role/delete/{roleId}", 5);
    try {
        restTemplate.getForObject(BASE_URL + "role/read/{roleId}.json", RoleTO.class, 2);
    } catch (HttpStatusCodeException e) {
        assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode());
    }
}

From source file:org.cloudfoundry.caldecott.client.HttpTunnel.java

private byte[] receiveDataBuffered(long page) {
    final String dataUrl = url + this.tunnelInfo.get("path_out") + "/" + page;
    byte[] responseBytes;
    try {//from  ww w .  j  ava2s .  c  o  m
        responseBytes = restOperations.execute(dataUrl, HttpMethod.GET, new RequestCallback() {
            public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
                clientHttpRequest.getHeaders().set("Auth-Token", auth);
            }
        }, new ResponseExtractor<byte[]>() {
            public byte[] extractData(ClientHttpResponse clientHttpResponse) throws IOException {
                if (logger.isDebugEnabled()) {
                    logger.debug("HEADER: " + clientHttpResponse.getHeaders().toString());
                }
                InputStream stream = clientHttpResponse.getBody();
                byte[] data = readContentData(stream);
                if (logger.isDebugEnabled()) {
                    logger.debug("[" + data.length + " bytes] GET from " + dataUrl + " resulted in: "
                            + clientHttpResponse.getStatusCode());
                }
                return data;
            }
        });
    } catch (HttpStatusCodeException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("GET from " + dataUrl + " resulted in: " + e.getStatusCode().value());
        }
        throw e;
    }
    return responseBytes;
}

From source file:org.trustedanalytics.user.common.WebErrorHandlers.java

@ExceptionHandler(HttpStatusCodeException.class)
public void handleHttpStatusCodeException(HttpStatusCodeException e, HttpServletResponse response)
        throws IOException {
    String message = extractErrorFromJSON(e.getResponseBodyAsString());
    message = StringUtils.isNotBlank(message) ? message : e.getMessage();
    logAndSendErrorResponse(response, e.getStatusCode(), message, e);
}