Example usage for org.apache.http.impl.client DefaultHttpRequestRetryHandler DefaultHttpRequestRetryHandler

List of usage examples for org.apache.http.impl.client DefaultHttpRequestRetryHandler DefaultHttpRequestRetryHandler

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public DefaultHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled) 

Source Link

Document

Create the request retry handler using the following list of non-retriable IOException classes:
  • InterruptedIOException
  • UnknownHostException
  • ConnectException
  • SSLException

Usage

From source file:com.arcbees.vcs.util.HttpClientWrapperImpl.java

private CloseableHttpClient initHttpClient() {
    RequestConfig requestConfig = getRequestConfig();

    String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion();

    connectionManager = new PoolingHttpClientConnectionManager();

    return HttpClientBuilder.create().useSystemProperties().addInterceptorFirst(new RequestAcceptEncoding())
            .addInterceptorFirst(new ResponseContentEncoding())
            .setRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT, true))
            .setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig)
            .setUserAgent("JetBrains TeamCity " + serverVersion).build();
}

From source file:eionet.gdem.qa.functions.Json.java

/**
 * Method converts the URL response body into XML format and returns it as String. If the response is not in JSON format, then JsonError object is converted to XML.
 * @param requestUrl Request URL to JSON format content.
 * @return String of XML/*from www  . j  a va2  s.c  o  m*/
 */
public static String jsonRequest2xmlString(String requestUrl) {
    JsonError error = null;
    String responseString = null;
    String xml = null;
    HttpGet method = null;

    // Create an instance of HttpClient.
    CloseableHttpClient client = HttpClients.custom()
            .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)).build();
    CloseableHttpResponse response = null;
    try {
        // Create a method instance.
        method = new HttpGet(requestUrl);

        // Provide custom retry handler is necessary
        //method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        // Execute the method.
        response = client.execute(method);

        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            LOGGER.error("Method failed: " + response.getStatusLine());
            error = new JsonError(statusCode, response.getStatusLine().getReasonPhrase());
        } else {
            // Read the response body.
            HttpEntity entity = response.getEntity();
            byte[] responseBody = IOUtils.toByteArray(entity.getContent());
            responseString = new String(responseBody, "UTF-8");
        }
        /*} catch (HttpException e) {
            LOGGER.error("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
            error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Fatal protocol violation.");*/
    } catch (IOException e) {
        LOGGER.error("Fatal transport error: " + e.getMessage());
        error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Fatal transport error.");
        e.printStackTrace();
    } catch (Exception e) {
        LOGGER.error("Error: " + e.getMessage());
        e.printStackTrace();
        error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error." + e.getMessage());
    } finally {
        // Release the connection.
        if (method != null) {
            method.releaseConnection();
        }
    }
    if (responseString != null) {
        xml = jsonString2xml(responseString);
    } else if (error != null) {
        xml = jsonString2xml(error);
    } else {
        xml = jsonString2xml(new JsonError());
    }
    return xml;
}

From source file:ch.ethz.dcg.pancho3.view.youtube.Query.java

private void initializeHttpClient() {
    // Initialize Http client
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT);
    httpClient = new DefaultHttpClient(params);

    HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(2, true);
    httpClient.setHttpRequestRetryHandler(retryHandler);
}

From source file:com.andrestrequest.http.HttpClientBuilder.java

/**
 * @return an HttpClient with config as specified in this builder
 *///from  w ww .j  av a 2  s.  co  m
DefaultHttpClient getHttpClient() {
    if (httpClient == null) {
        httpClient = new DefaultHttpClient();
        if (retryHandler == null) {
            retryHandler = new DefaultHttpRequestRetryHandler(0, false);
        }
        httpClient.setHttpRequestRetryHandler(retryHandler);
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
    }
    return httpClient;
}

From source file:io.undertow.testutils.TestHttpClient.java

@Override
protected HttpRequestRetryHandler createHttpRequestRetryHandler() {
    return new DefaultHttpRequestRetryHandler(0, false);
}

From source file:com.xively.client.http.HttpClientBuilder.java

/**
 * @return an HttpClient with config as specified in this builder
 *//*from ww w.ja  va  2s .  co m*/
HttpClient getHttpClient() {
    if (httpClient == null) {
        httpClient = HttpClients.custom().setRetryHandler(retryHandler).build();
        if (retryHandler == null) {
            retryHandler = new DefaultHttpRequestRetryHandler(0, false);
        }

        //httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
        //httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
    }
    return httpClient;
}

From source file:com.teradata.tempto.internal.hadoop.hdfs.HdfsModuleProvider.java

@Override
public Module getModule(Configuration configuration) {
    return new PrivateModule() {
        @Override/*  w w w  .ja va 2  s . c  om*/
        protected void configure() {
            install(httpRequestsExecutorModule());

            bind(HdfsClient.class).to(WebHdfsClient.class).in(Scopes.SINGLETON);
            bind(RevisionStorage.class).toProvider(RevisionStorageProvider.class).in(Scopes.SINGLETON);
            bind(HdfsDataSourceWriter.class).to(DefaultHdfsDataSourceWriter.class).in(Scopes.SINGLETON);

            expose(HdfsClient.class);
            expose(RevisionStorage.class);
            expose(HdfsDataSourceWriter.class);
        }

        private Module httpRequestsExecutorModule() {
            if (spnegoAuthenticationRequired()) {
                return new SpnegoHttpRequestsExecutor.Module();
            } else {
                return new SimpleHttpRequestsExecutor.Module();
            }
        }

        private boolean spnegoAuthenticationRequired() {
            Optional<String> authentication = configuration.getString("hdfs.webhdfs.authentication");
            return authentication.isPresent() && authentication.get().equalsIgnoreCase(AUTHENTICATION_SPNEGO);
        }

        @Inject
        @Provides
        @Singleton
        CloseableHttpClient createHttpClient() {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(NUMBER_OF_HTTP_RETRIES, true));
            return httpClientBuilder.build();
        }
    };
}

From source file:fi.helsinki.moodi.config.MoodleConfig.java

@Bean
public RestTemplate moodleRestTemplate() {
    return createRestTemplate(new DefaultHttpRequestRetryHandler(RETRY_COUNT, false));
}

From source file:org.frontcache.agent.FrontCacheAgent.java

public FrontCacheAgent(String frontcacheURL) {
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(3000)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
        @Override// ww w. j av  a2s  .  c  o m
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return 10 * 1000;
        }
    };

    client = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .setKeepAliveStrategy(keepAliveStrategy).setRedirectStrategy(new RedirectStrategy() {
                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                @Override
                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            }).build();

    this.frontCacheURL = frontcacheURL;

    if (frontcacheURL.endsWith("/"))
        this.frontCacheURI = frontcacheURL + IO_URI;
    else
        this.frontCacheURI = frontcacheURL + "/" + IO_URI;
}