use of org.springframework.web.client.HttpClientErrorException in project webofneeds by researchstudio-sat.
the class SignatureCheckingWonMessageProcessor method process.
@Override
public WonMessage process(final WonMessage message) throws WonMessageProcessingException {
StopWatch sw = new StopWatch();
try {
SignatureVerificationState result;
/*
* If the message is a successResponse to a delete Message then we can't check
* the signature as it is stored in the deleted Atom, so we just accept the
* message as valid and return it.
*/
if (message.getRespondingToMessageType() == WonMessageType.DELETE && message.getMessageType() == WonMessageType.SUCCESS_RESPONSE) {
return message;
}
for (WonMessage toCheck : message.getAllMessages()) {
try {
// obtain public keys
sw.start("get public keys");
Map<String, PublicKey> keys = WonKeysReaderWriter.readKeyFromMessage(toCheck);
WonMessageType type = toCheck.getMessageType();
switch(type) {
case CREATE_ATOM:
if (keys.isEmpty()) {
throw new WonMessageProcessingException("No key found in CREATE message");
}
break;
case REPLACE:
if (keys.isEmpty()) {
keys.putAll(getRequiredPublicKeys(toCheck.getCompleteDataset()));
}
break;
default:
if (!keys.isEmpty()) {
throw new WonMessageProcessingException(String.format("An Atom key may only be embedded in CREATE or REPLACE messages! Found one in %s message %s", type, message.getMessageURIRequired()));
}
keys.putAll(getRequiredPublicKeys(toCheck.getCompleteDataset()));
}
sw.stop();
// verify with those public keys
sw.start("verify");
result = WonMessageSignerVerifier.verify(keys, toCheck);
sw.stop();
if (logger.isDebugEnabled()) {
logger.debug("VERIFIED=" + result.isVerificationPassed() + " with keys: " + keys.values() + " for\n" + RdfUtils.writeDatasetToString(Prefixer.setPrefixes(toCheck.getCompleteDataset()), Lang.TRIG));
}
} catch (LinkedDataFetchingException e) {
/*
* If a delete message could not be validated because the atom was already
* deleted, we assume that this message is just mirrored back to the owner and
* is to be accepteed
*/
if (WonMessageType.DELETE.equals(toCheck.getMessageType())) {
if (e.getCause() instanceof HttpClientErrorException && HttpStatus.GONE.equals(((HttpClientErrorException) e.getCause()).getStatusCode())) {
if (logger.isDebugEnabled()) {
logger.debug("Failure during processing signature check of message" + toCheck.getMessageURI() + " (messageType was DELETE, but atom is already deleted, accept message anyway)");
}
return toCheck;
}
}
// TODO SignatureProcessingException?
throw new WonMessageProcessingException("Could not verify message " + toCheck.getMessageURI(), e);
} catch (Exception e) {
// TODO SignatureProcessingException?
throw new WonMessageProcessingException("Could not verify message " + toCheck.getMessageURI(), e);
}
// throw exception if the verification fails:
if (!result.isVerificationPassed()) {
String errormessage = "Message verification failed. Message:" + toCheck.toStringForDebug(false) + ", Problem:" + result.getMessage();
if (logger.isDebugEnabled()) {
logger.debug(errormessage + ". Offending message:\n" + RdfUtils.toString(Prefixer.setPrefixes(toCheck.getCompleteDataset())));
}
// TODO SignatureProcessingException?
throw new WonMessageProcessingException(new SignatureException(errormessage + ". To log the offending message, set Loglevel to DEBUG for logger '" + this.getClass().getName() + "'"));
}
}
return message;
} finally {
logger.debug(LogMarkers.TIMING, "Signature check for message {} took {} millis, details:\n {}", new Object[] { message.getMessageURIRequired(), sw.getTotalTimeMillis(), sw.prettyPrint() });
}
}
use of org.springframework.web.client.HttpClientErrorException in project spring-cloud-config by spring-cloud.
the class ConfigServicePropertySourceLocator method getRemoteEnvironment.
private Environment getRemoteEnvironment(RestTemplate restTemplate, ConfigClientProperties properties, String label, String state) {
String path = "/{name}/{profile}";
String name = properties.getName();
String profile = properties.getProfile();
String token = properties.getToken();
String uri = properties.getRawUri();
Object[] args = new String[] { name, profile };
if (StringUtils.hasText(label)) {
args = new String[] { name, profile, label };
path = path + "/{label}";
}
ResponseEntity<Environment> response = null;
try {
HttpHeaders headers = new HttpHeaders();
if (StringUtils.hasText(token)) {
headers.add(TOKEN_HEADER, token);
}
if (StringUtils.hasText(state)) {
// TODO: opt in to sending state?
headers.add(STATE_HEADER, state);
}
final HttpEntity<Void> entity = new HttpEntity<>((Void) null, headers);
response = restTemplate.exchange(uri + path, HttpMethod.GET, entity, 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;
}
use of org.springframework.web.client.HttpClientErrorException in project spring-cloud-sleuth by spring-cloud.
the class TraceFilterWebIntegrationTests method should_create_spans_for_endpoint_returning_unsuccessful_result.
@Test
public void should_create_spans_for_endpoint_returning_unsuccessful_result() {
try {
new RestTemplate().getForObject("http://localhost:" + port() + "/test_bad_request", String.class);
fail("should throw exception");
} catch (HttpClientErrorException e) {
}
then(Tracing.current().tracer().currentSpan()).isNull();
then(this.accumulator.getSpans()).hasSize(1);
then(this.accumulator.getSpans().get(0).kind().ordinal()).isEqualTo(Span.Kind.SERVER.ordinal());
then(this.accumulator.getSpans().get(0).tags()).containsEntry("http.status_code", "400");
then(this.accumulator.getSpans().get(0).tags()).containsEntry("http.path", "/test_bad_request");
}
use of org.springframework.web.client.HttpClientErrorException in project crnk-framework by crnk-project.
the class BasicSpringBootTest method testErrorsSerializedAsJsonApi.
@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());
}
}
use of org.springframework.web.client.HttpClientErrorException in project tutorials by eugenp.
the class PetApi method findPetsByStatus.
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid status value
* @param status Status values that need to be considered for filter
* @return List<Pet>
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public List<Pet> findPetsByStatus(List<String> status) throws RestClientException {
Object postBody = null;
// verify the required parameter 'status' is set
if (status == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'status' when calling findPetsByStatus");
}
String path = UriComponentsBuilder.fromPath("/pet/findByStatus").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase()), "status", status));
final String[] accepts = { "application/xml", "application/json" };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
ParameterizedTypeReference<List<Pet>> returnType = new ParameterizedTypeReference<List<Pet>>() {
};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
Aggregations