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

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

Introduction

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

Prototype

public final HttpClientBuilder useSystemProperties() 

Source Link

Document

Use system properties when creating and configuring default implementations.

Usage

From source file:org.yamj.core.tools.web.PoolingHttpClientBuilder.java

@SuppressWarnings("resource")
public PoolingHttpClient build() {
    // create proxy
    HttpHost proxy = null;//from  w w w  . j a  v  a 2  s.  c om
    CredentialsProvider credentialsProvider = null;

    if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) {
        proxy = new HttpHost(proxyHost, proxyPort);

        if (StringUtils.isNotBlank(proxyUsername) && StringUtils.isNotBlank(proxyPassword)) {
            if (systemProperties) {
                credentialsProvider = new SystemDefaultCredentialsProvider();
            } else {
                credentialsProvider = new BasicCredentialsProvider();
            }
            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }
    }

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
    connManager.setMaxTotal(connectionsMaxTotal);
    connManager.setDefaultMaxPerRoute(connectionsMaxPerRoute);

    HttpClientBuilder builder = HttpClientBuilder.create().setConnectionManager(connManager).setProxy(proxy)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectionTimeout)
                    .setSocketTimeout(socketTimeout).setProxy(proxy).build());

    // use system properties
    if (systemProperties) {
        builder.useSystemProperties();
    }

    // build the client
    PoolingHttpClient wrapper = new PoolingHttpClient(builder.build(), connManager);
    wrapper.addGroupLimit(".*", 1); // default limit, can be overwritten

    if (StringUtils.isNotBlank(maxDownloadSlots)) {
        LOG.debug("Using download limits: {}", maxDownloadSlots);

        Pattern pattern = Pattern.compile(",?\\s*([^=]+)=(\\d+)");
        Matcher matcher = pattern.matcher(maxDownloadSlots);
        while (matcher.find()) {
            String group = matcher.group(1);
            try {
                final Integer maxResults = Integer.valueOf(matcher.group(2));
                wrapper.addGroupLimit(group, maxResults);
                LOG.trace("Added download slot '{}' with max results {}", group, maxResults);
            } catch (NumberFormatException error) {
                LOG.debug("Rule '{}' is no valid regexp, ignored", group);
            }
        }
    }

    return wrapper;
}

From source file:org.archive.modules.recrawl.wbm.WbmPersistLoadProcessor.java

public synchronized HttpClient getHttpClient() {
    if (client == null) {
        if (conman == null) {
            conman = new PoolingHttpClientConnectionManager();
            conman.setDefaultMaxPerRoute(maxConnections);
            conman.setMaxTotal(Math.max(conman.getMaxTotal(), maxConnections));
        }/*  w w  w. j  a v a2 s.  com*/
        HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement()
                .setConnectionManager(conman);
        builder.useSystemProperties();
        // TODO: use setDefaultHeaders for adding requestHeaders? It's a bit painful
        // because we need to convert it to a Collection of Header objects.

        // config code for older version of httpclient.
        //            builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
        //            HttpParams params = client.getParams();
        //            params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
        //            params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
        // setup request/response intercepter for handling gzip-compressed response.
        // Disabled because httpclient 4.3.3 sends "Accept-Encoding: gzip,deflate" by
        // default. Response parsing will fail If gzip-decompression ResponseInterceptor
        // is installed.
        builder.addInterceptorLast(new HttpRequestInterceptor() {
            @Override
            public void process(final HttpRequest request, final HttpContext context) {
                //                    System.err.println("RequestInterceptor");
                //                    if (request.containsHeader("Accept-Encoding")) {
                //                        System.err.println("already has Accept-Encoding: " + request.getHeaders("Accept-Encoding")[0]);
                //                    }
                //                    if (gzipAccepted) {
                //                        if (!request.containsHeader("Accept-Encoding")) {
                //                            request.addHeader("Accept-Encoding", "gzip");
                //                        }
                //                    }
                // add extra headers configured.
                if (requestHeaders != null) {
                    for (Entry<String, String> ent : requestHeaders.entrySet()) {
                        request.addHeader(ent.getKey(), ent.getValue());
                    }
                }
            }
        });
        //            builder.addInterceptorFirst(new HttpResponseInterceptor() {
        //                @Override
        //                public void process(final HttpResponse response, final HttpContext context)
        //                        throws HttpException, IOException {
        //                    HttpEntity entity = response.getEntity();
        //                    Header ceheader = entity.getContentEncoding();
        //                    if (ceheader != null && contains(ceheader.getElements(), "gzip")) {
        //                        response.setEntity(new GzipInflatingHttpEntityWrapper(response.getEntity()));
        //                    }
        //                }
        //            });
        this.client = builder.build();
    }
    return client;
}

From source file:org.yamj.api.common.http.SimpleHttpClientBuilder.java

/**
 * Create the CloseableHttpClient//from   w  w  w  . jav  a 2 s  .com
 *
 * @return
 */
public CloseableHttpClient build() {
    // create proxy
    HttpHost proxy = null;
    CredentialsProvider credentialsProvider = null;

    if (isNotBlank(proxyHost) && proxyPort > 0) {
        proxy = new HttpHost(proxyHost, proxyPort);

        if (isNotBlank(proxyUsername) && isNotBlank(proxyPassword)) {
            if (systemProperties) {
                credentialsProvider = new SystemDefaultCredentialsProvider();
            } else {
                credentialsProvider = new BasicCredentialsProvider();
            }
            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }
    }

    HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(maxConnTotal)
            .setMaxConnPerRoute(maxConnPerRoute).setProxy(proxy)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout)
                    .setSocketTimeout(socketTimeout).setProxy(proxy).build());

    // use system properties
    if (systemProperties) {
        builder.useSystemProperties();
    }

    // build the http client
    return builder.build();
}

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

private CloseableHttpClient createHttpClient(ServerInfo serverInfo) {

    HttpClientBuilder builder = (useBuiltinWindowsAuthentication(serverInfo)) ? WinHttpClients.custom()
            : HttpClients.custom();//from  w  ww. j  a v  a  2 s  .c om
    HttpClientConnectionManager connMgr = createConnectionManagerIfNecessary();
    if (connMgr != null) {
        builder.setConnectionManager(connMgr);
    }
    builder.setUserAgent(userAgent);
    builder.useSystemProperties();

    return builder.build();
}

From source file:com.logsniffer.settings.http.HttpSettings.java

/**
 * Creates a {@link HttpClientBuilder} considering current settings.
 * /*from  w  w  w  .j ava 2s .  c  o  m*/
 * @return a {@link HttpClientBuilder} considering current settings.
 */
public HttpClientBuilder createHttpClientBuilder() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (getHttpProxy() != null && StringUtils.isNotBlank(getHttpProxy().getHost())) {
        httpClientBuilder = httpClientBuilder.setProxy(
                new HttpHost(getHttpProxy().getHost(), getHttpProxy().getPort(), getHttpProxy().getSchema()));
        if (StringUtils.isNotBlank(getHttpProxy().getUser())) {
            Credentials credentials = new UsernamePasswordCredentials(getHttpProxy().getUser(),
                    getHttpProxy().getPassword());
            AuthScope authScope = new AuthScope(getHttpProxy().getHost(), getHttpProxy().getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(authScope, credentials);
            httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            httpClientBuilder.useSystemProperties();
        }
    }
    return httpClientBuilder;
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java

/**
 * Create HttpClient from given host/port
 * @param request the {@link HttpRequestBase} for which an HttpClient will be created
 * @return CloseableHttpClient//from w w  w. j a v a 2s .  c om
 */
private CloseableHttpClient getHttpClient(final HttpRequestBase request) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.useSystemProperties();

    RequestConfig.Builder requestConfig = RequestConfig.custom();
    requestConfig.setConnectTimeout(10 * 1000);
    requestConfig.setConnectionRequestTimeout(60 * 1000);
    requestConfig.setSocketTimeout(60 * 1000);
    request.setConfig(requestConfig.build());

    final String host = getMethodHost(request);

    if (authenticator != null) {
        authenticator.configureBuilder(httpClientBuilder);

        context = HttpClientContext.create();
        authenticator.configureContext(context, HttpHost.create(host));
    }

    setClientProxyParams(host, httpClientBuilder);

    return httpClientBuilder.build();
}

From source file:com.helger.httpclient.HttpClientFactory.java

@Nonnull
public HttpClientBuilder createHttpClientBuilder() {
    final LayeredConnectionSocketFactory aSSLFactory = createSSLFactory();
    if (aSSLFactory == null)
        throw new IllegalStateException("Failed to create SSL SocketFactory");

    final HttpClientConnectionManager aConnMgr = createConnectionManager(aSSLFactory);
    final RequestConfig aRequestConfig = createRequestConfig();
    final HttpHost aProxyHost = getProxyHost();
    final CredentialsProvider aCredentialsProvider = createCredentialsProvider();

    final HttpClientBuilder aHCB = HttpClients.custom().setConnectionManager(aConnMgr)
            .setDefaultRequestConfig(aRequestConfig).setProxy(aProxyHost)
            .setDefaultCredentialsProvider(aCredentialsProvider);

    // Allow gzip,compress
    aHCB.addInterceptorLast(new RequestAcceptEncoding());
    // Add cookies
    aHCB.addInterceptorLast(new RequestAddCookies());
    // Un-gzip or uncompress
    aHCB.addInterceptorLast(new ResponseContentEncoding());

    // Enable usage of Java networking system properties
    if (m_bUseSystemProperties)
        aHCB.useSystemProperties();

    // Set retry handler (if needed)
    if (m_nRetries > 0)
        aHCB.setRetryHandler(createRequestRetryHandler(m_nRetries, m_eRetryMode));

    return aHCB;//from   w ww .  ja  v a 2  s  . c om
}

From source file:org.xwiki.extension.repository.http.internal.DefaultHttpClientFactory.java

@Override
public HttpClientBuilder createHttpClientBuilder(String user, String password) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // Pre-configure with everything configured at JVM level
    httpClientBuilder.useSystemProperties();

    // Setup user agent
    httpClientBuilder.setUserAgent(this.configuration.getUserAgent());

    // Setup authentication
    if (user != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }/*w ww .  jav  a2 s  . c  om*/

    return httpClientBuilder;
}