List of usage examples for org.springframework.web.client HttpStatusCodeException getStatusCode
public HttpStatus getStatusCode()
From source file:org.openlmis.fulfillment.service.referencedata.BaseReferenceDataService.java
/** * Return one object from Reference data service. * * @param id UUID of requesting object.//from www .jav a 2 s.c o m * @return Requesting reference data object. */ public T findOne(UUID id) { String url = getServiceUrl() + getUrl() + id; try { ResponseEntity<T> responseEntity = restTemplate.exchange(buildUri(url), HttpMethod.GET, createEntity(), getResultClass()); return responseEntity.getBody(); } catch (HttpStatusCodeException ex) { // rest template will handle 404 as an exception, instead of returning null if (ex.getStatusCode() == HttpStatus.NOT_FOUND) { logger.warn("{} with id {} does not exist. ", getResultClass().getSimpleName(), id); return null; } else { throw buildDataRetrievalException(ex); } } }
From source file:org.openlmis.fulfillment.service.notification.NotificationService.java
/** * Send an email notification.//from w w w. j a v a 2 s .com * * @param user receiver of the notification * @param subject subject of the email * @param content content of the email * @return true if success, false if failed. */ public boolean notify(UserDto user, String subject, String content) { NotificationDto request = buildNotification(user, subject, content); logger.debug("Sending request:" + "\n subject:" + request.getMessages().get(EMAIL.toString()).getSubject() + "\n content:" + request.getMessages().get(EMAIL.toString()).getBody() + "\n to: " + request.getUserId()); String url = notificationUrl + "/api/notifications"; try { RequestHeaders headers; headers = RequestHeaders.init().setAuth(authService.obtainAccessToken()); URI uri = RequestHelper.createUri(url); HttpEntity<NotificationDto> entity = RequestHelper.createEntity(request, headers); restTemplate.postForObject(uri, entity, Object.class); } catch (HttpStatusCodeException ex) { logger.error("Unable to send notification. Error code: {}, response message: {}", ex.getStatusCode(), ex.getResponseBodyAsString()); return false; } return true; }
From source file:com.xyxy.platform.examples.showcase.functional.rest.UserRestFT.java
/** * ?ShiroHttpBasic?//from w w w. j a v a 2 s . c o m */ @Test public void authWithHttpBasic() { // Http Basic? HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set(com.google.common.net.HttpHeaders.AUTHORIZATION, Servlets.encodeHttpBasic("admin", "wrongpassword")); HttpEntity<?> requestEntity = new HttpEntity(requestHeaders); try { jdkTemplate.exchange(resourceUrl + "/{id}.xml", HttpMethod.GET, requestEntity, UserDTO.class, 1L); fail("Get should fail with error username/password"); } catch (HttpStatusCodeException e) { assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } }
From source file:com.wolkabout.hexiwear.activity.SignUpActivity.java
@Background void startSignUp() { final SignUpDto signUpDto = parseUserInput(); try {/*from w w w . j a va 2 s.c o m*/ authenticationService.signUp(signUpDto); onSignUpSuccess(); } catch (HttpStatusCodeException e) { if (e.getStatusCode() == HttpStatus.BAD_REQUEST && e.getResponseBodyAsString().contains("USER_EMAIL_IS_NOT_UNIQUE")) { onSignUpError(R.string.registration_error_email_already_exists); return; } onSignUpError(R.string.registration_failed); } catch (Exception e) { onSignUpError(R.string.registration_failed); } finally { dismissSigningUpLabel(); } }
From source file:com.atwelm.aezwidget.responses.interfaces.AEZCell.java
/** * Executes the URL and associated details for the cell * @param callback The callback when completed *//* www . ja v a 2 s . com*/ public final void execute(final ExecutionResponseCallback callback) { if (!isExecutable()) { return; } Thread t = new Thread(new Runnable() { @Override public void run() { try { String executionType = getExecutionType(); String executionUrl = getExecutionUrl(); String executionBody = getExecutionBody(); HttpHeaders executionHeaders = getExecutionHeaders(); HttpEntity<String> requestEntity = new HttpEntity<String>(executionBody, executionHeaders); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<GenericExecutionResponse> responseEntity = restTemplate.exchange(executionUrl, HttpMethod.valueOf(executionType), requestEntity, GenericExecutionResponse.class); int returnStatus = responseEntity.getStatusCode().value(); if (returnStatus <= 200 && returnStatus < 300) { GenericExecutionResponse response = responseEntity.getBody(); if (callback != null) { callback.success(response); } } else { if (callback != null) { callback.failure(returnStatus); } } } catch (HttpStatusCodeException hsce) { callback.failure(hsce.getStatusCode().value()); } catch (RestClientException rce) { // TODO: Make this more specific since it includes scenarios such as when the network cannot be reached callback.failure(-1); } } }); t.start(); }
From source file:com.weibo.handler.ErrorCodeHandler.java
public ErrorCode handle(HttpStatusCodeException error) { ObjectMapper objectMapper = new ObjectMapper(); ErrorCode errorCode = new ErrorCode(); errorCode.setRequest(StringUtils.EMPTY); errorCode.setErrorCode(error.getStatusCode().toString()); errorCode.setError(error.getStatusText()); try {//from ww w .j ava 2 s. c o m errorCode = objectMapper.readValue(error.getResponseBodyAsByteArray(), ErrorCode.class); } catch (JsonParseException e) { log.error(ExceptionUtils.getFullStackTrace(e)); } catch (JsonMappingException e) { log.error(ExceptionUtils.getFullStackTrace(e)); } catch (IOException e) { log.error(ExceptionUtils.getFullStackTrace(e)); } return errorCode; }
From source file:org.openlmis.fulfillment.service.BaseCommunicationServiceTest.java
@Test public void shouldRetryObtainingAccessTokenIfResponseBodyIsEmpty() throws Exception { // given/*from w w w .j a va 2 s .c o m*/ BaseCommunicationService<T> service = prepareService(); HttpStatusCodeException exception = mock(HttpStatusCodeException.class); when(exception.getStatusCode()).thenReturn(HttpStatus.UNAUTHORIZED); when(exception.getResponseBodyAsString()).thenReturn(""); // when when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(HttpEntity.class), eq(service.getArrayResultClass()))).thenThrow(exception); expectedException.expect(DataRetrievalException.class); service.findAll("", RequestParameters.init()); verify(authService, times(1)).clearTokenCache(); verify(authService, times(2)).obtainAccessToken(); }
From source file:org.openlmis.fulfillment.service.BaseCommunicationServiceTest.java
@Test public void shouldRetryObtainingAccessToken() throws Exception { // given/* www. j a va2 s. c o m*/ BaseCommunicationService<T> service = prepareService(); HttpStatusCodeException exception = mock(HttpStatusCodeException.class); when(exception.getStatusCode()).thenReturn(HttpStatus.UNAUTHORIZED); when(exception.getResponseBodyAsString()) .thenReturn("{\"error\":\"invalid_token\",\"error_description\":\"" + UUID.randomUUID() + "}"); // when when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(HttpEntity.class), eq(service.getArrayResultClass()))).thenThrow(exception); expectedException.expect(DataRetrievalException.class); service.findAll("", RequestParameters.init()); verify(authService, times(1)).clearTokenCache(); verify(authService, times(2)).obtainAccessToken(); }
From source file:com.t163.handler.T163ErrorCodeHandler.java
public T163ErrorCode handle(HttpStatusCodeException error) { ObjectMapper objectMapper = new ObjectMapper(); T163ErrorCode errorCode = new T163ErrorCode(); errorCode.setRequest(StringUtils.EMPTY); errorCode.setErrorCode(error.getStatusCode().toString()); errorCode.setError(error.getStatusText()); try {//w w w . j a v a 2 s . c o m errorCode = objectMapper.readValue(error.getResponseBodyAsByteArray(), T163ErrorCode.class); } catch (JsonParseException e) { log.error(ExceptionUtils.getFullStackTrace(e)); } catch (JsonMappingException e) { log.error(ExceptionUtils.getFullStackTrace(e)); } catch (IOException e) { log.error(ExceptionUtils.getFullStackTrace(e)); } return errorCode; }
From source file:eu.cloudwave.wp5.feedback.eclipse.base.infrastructure.rest.RestClientImpl.java
private void handleErrors(final RestClientException exception) { // handle 404 NOT FOUND error if (exception instanceof ResourceAccessException) { throw new RequestException(ErrorType.FEEDBACK_HANDLER_NOT_AVAILABLE, exception.getMessage()); } else if (exception instanceof HttpStatusCodeException) { final HttpStatusCodeException httpException = (HttpStatusCodeException) exception; // handle 404 NOT FOUND error if (httpException.getStatusCode().equals(HttpStatus.NOT_FOUND)) { throw new RequestException(ErrorType.FEEDBACK_HANDLER_NOT_AVAILABLE, exception.getMessage()); }/*from w ww . java 2 s .c o m*/ // handle other errors final ObjectMapper mapper = new ObjectMapper(); try { final RestRequestErrorDto error = mapper.readValue(httpException.getResponseBodyAsString(), RestRequestErrorDto.class); throw new RequestException(error.getType(), error.getMessage()); } catch (final IOException e) { } } throw new RuntimeException(READ_SERVER_ERROR_EXCEPTION, exception); }