Example usage for org.apache.http.impl.client HttpClientBuilder setRetryHandler

List of usage examples for org.apache.http.impl.client HttpClientBuilder setRetryHandler

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder setRetryHandler.

Prototype

public final HttpClientBuilder setRetryHandler(final HttpRequestRetryHandler retryHandler) 

Source Link

Document

Assigns HttpRequestRetryHandler instance.

Usage

From source file:org.jboss.pnc.client.ApacheHttpClient43EngineWithRetry.java

@Override
protected HttpClient createDefaultHttpClient() {
    logger.info("Bootstrapping http engine with request retry handler...");
    final HttpClientBuilder builder = HttpClientBuilder.create();
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    if (defaultProxy != null) {
        requestBuilder.setProxy(defaultProxy);
    }//  w  w w  .  ja va 2  s  .c o  m
    builder.disableContentCompression();
    builder.setDefaultRequestConfig(requestBuilder.build());

    HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler();
    builder.setRetryHandler(retryHandler);
    return builder.build();
}

From source file:sk.datalan.solr.impl.HttpClientUtil.java

public static HttpClientBuilder configureClient(final HttpClientConfiguration config) {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    // max total connections
    if (config.isSetMaxConnections()) {
        clientBuilder.setMaxConnTotal(config.getMaxConnections());
    }//from w w  w . j a va 2s.c  o m

    // max connections per route
    if (config.isSetMaxConnectionsPerRoute()) {
        clientBuilder.setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    }

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true);

    // connection timeout
    if (config.isSetConnectionTimeout()) {
        requestConfigBuilder.setConnectTimeout(config.getConnectionTimeout());
    }

    // soucket timeout
    if (config.isSetSocketTimeout()) {
        requestConfigBuilder.setSocketTimeout(config.getSocketTimeout());
    }

    // soucket timeout
    if (config.isSetFollowRedirects()) {
        requestConfigBuilder.setRedirectsEnabled(config.getFollowRedirects());
    }
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    if (config.isSetUseRetry()) {
        if (config.getUseRetry()) {
            clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler());
        } else {
            clientBuilder.setRetryHandler(NO_RETRY);
        }
    }

    // basic authentication
    if (config.isSetBasicAuthUsername() && config.isSetBasicAuthPassword()) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(config.getBasicAuthUsername(), config.getBasicAuthPassword()));
    }

    if (config.isSetAllowCompression()) {
        clientBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor());
        clientBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor());
    }

    // SSL context for secure connections can be created either based on
    // system or application specific properties.
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    // Use custom hostname verifier to customize SSL hostname verification.
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();

    clientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));

    return clientBuilder;
}

From source file:de.shadowhunt.subversion.internal.AbstractHelper.java

public HttpClient getHttpClient(final String username, final HttpRequestInterceptor... interceptors) {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    final CredentialsProvider cp = new BasicCredentialsProvider();
    final Credentials credentials = new UsernamePasswordCredentials(username, PASSWORD);
    cp.setCredentials(AuthScope.ANY, credentials);
    builder.setDefaultCredentialsProvider(cp);

    for (HttpRequestInterceptor interceptor : interceptors) {
        builder.addInterceptorFirst(interceptor);
    }//from ww  w.j  a va2s  . c  om

    builder.setRetryHandler(new SubversionRequestRetryHandler());
    return builder.build();
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyConnectorClient.java

private CloseableHttpClient createHttpClient() {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    // setting the SoTimeout (which is configured in seconds)
    builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(1000 * config.getSoTimeout()).build());
    builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    return builder.build();
}

From source file:org.tinymediamanager.scraper.util.TmmHttpClient.java

/**
 * instantiates a new CloseableHttpClient
 * //from   ww w.  j  a va 2  s  . c  o  m
 * @return CloseableHttpClient
 */
public static CloseableHttpClient createHttpClient() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    // Increase default max connection per route to 5
    connectionManager.setMaxTotal(5);

    HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();
    httpClientBuilder.setConnectionManager(connectionManager);

    // my own retry handler
    HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= 5) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return false;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {
                // Connection refused
                return false;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        }

    };
    httpClientBuilder.setRetryHandler(myRetryHandler);

    // set proxy if needed
    if ((Globals.settings.useProxy())) {
        setProxy(httpClientBuilder);
    }

    return httpClientBuilder.build();
}

From source file:com.netflix.spinnaker.orca.pipeline.util.HttpClientUtils.java

private static CloseableHttpClient httpClientWithServiceUnavailableRetryStrategy() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
                @Override/* w  w w. j  a va  2  s. co m*/
                public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    HttpUriRequest currentReq = (HttpUriRequest) context
                            .getAttribute(HttpCoreContext.HTTP_REQUEST);
                    LOGGER.info("Response code {} for {}", statusCode, currentReq.getURI());

                    if (statusCode >= HttpStatus.SC_OK && statusCode <= 299) {
                        return false;
                    }

                    boolean shouldRetry = (statusCode == 429
                            || RETRYABLE_500_HTTP_STATUS_CODES.contains(statusCode))
                            && executionCount <= MAX_RETRIES;
                    if (!shouldRetry) {
                        throw new RetryRequestException(String.format("Not retrying %s. Count %d, Max %d",
                                currentReq.getURI(), executionCount, MAX_RETRIES));
                    }

                    LOGGER.error("Retrying request on response status {}. Count {} Max is {}", statusCode,
                            executionCount, MAX_RETRIES);
                    return true;
                }

                @Override
                public long getRetryInterval() {
                    return RETRY_INTERVAL;
                }
            });

    httpClientBuilder.setRetryHandler((exception, executionCount, context) -> {
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
        Uninterruptibles.sleepUninterruptibly(RETRY_INTERVAL, TimeUnit.MILLISECONDS);
        LOGGER.info("Encountered network error. Retrying request {},  Count {} Max is {}", currentReq.getURI(),
                executionCount, MAX_RETRIES);
        return executionCount <= MAX_RETRIES;
    });

    httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_MILLIS)
            .setConnectTimeout(TIMEOUT_MILLIS).setSocketTimeout(TIMEOUT_MILLIS).build());

    return httpClientBuilder.build();
}

From source file:leap.lang.http.client.apache.ApacheHttpClient.java

protected CloseableHttpClient initHttpClient() {
    HttpClientBuilder cb = HttpClientBuilder.create();

    //TODO : small buffer size will cause socket closed when reading response entity?
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(getDefaultRegistry());
    //cm.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(1024 * 1024).build());

    cm.setMaxTotal(maxConnectionTotal);//from  w  w w  . j a  va2 s.  c  o m
    cm.setDefaultMaxPerRoute(maxConnectionPerRoute);

    if (bufferSize > 0) {
        ConnectionConfig cc = ConnectionConfig.copy(ConnectionConfig.DEFAULT).setBufferSize(bufferSize).build();

        cm.setDefaultConnectionConfig(cc);
    }

    cb.setRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    });

    cb.setConnectionManager(cm);
    cb.setDefaultRequestConfig(requestConfig);

    return cb.build();
}

From source file:org.bonitasoft.connectors.rest.RESTConnector.java

/**
 * Execute a given request/*from  w  w w . j av  a  2 s  .c  o  m*/
 * 
 * @param request The request to execute
 * @return The response of the executed request
 * @throws Exception any exception that might occur
 */
public void execute(final Request request) throws Exception {
    CloseableHttpClient httpClient = null;

    try {
        final URL url = request.getUrl();
        final String urlHost = url.getHost();

        final Builder requestConfigurationBuilder = RequestConfig.custom();
        requestConfigurationBuilder.setConnectionRequestTimeout(CONNECTION_TIMEOUT);
        requestConfigurationBuilder.setRedirectsEnabled(request.isRedirect());

        final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
        setSSL(request.getSsl(), httpClientBuilder);
        setProxy(request.getProxy(), httpClientBuilder, requestConfigurationBuilder);
        setCookies(requestConfigurationBuilder, httpClientBuilder, request.getCookies(), urlHost);

        final RequestBuilder requestBuilder = getRequestBuilderFromMethod(request.getRestMethod());
        requestBuilder.setVersion(
                new ProtocolVersion(HTTP_PROTOCOL, HTTP_PROTOCOL_VERSION_MAJOR, HTTP_PROTOCOL_VERSION_MINOR));
        int urlPort = url.getPort();
        if (url.getPort() == -1) {
            urlPort = url.getDefaultPort();
        }
        final String urlProtocol = url.getProtocol();
        final String urlStr = url.toString();
        requestBuilder.setUri(urlStr);
        setHeaders(requestBuilder, request.getHeaders());
        if (!HTTPMethod.GET.equals(HTTPMethod.valueOf(requestBuilder.getMethod()))) {
            final String body = request.getBody();
            if (body != null) {
                requestBuilder.setEntity(new StringEntity(request.getBody(), request.getContentType()));
            }
        }

        final HttpContext httpContext = setAuthorizations(requestConfigurationBuilder,
                request.getAuthorization(), request.getProxy(), urlHost, urlPort, urlProtocol,
                httpClientBuilder);

        requestBuilder.setConfig(requestConfigurationBuilder.build());
        httpClientBuilder.setDefaultRequestConfig(requestConfigurationBuilder.build());

        final HttpUriRequest httpRequest = requestBuilder.build();
        httpClient = httpClientBuilder.build();
        final CloseableHttpResponse httpResponse = httpClient.execute(httpRequest, httpContext);
        LOGGER.fine("Request sent.");
        setOutputs(httpResponse, request);
    } finally {
        try {
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (final IOException ex) {
            logException(ex);
        }
    }
}