Java Code Examples for org.springframework.web.client.HttpClientErrorException#getResponseBodyAsString()

The following examples show how to use org.springframework.web.client.HttpClientErrorException#getResponseBodyAsString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JobServiceImpl.java    From griffin with Apache License 2.0 6 votes vote down vote up
/**
 * Check instance status in case that session id is overdue and app id is
 * null and so we cannot update instance state
 * .
 *
 * @param instance job instance bean
 * @param e        HttpClientErrorException
 * @return boolean
 */
private boolean checkStatus(JobInstanceBean instance,
                            HttpClientErrorException e) {
    int code = e.getStatusCode().value();
    String appId = instance.getAppId();
    String responseBody = e.getResponseBodyAsString();
    Long sessionId = instance.getSessionId();
    sessionId = sessionId != null ? sessionId : -1;
    // If code is 404 and appId is null and response body is like 'Session
    // {id} not found',this means instance may not be scheduled for
    // a long time by spark for too many tasks. It may be dead.
    if (code == 404 && appId == null && (responseBody != null &&
        responseBody.contains(sessionId.toString()))) {
        instance.setState(DEAD);
        instance.setDeleted(true);
        instanceRepo.save(instance);
        return true;
    }
    return false;
}
 
Example 2
Source File: BasicSpringBoot2Test.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorsSerializedAsJsonApi() throws IOException {
	RestTemplate testRestTemplate = new RestTemplate();
	try {
		testRestTemplate
				.getForEntity("http://localhost:" + this.port + "/doesNotExist", String.class);
		Assert.fail();
	}
	catch (HttpClientErrorException e) {
		assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode());

		String body = e.getResponseBodyAsString();
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(JacksonModule.createJacksonModule());
		Document document = mapper.readerFor(Document.class).readValue(body);

		Assert.assertEquals(1, document.getErrors().size());
		ErrorData errorData = document.getErrors().get(0);
		Assert.assertEquals("404", errorData.getStatus());
		Assert.assertEquals("Not Found", errorData.getTitle());
		Assert.assertEquals("No message available", errorData.getDetail());
	}
}
 
Example 3
Source File: BasicSpringBoot1Test.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorsSerializedAsJsonApi() throws IOException {
	RestTemplate testRestTemplate = new RestTemplate();
	try {
		testRestTemplate
				.getForEntity("http://localhost:" + this.port + "/doesNotExist", String.class);
		Assert.fail();
	} catch (HttpClientErrorException e) {
		assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode());

		String body = e.getResponseBodyAsString();
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(JacksonModule.createJacksonModule());
		Document document = mapper.readerFor(Document.class).readValue(body);

		Assert.assertEquals(1, document.getErrors().size());
		ErrorData errorData = document.getErrors().get(0);
		Assert.assertEquals("404", errorData.getStatus());
		Assert.assertEquals("Not Found", errorData.getTitle());
		Assert.assertEquals("No message available", errorData.getDetail());
	}
}
 
Example 4
Source File: NamespaceControllerTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFailWhenAppNamespaceNameIsInvalid() {
  Assert.assertTrue(consumerPermissionValidator.hasCreateNamespacePermission(null, null));

  OpenAppNamespaceDTO dto = new OpenAppNamespaceDTO();
  dto.setAppId("appId");
  dto.setName("invalid name");
  dto.setFormat(ConfigFileFormat.Properties.getValue());
  dto.setDataChangeCreatedBy("apollo");
  try {
    restTemplate.postForEntity(
        url("/openapi/v1/apps/{appId}/appnamespaces"),
        dto, OpenAppNamespaceDTO.class, dto.getAppId()
    );
    Assert.fail("should throw");
  } catch (HttpClientErrorException e) {
    String result = e.getResponseBodyAsString();
    Assert.assertThat(result, containsString(InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE));
    Assert.assertThat(result, containsString(InputValidator.INVALID_NAMESPACE_NAMESPACE_MESSAGE));
  }
}
 
Example 5
Source File: RepositoryClient.java    From mojito with Apache License 2.0 6 votes vote down vote up
/**
 * Updates a {@link Repository}
 *
 * @param name
 * @param newName
 * @param description
 * @param repositoryLocales With id, and repository id not set
 * @param integrityCheckers
 * @throws com.box.l10n.mojito.rest.client.exception.RepositoryNotFoundException
 * @throws com.box.l10n.mojito.rest.client.exception.ResourceNotUpdatedException
 */
public void updateRepository(String name, String newName, String description, Boolean checkSLA, Set<RepositoryLocale> repositoryLocales, Set<IntegrityChecker> integrityCheckers) throws RepositoryNotFoundException, ResourceNotUpdatedException {

    logger.debug("Updating repository by name = [{}]", name);
    Repository repository = getRepositoryByName(name);

    repository.setDescription(description);
    repository.setName(newName);
    repository.setRepositoryLocales(repositoryLocales);
    repository.setCheckSLA(checkSLA);
    if (integrityCheckers != null) {
        repository.setIntegrityCheckers(integrityCheckers);
    }

    try {
        authenticatedRestTemplate.patch(getBasePathForResource(repository.getId()), repository);
    } catch (HttpClientErrorException exception) {
        if (exception.getStatusCode().equals(HttpStatus.CONFLICT)) {
            throw new ResourceNotUpdatedException(exception.getResponseBodyAsString());
        } else {
            throw exception;
        }
    }

}
 
Example 6
Source File: RestErrorAdvice.java    From sample-boot-micro with MIT License 5 votes vote down vote up
/** RestTemplate 例外時のブリッジサポート */
@ExceptionHandler(HttpClientErrorException.class)
public ResponseEntity<String> handleHttpClientError(HttpClientErrorException e) {
    HttpHeaders headers = new HttpHeaders();
    headers.put(HttpHeaders.CONTENT_TYPE, Arrays.asList(MediaType.APPLICATION_JSON_VALUE));
    return new ResponseEntity<>(e.getResponseBodyAsString(), headers, e.getStatusCode());
}
 
Example 7
Source File: RepositoryClient.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link Repository} using the API
 *
 * @param name
 * @param description
 * @param sourceLocale
 * @param repositoryLocales With id, and repository id not set
 * @param integrityCheckers
 * @return
 * @throws com.box.l10n.mojito.rest.client.exception.ResourceNotCreatedException
 */
public Repository createRepository(String name,
                                   String description,
                                   Locale sourceLocale,
                                   Set<RepositoryLocale> repositoryLocales,
                                   Set<IntegrityChecker> integrityCheckers,
                                   Boolean checkSLA) throws ResourceNotCreatedException {
    logger.debug("Creating repo with name = {}, and description = {}, and repositoryLocales = {}", name, description, repositoryLocales.toString());

    Repository repoToCreate = new Repository();
    repoToCreate.setName(name);
    repoToCreate.setDescription(description);
    repoToCreate.setSourceLocale(sourceLocale);
    repoToCreate.setRepositoryLocales(repositoryLocales);
    repoToCreate.setIntegrityCheckers(integrityCheckers);
    repoToCreate.setCheckSLA(checkSLA);

    try {
        return authenticatedRestTemplate.postForObject(getBasePathForEntity(), repoToCreate, Repository.class);
    } catch (HttpClientErrorException exception) {
        if (exception.getStatusCode().equals(HttpStatus.CONFLICT)) {
            throw new ResourceNotCreatedException(exception.getResponseBodyAsString());
        } else {
            throw exception;
        }
    }
}
 
Example 8
Source File: Bot.java    From jbot with GNU General Public License v3.0 5 votes vote down vote up
protected final ResponseEntity<String> reply(Event event) {
    sendTypingOffIndicator(event.getRecipient());
    logger.debug("Send message: {}", event.toString());
    try {
        return restTemplate.postForEntity(fbSendUrl, event, String.class);
    } catch (HttpClientErrorException e) {
        logger.error("Send message error: Response body: {} \nException: ", e.getResponseBodyAsString(), e);
        return new ResponseEntity<>(e.getResponseBodyAsString(), e.getStatusCode());
    }
}
 
Example 9
Source File: RestErrorAdvice.java    From sample-boot-hibernate with MIT License 5 votes vote down vote up
/** RestTemplate 例外時のブリッジサポート */
@ExceptionHandler(HttpClientErrorException.class)
public ResponseEntity<String> handleHttpClientError(HttpClientErrorException e) {
    HttpHeaders headers = new HttpHeaders();
    headers.put(HttpHeaders.CONTENT_TYPE, Arrays.asList(MediaType.APPLICATION_JSON_VALUE));
    return new ResponseEntity<>(e.getResponseBodyAsString(), headers, e.getStatusCode());
}
 
Example 10
Source File: ArtifactoryClient.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
private void handle(Consumer<Object> logger, String message, HttpClientErrorException o_O) {

		try {

			logger.accept(message);

			Errors errors = new ObjectMapper().readValue(o_O.getResponseBodyAsByteArray(), Errors.class);
			errors.getErrors().forEach(logger);
			errors.getMessages().forEach(logger);

		} catch (IOException e) {
			o_O.addSuppressed(e);
			throw new RuntimeException(o_O.getResponseBodyAsString(), o_O);
		}
	}
 
Example 11
Source File: ClientfacingErrorITest.java    From backstopper with Apache License 2.0 4 votes vote down vote up
@RequestMapping("/throw4xxServerHttpStatusCodeException")
public void throw4xxServerHttpStatusCodeException() {
    HttpClientErrorException serverResponseEx = new HttpClientErrorException(HttpStatus.FAILED_DEPENDENCY, "ignoreme", responseBodyForDownstreamServiceError(), null);
    throw new ServerHttpStatusCodeException(new Exception("Intentional test exception"), "FOO", serverResponseEx, serverResponseEx.getStatusCode().value(), serverResponseEx.getResponseHeaders(), serverResponseEx.getResponseBodyAsString());
}
 
Example 12
Source File: SmartlingClient.java    From mojito with Apache License 2.0 2 votes vote down vote up
/**
 * For error raised through HTTP error.
 *
 * Note that 200 is not always success, {@see throwExceptionOnError}
 */
SmartlingClientException wrapIntoSmartlingException(HttpClientErrorException httpClientErrorException, String messageSummary, Object... vars) throws SmartlingClientException {
    String msg = String.format(messageSummary, vars) + "\nMessage: " + httpClientErrorException.getMessage() + "\nBody: " +  httpClientErrorException.getResponseBodyAsString();
    return new SmartlingClientException(msg, httpClientErrorException);
}