Example usage for org.apache.http.config SocketConfig custom

List of usage examples for org.apache.http.config SocketConfig custom

Introduction

In this page you can find the example usage for org.apache.http.config SocketConfig custom.

Prototype

public static Builder custom() 

Source Link

Usage

From source file:org.iipg.hurricane.jmx.client.JMXClientBuilder.java

private SocketConfig createSocketConfig() {
    SocketConfig.Builder socketConfigB = SocketConfig.custom();
    if (socketTimeout >= 0) {
        socketConfigB.setSoTimeout(socketTimeout);
    }//from   w w w  . j  a va  2 s . co m
    socketConfigB.setTcpNoDelay(tcpNoDelay);
    return socketConfigB.build();
}

From source file:org.callimachusproject.webdriver.helpers.BrowserFunctionalTestCase.java

private void recordTest(String jobId, String data, int retry) {
    String remotewebdriver = System.getProperty("org.callimachusproject.test.remotewebdriver");
    if (remotewebdriver != null && remotewebdriver.contains("saucelabs.com")) {
        URI uri = URI.create(remotewebdriver);
        CloseableHttpClient client = HttpClientBuilder.create().useSystemProperties()
                .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(5000).build()).build();
        try {//from  w  w  w  .  ja  v  a 2s  . com
            try {
                String info = uri.getUserInfo();
                putTestData(info, jobId, data, client);
            } finally {
                client.close();
            }
        } catch (IOException ex) {
            if (retry > 0) {
                logger.warn(ex.toString(), ex);
                recordTest(jobId, data, retry - 1);
            } else {
                logger.error(ex.toString(), ex);
            }
        } catch (RuntimeException ex) {
            logger.error(ex.toString(), ex);
        }
    }
}

From source file:com.ibm.og.client.ApacheClient.java

private SocketConfig createSocketConfig() {
    return SocketConfig.custom().setSoTimeout(this.soTimeout).setSoReuseAddress(this.soReuseAddress)
            .setSoLinger(this.soLinger).setSoKeepAlive(this.soKeepAlive).setTcpNoDelay(this.tcpNoDelay)
            .setSndBufSize(this.soSndBuf).setRcvBufSize(this.soRcvBuf).build();
}

From source file:com.tremolosecurity.proxy.filter.PostProcess.java

public CloseableHttpClient getHttp(String finalURL, HttpServletRequest request, ConfigManager cfgMgr) {
    HttpSession session = request.getSession();
    PoolingHttpClientConnectionManager phcm = (PoolingHttpClientConnectionManager) session
            .getAttribute("TREMOLO_HTTP_POOL");
    CloseableHttpClient http = (CloseableHttpClient) session.getAttribute("TREMOLO_HTTP_CLIENT");
    if (http == null) {
        //create a new connection manager and client
        phcm = new PoolingHttpClientConnectionManager(cfgMgr.getHttpClientSocketRegistry());
        BigInteger num = cfgMgr.getCfg().getThreadsPerRoute();
        if (num == null) {
            phcm.setDefaultMaxPerRoute(6);
        } else {//w ww. j  a v  a  2s. c  o m
            phcm.setDefaultMaxPerRoute(num.intValue());
        }
        phcm.setDefaultSocketConfig(SocketConfig.custom().setSoKeepAlive(true).build());
        http = HttpClients.custom().setConnectionManager(phcm)
                .setDefaultRequestConfig(cfgMgr.getGlobalHttpClientConfig()).build();

        session.setAttribute("TREMOLO_HTTP_POOL", phcm);
        session.setAttribute("TREMOLO_HTTP_CLIENT", http);

        LogoutUtil.insertFirstLogoutHandler(request, new CloseHttpConnectionsOnLogout(http, phcm));

    }

    return http;
}

From source file:com.nominanuda.web.http.HttpCoreHelper.java

public HttpClient createClient(int maxConnPerRoute, long connTimeoutMillis, long soTimeoutMillis,
        @Nullable String proxyHostAnPort) {
    Registry<ConnectionSocketFactory> defaultRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(defaultRegistry);
    connMgr.setDefaultMaxPerRoute(maxConnPerRoute);
    SocketConfig sCfg = SocketConfig.custom().setSoTimeout((int) soTimeoutMillis)
            .setSoTimeout((int) connTimeoutMillis).build();
    connMgr.setDefaultSocketConfig(sCfg);
    HttpClientBuilder hcb = HttpClientBuilder.create();
    hcb.setDefaultSocketConfig(sCfg).setConnectionManager(connMgr);
    if (proxyHostAnPort == null) {
    } else if ("jvm".equalsIgnoreCase(proxyHostAnPort)) {
        SystemDefaultRoutePlanner rp = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
        hcb.setRoutePlanner(rp);//w  w  w.  j a  v  a  2s.  c om
    } else {
        String[] hostAndPort = proxyHostAnPort.split(":");
        Check.illegalargument.assertTrue(hostAndPort.length < 3, "wrong hostAndPort:" + proxyHostAnPort);
        String host = hostAndPort[0];
        int port = 80;
        if (hostAndPort.length > 1) {
            port = Integer.valueOf(hostAndPort[1]);
        }
        HttpHost proxy = new HttpHost(host, port);
        hcb.setProxy(proxy);
    }
    HttpClient httpClient = hcb.build();
    return httpClient;
}

From source file:com.xebialabs.overthere.winrm.WinRmClient.java

private void configureHttpClient(final HttpClientBuilder httpclient) throws GeneralSecurityException {
    configureTrust(httpclient);/*from  w  ww.  ja  v  a 2 s  .  c  o  m*/
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    httpclient.setDefaultCredentialsProvider(credentialsProvider);

    configureAuthentication(credentialsProvider, BASIC, new BasicUserPrincipal(username));

    if (enableKerberos) {
        String spnServiceClass = kerberosUseHttpSpn ? "HTTP" : "WSMAN";
        RegistryBuilder<AuthSchemeProvider> authSchemeRegistryBuilder = RegistryBuilder.create();
        authSchemeRegistryBuilder.register(KERBEROS, new WsmanKerberosSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        authSchemeRegistryBuilder.register(SPNEGO, new WsmanSPNegoSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        httpclient.setDefaultAuthSchemeRegistry(authSchemeRegistryBuilder.build());
        configureAuthentication(credentialsProvider, KERBEROS, new KerberosPrincipal(username));
        configureAuthentication(credentialsProvider, SPNEGO, new KerberosPrincipal(username));
    }

    httpclient.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build());
    httpclient.setDefaultRequestConfig(
            RequestConfig.custom().setAuthenticationEnabled(true).setConnectTimeout(connectionTimeout).build());
}

From source file:com.wudaosoft.net.httpclient.Request.java

protected void init() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
        CertificateException, IOException {

    Args.notNull(hostConfig, "Host config");

    SSLConnectionSocketFactory sslConnectionSocketFactory = null;

    if (sslcontext == null) {

        if (hostConfig.getCA() != null) {
            // Trust root CA and all self-signed certs
            SSLContext sslcontext1 = SSLContexts.custom().loadTrustMaterial(hostConfig.getCA(),
                    hostConfig.getCAPassword(), TrustSelfSignedStrategy.INSTANCE).build();

            // Allow TLSv1 protocol only
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1, new String[] { "TLSv1" },
                    null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        } else {//from  w w w  . ja v  a2  s  . c o  m

            if (isTrustAll) {

                SSLContext sslcontext1 = SSLContext.getInstance("TLS");

                TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                            throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                            throws CertificateException {
                    }

                } };

                sslcontext1.init(null, trustAllCerts, null);

                sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1,
                        NoopHostnameVerifier.INSTANCE);
            } else {
                sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
            }
        }
    } else {

        sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    }

    if (keepAliveStrategy == null) {
        keepAliveStrategy = new ConnectionKeepAliveStrategy() {

            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                // Honor 'keep-alive' header
                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")) {
                        try {
                            return Long.parseLong(value) * 1000;
                        } catch (NumberFormatException ignore) {
                        }
                    }
                }
                // HttpHost target = (HttpHost)
                // context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
                // if
                // ("xxxxx".equalsIgnoreCase(target.getHostName()))
                // {
                // // Keep alive for 5 seconds only
                // return 3 * 1000;
                // } else {
                // // otherwise keep alive for 30 seconds
                // return 30 * 1000;
                // }

                return 30 * 1000;
            }

        };
    }

    if (retryHandler == null) {
        retryHandler = new HttpRequestRetryHandler() {

            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount >= 3) {
                    // 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;
            }
        };
    }

    connManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory).build());

    if (hostConfig.getHost() != null) {

        connManager.setMaxTotal(hostConfig.getPoolSize() + 60);

        connManager.setMaxPerRoute(
                new HttpRoute(hostConfig.getHost(), null,
                        !HttpHost.DEFAULT_SCHEME_NAME.equals(hostConfig.getHost().getSchemeName())),
                hostConfig.getPoolSize());

        connManager.setDefaultMaxPerRoute(20);
    } else {
        connManager.setMaxTotal(hostConfig.getPoolSize());
        int hostCount = hostConfig.getHostCount() == 0 ? 10 : hostConfig.getHostCount();
        connManager.setDefaultMaxPerRoute(hostConfig.getPoolSize() / hostCount);
    }

    // connManager.setValidateAfterInactivity(2000);

    // Create socket configuration
    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(isKeepAlive).build();
    connManager.setDefaultSocketConfig(socketConfig);

    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .setCharset(hostConfig.getCharset() == null ? Consts.UTF_8 : hostConfig.getCharset()).build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    new IdleConnectionMonitorThread(connManager).start();

    if (requestInterceptor == null) {
        requestInterceptor = new SortHeadersInterceptor(hostConfig);
    }

    if (!hostConfig.isMulticlient()) {
        defaultHttpContext = HttpClientContext.create();
        httpClient = create();
    }
}

From source file:com.petalmd.armor.AbstractUnitTest.java

protected final HeaderAwareJestHttpClient getJestClient(final String serverUri, final String username,
        final String password) throws Exception {// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();

    final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build();

    // Construct a new Jest client according to configuration via factory
    final HeaderAwareJestClientFactory factory1 = new HeaderAwareJestClientFactory();

    factory1.setHttpClientConfig(clientConfig1);

    final HeaderAwareJestHttpClient c = factory1.getObject();

    final HttpClientBuilder hcb = HttpClients.custom();

    if (username != null) {
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(username, password));
    }/*  w w w  . j  ava2  s .c o  m*/

    if (useSpnego) {
        //SPNEGO/Kerberos setup
        log.debug("SPNEGO activated");
        final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true, false);//  new NegotiateSchemeProvider();
        final Credentials jaasCreds = new JaasCredentials();
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM),
                new NTCredentials("Guest", "Guest", "Guest", "Guest"));
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();

        hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    }

    hcb.setDefaultCredentialsProvider(credsProvider);

    if (serverUri.startsWith("https")) {
        log.debug("Configure Jest with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorTS.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorKS.jks")),
                "changeit".toCharArray());

        final SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadKeyMaterial(keyStore, "changeit".toCharArray()).loadTrustMaterial(myTrustStore).build();

        String[] protocols = null;

        if (enableSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = SecurityUtil.ENABLED_SSL_PROTOCOLS;
        }

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

        hcb.setSSLSocketFactory(sslsf);

    }

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

    final CloseableHttpClient httpClient = hcb.build();

    c.setHttpClient(httpClient);
    return c;

}

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

private SocketConfig.Builder createSocketConfigBuilder(final int timeout) {
    final SocketConfig.Builder socketBuilder = SocketConfig.custom()
            // timeout
            .setSoTimeout(timeout);//from ww  w .j  a  v a 2s  .co m
    return socketBuilder;
}