Search in sources :

Example 31 with RestClientException

use of org.springframework.web.client.RestClientException in project commons by craftercms.

the class HttpMessageConvertingResponseErrorHandler method handleError.

@Override
public void handleError(ClientHttpResponse response) throws IOException {
    HttpStatus status = response.getStatusCode();
    HttpMessageConverterExtractor<?> responseExtractor = new HttpMessageConverterExtractor<>(responseType, messageConverters);
    Object errorDetails;
    try {
        errorDetails = responseExtractor.extractData(response);
    } catch (RestClientException e) {
        // the response body as string
        throw new RestServiceException(status, getResponseBodyAsString(response));
    }
    throw new RestServiceException(status, errorDetails);
}
Also used : HttpStatus(org.springframework.http.HttpStatus) HttpMessageConverterExtractor(org.springframework.web.client.HttpMessageConverterExtractor) RestClientException(org.springframework.web.client.RestClientException)

Example 32 with RestClientException

use of org.springframework.web.client.RestClientException in project spring-cloud-sleuth by spring-cloud.

the class TraceExchangeFilterFunction method filter.

@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
    final ClientRequest.Builder builder = ClientRequest.from(request);
    Mono<ClientResponse> exchange = Mono.defer(() -> next.exchange(builder.build())).cast(Object.class).onErrorResume(Mono::just).zipWith(Mono.subscriberContext()).flatMap(anyAndContext -> {
        Object any = anyAndContext.getT1();
        Span clientSpan = anyAndContext.getT2().get(CLIENT_SPAN_KEY);
        Mono<ClientResponse> continuation;
        final Tracer.SpanInScope ws = tracer().withSpanInScope(clientSpan);
        if (any instanceof Throwable) {
            continuation = Mono.error((Throwable) any);
        } else {
            continuation = Mono.just((ClientResponse) any);
        }
        return continuation.doAfterSuccessOrError((clientResponse, throwable1) -> {
            Throwable throwable = throwable1;
            if (clientResponse == null || clientResponse.statusCode() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No response was returned. Will close the span [" + clientSpan + "]");
                }
                handleReceive(clientSpan, ws, clientResponse, throwable);
                return;
            }
            boolean error = clientResponse.statusCode().is4xxClientError() || clientResponse.statusCode().is5xxServerError();
            if (error) {
                if (log.isDebugEnabled()) {
                    log.debug("Non positive status code was returned from the call. Will close the span [" + clientSpan + "]");
                }
                throwable = new RestClientException("Status code of the response is [" + clientResponse.statusCode().value() + "] and the reason is [" + clientResponse.statusCode().getReasonPhrase() + "]");
            }
            handleReceive(clientSpan, ws, clientResponse, throwable);
        });
    }).subscriberContext(c -> {
        if (log.isDebugEnabled()) {
            log.debug("Instrumenting WebClient call");
        }
        Span parent = c.getOrDefault(Span.class, null);
        Span clientSpan = handler().handleSend(injector(), builder, request, tracer().nextSpan());
        if (log.isDebugEnabled()) {
            log.debug("Created a client span for the WebClient " + clientSpan);
        }
        if (parent == null) {
            c = c.put(Span.class, clientSpan);
            if (log.isDebugEnabled()) {
                log.debug("Reactor Context got injected with the client span " + clientSpan);
            }
        }
        return c.put(CLIENT_SPAN_KEY, clientSpan);
    });
    return exchange;
}
Also used : ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) RestClientException(org.springframework.web.client.RestClientException) HttpTracing(brave.http.HttpTracing) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) Tracer(brave.Tracer) Span(brave.Span) WebClient(org.springframework.web.reactive.function.client.WebClient) BeansException(org.springframework.beans.BeansException) Mono(reactor.core.publisher.Mono) TraceContext(brave.propagation.TraceContext) Consumer(java.util.function.Consumer) BeanPostProcessor(org.springframework.beans.factory.config.BeanPostProcessor) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) List(java.util.List) ExchangeFilterFunction(org.springframework.web.reactive.function.client.ExchangeFilterFunction) BeanFactory(org.springframework.beans.factory.BeanFactory) Propagation(brave.propagation.Propagation) HttpClientHandler(brave.http.HttpClientHandler) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) Mono(reactor.core.publisher.Mono) RestClientException(org.springframework.web.client.RestClientException) Span(brave.Span) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest)

Example 33 with RestClientException

use of org.springframework.web.client.RestClientException in project syndesis-qe by syndesisio.

the class EndpointClient method createAllTrustingClient.

// Required in order to skip certificate validation
private static HttpClient createAllTrustingClient() {
    HttpClient httpclient;
    try {
        final SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial((TrustStrategy) (X509Certificate[] chain, String authType) -> true);
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), // needed to connections to API Provider integrations
        new NoopHostnameVerifier());
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).setMaxConnTotal(1000).setMaxConnPerRoute(1000).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new RestClientException("Cannot create all SSL certificates trusting client", e);
    }
    return httpclient;
}
Also used : NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HttpClient(org.apache.http.client.HttpClient) RestClientException(org.springframework.web.client.RestClientException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) X509Certificate(java.security.cert.X509Certificate) KeyManagementException(java.security.KeyManagementException)

Example 34 with RestClientException

use of org.springframework.web.client.RestClientException in project nzbhydra2 by theotherp.

the class Sabnzbd method checkConnection.

@Override
public GenericResponse checkConnection() {
    logger.debug("Checking connection");
    UriComponentsBuilder baseUrl = getBaseUrl();
    try {
        restTemplate.exchange(baseUrl.queryParam("mode", "get_cats").toUriString(), HttpMethod.GET, null, CategoriesResponse.class);
        logger.info("Connection check with sabnzbd using URL {} successful", baseUrl.toUriString());
        return new GenericResponse(true, null);
    } catch (RestClientException e) {
        logger.info("Connection check with sabnzbd using URL {} failed: {}", baseUrl.toUriString(), e.getMessage());
        return new GenericResponse(false, e.getMessage());
    }
}
Also used : GenericResponse(org.nzbhydra.GenericResponse) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) RestClientException(org.springframework.web.client.RestClientException)

Example 35 with RestClientException

use of org.springframework.web.client.RestClientException in project nzbhydra2 by theotherp.

the class UpdateManager method installUpdate.

public void installUpdate() throws UpdateException {
    Release latestRelease = latestReleaseCache.get();
    logger.info("Starting update process to {}", latestRelease.getTagName());
    Asset asset = getAsset(latestRelease);
    String url = asset.getBrowserDownloadUrl();
    logger.debug("Downloading update from URL {}", url);
    File updateZip;
    try {
        File updateFolder = new File(NzbHydra.getDataFolder(), "update");
        if (!updateFolder.exists()) {
            logger.debug("Creating update folder {}", updateFolder);
            Files.createDirectory(updateFolder.toPath());
        } else {
            logger.debug("Cleaning update folder {}", updateFolder.getAbsolutePath());
            FileUtils.cleanDirectory(updateFolder);
        }
        updateZip = new File(updateFolder, asset.getName());
        logger.debug("Saving update file as {}", updateZip.getAbsolutePath());
        applicationEventPublisher.publishEvent(new UpdateEvent("Downloading update file"));
        webAccess.downloadToFile(url, updateZip);
    } catch (RestClientException | IOException e) {
        logger.error("Error while download or saving ZIP", e);
        throw new UpdateException("Error while downloading, saving or extracting update ZIP", e);
    }
    if (configProvider.getBaseConfig().getMain().isBackupBeforeUpdate()) {
        try {
            logger.info("Creating backup before shutting down");
            applicationEventPublisher.publishEvent(new UpdateEvent("Creating backup before update"));
            backupAndRestore.backup();
        } catch (Exception e) {
            throw new UpdateException("Unable to create backup before update", e);
        }
    }
    logger.info("Shutting down to let wrapper execute the update");
    applicationEventPublisher.publishEvent(new UpdateEvent("Shutting down to let wrapper execute update"));
    exitWithReturnCode(UPDATE_RETURN_CODE);
}
Also used : RestClientException(org.springframework.web.client.RestClientException) Asset(org.nzbhydra.mapping.github.Asset) IOException(java.io.IOException) File(java.io.File) Release(org.nzbhydra.mapping.github.Release) RestClientException(org.springframework.web.client.RestClientException) IOException(java.io.IOException)

Aggregations

RestClientException (org.springframework.web.client.RestClientException)43 HttpHeaders (org.springframework.http.HttpHeaders)12 HttpEntity (org.springframework.http.HttpEntity)11 IOException (java.io.IOException)9 RestTemplate (org.springframework.web.client.RestTemplate)9 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)8 Test (org.junit.Test)5 JsonParseException (com.fasterxml.jackson.core.JsonParseException)4 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)4 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)4 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)4 URI (java.net.URI)3 List (java.util.List)3 Test (org.junit.jupiter.api.Test)3 JSONObject (com.alibaba.fastjson.JSONObject)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 RealNameAuthentication (com.itrus.portal.db.RealNameAuthentication)2 RealNameAuthenticationExample (com.itrus.portal.db.RealNameAuthenticationExample)2 GitHubDTO (com.nixmash.blog.jpa.dto.GitHubDTO)2