Search in sources :

Example 21 with HttpClientErrorException

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() });
    }
}
Also used : WonMessageProcessingException(won.protocol.exception.WonMessageProcessingException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) PublicKey(java.security.PublicKey) WonMessage(won.protocol.message.WonMessage) LinkedDataFetchingException(won.protocol.rest.LinkedDataFetchingException) WonMessageType(won.protocol.message.WonMessageType) SignatureVerificationState(won.cryptography.rdfsign.SignatureVerificationState) SignatureException(java.security.SignatureException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) WonMessageProcessingException(won.protocol.exception.WonMessageProcessingException) SignatureException(java.security.SignatureException) LinkedDataFetchingException(won.protocol.rest.LinkedDataFetchingException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) StopWatch(org.springframework.util.StopWatch)

Example 22 with HttpClientErrorException

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;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) Environment(org.springframework.cloud.config.environment.Environment)

Example 23 with HttpClientErrorException

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");
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) RestTemplate(org.springframework.web.client.RestTemplate) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 24 with HttpClientErrorException

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());
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) RestTemplate(org.springframework.web.client.RestTemplate) Document(io.crnk.core.engine.document.Document) ErrorData(io.crnk.core.engine.document.ErrorData) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 25 with HttpClientErrorException

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&lt;Pet&gt;
 * @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);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) MediaType(org.springframework.http.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) Pet(com.baeldung.petstore.client.model.Pet)

Aggregations

HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)113 HttpHeaders (org.springframework.http.HttpHeaders)31 Test (org.junit.Test)25 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)24 HashMap (java.util.HashMap)21 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)21 MediaType (org.springframework.http.MediaType)19 RestTemplate (org.springframework.web.client.RestTemplate)19 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)18 HttpEntity (org.springframework.http.HttpEntity)16 URI (java.net.URI)15 Map (java.util.Map)8 HttpStatus (org.springframework.http.HttpStatus)8 RestClientException (org.springframework.web.client.RestClientException)8 ResourceAccessException (org.springframework.web.client.ResourceAccessException)7 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)6 Date (java.util.Date)5 List (java.util.List)5 OpenAppNamespaceDTO (com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO)4 ArrayList (java.util.ArrayList)4