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

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

Introduction

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

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointAuthority.java

protected void getSharePointSession() throws ManifoldCFException {
    if (proxy == null) {
        // Set up server URL
        try {//from  w  ww.  j  a  va2 s.c  o m
            if (serverPortString == null || serverPortString.length() == 0) {
                if (serverProtocol.equals("https"))
                    this.serverPort = 443;
                else
                    this.serverPort = 80;
            } else
                this.serverPort = Integer.parseInt(serverPortString);
        } catch (NumberFormatException e) {
            throw new ManifoldCFException(e.getMessage(), e);
        }

        int proxyPort = 8080;
        if (proxyPortString != null && proxyPortString.length() > 0) {
            try {
                proxyPort = Integer.parseInt(proxyPortString);
            } catch (NumberFormatException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }

        serverUrl = serverProtocol + "://" + serverName;
        if (serverProtocol.equals("https")) {
            if (serverPort != 443)
                serverUrl += ":" + Integer.toString(serverPort);
        } else {
            if (serverPort != 80)
                serverUrl += ":" + Integer.toString(serverPort);
        }

        fileBaseUrl = serverUrl + encodedServerLocation;

        int connectionTimeout = 60000;
        int socketTimeout = 900000;

        // Set up ssl if indicated

        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        SSLConnectionSocketFactory myFactory = null;
        if (keystoreData != null) {
            keystoreManager = KeystoreManagerFactory.make("", keystoreData);
            myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(),
                    new BrowserCompatHostnameVerifier());
        }

        if (strippedUserName != null) {
            credentialsProvider.setCredentials(new AuthScope(serverName, serverPort),
                    new NTCredentials(strippedUserName, password, currentHost, ntlmDomain));
        }

        RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        // If there's a proxy, set that too.
        if (proxyHost != null && proxyHost.length() > 0) {

            // Configure proxy authentication
            if (proxyUsername != null && proxyUsername.length() > 0) {
                if (proxyPassword == null)
                    proxyPassword = "";
                if (proxyDomain == null)
                    proxyDomain = "";

                credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
            }

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);

            requestBuilder.setProxy(proxy);
        }

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(credentialsProvider);
        if (myFactory != null)
            builder.setSSLSocketFactory(myFactory);
        builder.setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy());
        httpClient = builder.build();

        proxy = new SPSProxyHelper(serverUrl, encodedServerLocation, serverLocation, serverUserName, password,
                org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd",
                httpClient, isClaimSpace);

    }
    sharepointSessionTimeout = System.currentTimeMillis() + SharePointExpirationInterval;
}

From source file:org.kaaproject.kaa.server.appenders.rest.appender.RestLogAppender.java

@Override
protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) {
    this.configuration = configuration;
    this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize());
    target = new HttpHost(configuration.getHost(), configuration.getPort(),
            configuration.getSsl() ? "https" : "http");
    HttpClientBuilder builder = HttpClients.custom();
    if (configuration.getUsername() != null && configuration.getPassword() != null) {
        LOG.info("Adding basic auth credentials provider");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }//from  w w w .j av  a2 s .  c  om
    if (!configuration.getVerifySslCert()) {
        LOG.info("Adding trustful ssl context");
        SSLContextBuilder sslBuilder = new SSLContextBuilder();
        try {
            sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build());
            builder.setSSLSocketFactory(sslsf);
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
            LOG.error("Failed to init socket factory {}", ex.getMessage(), ex);
        }
    }
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize());
    cm.setMaxTotal(configuration.getConnectionPoolSize());
    builder.setConnectionManager(cm);
    this.client = builder.build();
}

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   ww w . jav a 2 s  .co m
 */
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:org.bimserver.client.AbstractBimServerClientFactory.java

public void initHttpClient() {
    HttpClientBuilder builder = HttpClientBuilder.create();

    HttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    builder.setConnectionManager(connManager);

    //      builder.addInterceptorFirst(new HttpRequestInterceptor() {
    //         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    //            if (!request.containsHeader("Accept-Encoding")) {
    //               request.addHeader("Accept-Encoding", "gzip");
    //            }
    //         }//from   w  w w. j av  a2s.  co m
    //      });
    //
    //      builder.addInterceptorFirst(new HttpResponseInterceptor() {
    //         public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
    //            HttpEntity entity = response.getEntity();
    //            if (entity != null) {
    //               Header ceheader = entity.getContentEncoding();
    //               if (ceheader != null) {
    //                  HeaderElement[] codecs = ceheader.getElements();
    //                  for (int i = 0; i < codecs.length; i++) {
    //                     if (codecs[i].getName().equalsIgnoreCase("gzip")) {
    //                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
    //                        return;
    //                     }
    //                  }
    //               }
    //            }
    //         }
    //      });

    httpClient = builder.build();
}

From source file:org.piwigo.remotesync.api.client.WSClient.java

protected CloseableHttpClient getHttpClient() throws Exception {
    if (httpClient == null) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        if (clientConfiguration.getUsesProxy()) {
            String proxyUrl = clientConfiguration.getProxyUrl();
            int proxyPort = clientConfiguration.getProxyPort();

            String proxyUsername = clientConfiguration.getProxyUsername();
            String proxyPassword = clientConfiguration.getProxyPassword();

            if (proxyUsername != null && proxyUsername.length() > 0 && proxyPassword != null
                    && proxyPassword.length() > 0) {
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(proxyUrl, proxyPort),
                        new UsernamePasswordCredentials(proxyUsername, proxyPassword));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }/*w  w  w. j ava  2  s .c o  m*/

            HttpHost proxy = new HttpHost(proxyUrl, proxyPort);
            requestConfig = RequestConfig.custom().setProxy(proxy).build();
        }

        if (clientConfiguration.getTrustSSLCertificates()) {
            SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
            sslContextBuilder.loadTrustMaterial(null, new TrustSSLCertificatesStrategy());
            httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContextBuilder.build()));
        }

        httpClient = httpClientBuilder.build();
    }

    return httpClient;
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2.I2B2XMLResourceImplementation.java

/**
 * CREATES A CLIENT/*from w ww .  ja v  a2 s . co  m*/
 * 
 * @param token
 * @return
 */
protected HttpClient createClient(SecureSession session) {
    // SSL WRAPAROUND
    HttpClientBuilder returns = null;

    if (ignoreCertificate) {
        try {
            // CLIENT CONNECTION
            returns = ignoreCertificate();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
    } else {
        returns = HttpClientBuilder.create();
    }

    List<Header> defaultHeaders = new ArrayList<Header>();

    String token = session.getToken().toString();
    if (this.clientId != null) {
        token = SecurityUtility.delegateToken(this.namespace, this.clientId, session);
    }

    if (session != null) {
        defaultHeaders.add(new BasicHeader("Authorization", token));
    }
    defaultHeaders.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
    returns.setDefaultHeaders(defaultHeaders);

    return returns.build();
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

/**
 * {@inheritDoc}//  ww w  .ja va  2s .  c  o m
 */
@Override
public WebResponse getResponse(final WebRequest request) throws IOException {
    final URL url = request.getUrl();
    final HttpClientBuilder builder = reconfigureHttpClientIfNeeded(getHttpClientBuilder());

    if (connectionManager_ == null) {
        connectionManager_ = createConnectionManager(builder);
    }
    builder.setConnectionManager(connectionManager_);

    HttpUriRequest httpMethod = null;
    try {
        try {
            httpMethod = makeHttpMethod(request, builder);
        } catch (final URISyntaxException e) {
            throw new IOException("Unable to create URI from URL: " + url.toExternalForm() + " (reason: "
                    + e.getMessage() + ")", e);
        }
        final HttpHost hostConfiguration = getHostConfiguration(request);
        final long startTime = System.currentTimeMillis();

        HttpResponse httpResponse = null;
        try {
            httpResponse = builder.build().execute(hostConfiguration, httpMethod, httpContext_);
        } catch (final SSLPeerUnverifiedException s) {
            // Try to use only SSLv3 instead
            if (webClient_.getOptions().isUseInsecureSSL()) {
                HtmlUnitSSLConnectionSocketFactory.setUseSSL3Only(httpContext_, true);
                httpResponse = builder.build().execute(hostConfiguration, httpMethod, httpContext_);
            } else {
                throw s;
            }
        } catch (final Error e) {
            // in case a StackOverflowError occurs while the connection is leased, it won't get released.
            // Calling code may catch the StackOverflowError, but due to the leak, the httpClient_ may
            // come out of connections and throw a ConnectionPoolTimeoutException.
            // => best solution, discard the HttpClient instance.
            httpClientBuilder_.set(null);
            throw e;
        }

        final DownloadedContent downloadedBody = downloadResponseBody(httpResponse);
        final long endTime = System.currentTimeMillis();
        return makeWebResponse(httpResponse, request, downloadedBody, endTime - startTime);
    } finally {
        if (httpMethod != null) {
            onResponseGenerated(httpMethod);
        }
    }
}

From source file:com.floragunn.searchguard.test.helper.rest.RestHelper.java

protected final CloseableHttpClient getHTTPClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHTTPClientSSL) {

        log.debug("Configure HTTP client with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(truststore)),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(keystore)),
                "changeit".toCharArray());

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }//from www. j a va2 s .co m

        if (sendHTTPClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHTTPClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    return hcb.build();
}