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:de.codecentric.elasticsearch.plugin.kerberosrealm.AbstractUnitTest.java

protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception {

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final HttpClientBuilder hcb = HttpClients.custom();

    if (useSpnego) {
        //SPNEGO/Kerberos setup
        log.debug("SPNEGO activated");
        final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);//  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);
    }/*  w ww . jav  a 2  s  . com*/

    hcb.setDefaultCredentialsProvider(credsProvider);
    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build());
    final CloseableHttpClient httpClient = hcb.build();
    return httpClient;
}

From source file:es.auth.plugin.AbstractUnitTest.java

protected final JestHttpClient getJestClient(final String serverUri, final String username,
        final String password) throws Exception {
    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 JestClientFactory factory1 = new JestClientFactory();
    factory1.setHttpClientConfig(clientConfig1);
    final JestHttpClient c = factory1.getObject();
    final HttpClientBuilder hcb = HttpClients.custom();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
    hcb.setDefaultCredentialsProvider(credsProvider);
    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());
    final CloseableHttpClient httpClient = hcb.build();
    c.setHttpClient(httpClient);/*from  ww w  .j  a va 2 s .  c om*/
    return c;
}

From source file:com.floragunn.searchguard.ssl.AbstractUnitTest.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(getAbsoluteFilePathFromClassPath("truststore.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("node-0-keystore.jks")),
                "changeit".toCharArray());

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

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }/* ww  w  .  j  ava  2 s . c om*/

        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();
}

From source file:org.apache.manifoldcf.meridio.MeridioWrapper.java

/** The Meridio Wrapper constructor that calls the Meridio login method
*
*@param log                                     a handle to a Log4j logger
*@param meridioDmwsUrl          the URL to the Meridio Document Management Web Service
*@param meridioRmwsUrl          the URL to the Meridio Records Management Web Service
*@param dmwsProxyHost           the proxy for DMWS, or null if none
*@param dmwsProxyPort           the proxy port for DMWS, or -1 if default
*@param rmwsProxyHost           the proxy for RMWS, or null if none
*@param rmwsProxyPort           the proxy port for RMWS, or -1 if default
*@param userName                        the username of the user to log in as, must include the Windows, e.g. domain\\user
*@param password                        the password of the user who is logging in
*@param clientWorkstation       an identifier for the client workstation, could be the IP address, for auditing purposes
*@param protocolFactory         the protocol factory object to use for https communication
*@param engineConfigurationFile the engine configuration object to use to communicate with the web services
*
*@throws RemoteException        if an error is encountered logging into Meridio
*///w  w  w.ja  v  a  2s . c o m
public MeridioWrapper(Logger log, URL meridioDmwsUrl, URL meridioRmwsUrl, URL meridioManifoldCFWSUrl,
        String dmwsProxyHost, String dmwsProxyPort, String rmwsProxyHost, String rmwsProxyPort,
        String mcwsProxyHost, String mcwsProxyPort, String userName, String password, String clientWorkstation,
        javax.net.ssl.SSLSocketFactory mySSLFactory, Class resourceClass, String engineConfigurationFile)
        throws RemoteException, NumberFormatException {
    // Initialize local instance variables
    oLog = log;
    this.engineConfiguration = new ResourceProvider(resourceClass, engineConfigurationFile);
    this.clientWorkstation = clientWorkstation;

    SSLConnectionSocketFactory myFactory = null;
    if (mySSLFactory != null) {
        myFactory = new SSLConnectionSocketFactory(mySSLFactory, new BrowserCompatHostnameVerifier());
    }

    // Set up the pool.
    // We have a choice: We can either have one httpclient instance, which gets reinitialized for every service
    // it connects with (because each one has a potentially different proxy setup), OR we can have a different
    // httpclient for each service.  The latter approach is obviously the more efficient, so I've chosen to do it
    // that way.

    // Parse the user and password values
    int index = userName.indexOf("\\");
    String domainUser;
    String domain;
    if (index != -1) {
        domainUser = userName.substring(index + 1);
        domain = userName.substring(0, index);
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "', domain is '" + domain + "'");
    } else {
        domain = null;
        domainUser = userName;
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "'; there is no domain specified");
    }

    if (oLog != null && oLog.isDebugEnabled()) {
        if (password != null && password.length() > 0)
            oLog.debug("Meridio: Password exists");
        else
            oLog.debug("Meridio: Password is null");
    }

    int socketTimeout = 900000;
    int connectionTimeout = 300000;

    dmwsConnectionManager = new PoolingHttpClientConnectionManager();
    rmwsConnectionManager = new PoolingHttpClientConnectionManager();
    mcwsConnectionManager = new PoolingHttpClientConnectionManager();

    // Initialize the three httpclient objects

    CredentialsProvider dmwsCredentialsProvider = new BasicCredentialsProvider();
    CredentialsProvider rmwsCredentialsProvider = new BasicCredentialsProvider();

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

    // Set up credentials
    if (domainUser != null) {
        dmwsCredentialsProvider.setCredentials(
                new AuthScope(meridioDmwsUrl.getHost(), meridioDmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
        rmwsCredentialsProvider.setCredentials(
                new AuthScope(meridioRmwsUrl.getHost(), meridioRmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
    }

    // Initialize DMWS proxy
    if (dmwsProxyHost != null && dmwsProxyHost.length() > 0) {
        int port = (dmwsProxyPort == null || dmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(dmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            dmwsCredentialsProvider.setCredentials(new AuthScope(dmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(dmwsProxyHost, port);
        dmwsRequestBuilder.setProxy(proxy);
    }

    // Initialize RMWS proxy
    if (rmwsProxyHost != null && rmwsProxyHost.length() > 0) {
        int port = (rmwsProxyPort == null || rmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(rmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            rmwsCredentialsProvider.setCredentials(new AuthScope(rmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(rmwsProxyHost, port);
        rmwsRequestBuilder.setProxy(proxy);
    }

    dmwsHttpClient = HttpClients.custom().setConnectionManager(dmwsConnectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(dmwsRequestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(dmwsCredentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();

    rmwsHttpClient = HttpClients.custom().setConnectionManager(rmwsConnectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(rmwsRequestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(rmwsCredentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();

    if (meridioManifoldCFWSUrl != null) {
        CredentialsProvider mcwsCredentialsProvider = new BasicCredentialsProvider();

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

        if (domainUser != null) {
            mcwsCredentialsProvider.setCredentials(
                    new AuthScope(meridioManifoldCFWSUrl.getHost(), meridioManifoldCFWSUrl.getPort()),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        // Initialize MCWS proxy
        if (mcwsProxyHost != null && mcwsProxyHost.length() > 0) {
            int port = (mcwsProxyPort == null || mcwsProxyPort.length() == 0) ? 8080
                    : Integer.parseInt(mcwsProxyPort);
            // Configure proxy authentication
            if (domainUser != null && domainUser.length() > 0) {
                mcwsCredentialsProvider.setCredentials(new AuthScope(mcwsProxyHost, port),
                        new NTCredentials(domainUser, password, currentHost, domain));
            }

            HttpHost proxy = new HttpHost(mcwsProxyHost, port);
            mcwsRequestBuilder.setProxy(proxy);
        }

        mcwsHttpClient = HttpClients.custom().setConnectionManager(mcwsConnectionManager).setMaxConnTotal(1)
                .disableAutomaticRetries().setDefaultRequestConfig(mcwsRequestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(mcwsCredentialsProvider).setSSLSocketFactory(myFactory)
                .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy()).build();
    }

    // Set up the stub handles
    /*=================================================================
    * Get a handle to the DMWS
    *================================================================*/
    MeridioDMLocator meridioDMLocator = new MeridioDMLocator(engineConfiguration);
    MeridioDMSoapStub meridioDMWebService = new MeridioDMSoapStub(meridioDmwsUrl, meridioDMLocator);

    meridioDMWebService.setPortName(meridioDMLocator.getMeridioDMSoapWSDDServiceName());
    meridioDMWebService.setUsername(userName);
    meridioDMWebService.setPassword(password);
    meridioDMWebService._setProperty(HTTPCLIENT_PROPERTY, dmwsHttpClient);

    meridioDMWebService_ = meridioDMWebService;

    /*=================================================================
    * Get a handle to the RMWS
    *================================================================*/
    MeridioRMLocator meridioRMLocator = new MeridioRMLocator(engineConfiguration);
    MeridioRMSoapStub meridioRMWebService = new MeridioRMSoapStub(meridioRmwsUrl, meridioRMLocator);

    meridioRMWebService.setPortName(meridioRMLocator.getMeridioRMSoapWSDDServiceName());
    meridioRMWebService.setUsername(userName);
    meridioRMWebService.setPassword(password);
    meridioRMWebService._setProperty(HTTPCLIENT_PROPERTY, rmwsHttpClient);

    meridioRMWebService_ = meridioRMWebService;

    /*=================================================================
    * Get a handle to the MeridioMetaCarta Web Service
    *================================================================*/
    if (meridioManifoldCFWSUrl != null) {
        MetaCartaLocator meridioMCWS = new MetaCartaLocator(engineConfiguration);
        Service McWsService = null;
        MetaCartaSoapStub meridioMetaCartaWebService = new MetaCartaSoapStub(meridioManifoldCFWSUrl,
                McWsService);

        meridioMetaCartaWebService.setPortName(meridioMCWS.getMetaCartaSoapWSDDServiceName());
        meridioMetaCartaWebService.setUsername(userName);
        meridioMetaCartaWebService.setPassword(password);
        meridioMetaCartaWebService._setProperty(HTTPCLIENT_PROPERTY, mcwsHttpClient);

        meridioMCWS_ = meridioMetaCartaWebService;
    }

    this.loginUnified();
}

From source file:org.apache.manifoldcf.crawler.connectors.wiki.WikiConnector.java

protected void getSession() throws ManifoldCFException, ServiceInterruption {
    if (hasBeenSetup == false) {
        String emailAddress = params.getParameter(WikiConfig.PARAM_EMAIL);
        if (emailAddress != null)
            userAgent = "Mozilla/5.0 (ApacheManifoldCFWikiReader; "
                    + ((emailAddress == null) ? "" : emailAddress) + ")";
        else//from  ww w.j  av  a2s  .  c o m
            userAgent = null;

        String protocol = params.getParameter(WikiConfig.PARAM_PROTOCOL);
        if (protocol == null || protocol.length() == 0)
            protocol = "http";
        String portString = params.getParameter(WikiConfig.PARAM_PORT);
        if (portString == null || portString.length() == 0)
            portString = null;
        String path = params.getParameter(WikiConfig.PARAM_PATH);
        if (path == null)
            path = "/w";

        baseURL = protocol + "://" + server + ((portString != null) ? ":" + portString : "") + path
                + "/api.php?format=xml&";

        int socketTimeout = 900000;
        int connectionTimeout = 300000;

        javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory
                .getTrustingSecureSocketFactory();
        SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
                new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        // Set up connection manager
        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        if (accessUser != null && accessUser.length() > 0 && accessPassword != null) {
            Credentials credentials = new UsernamePasswordCredentials(accessUser, accessPassword);
            if (accessRealm != null && accessRealm.length() > 0)
                credentialsProvider.setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, accessRealm), credentials);
            else
                credentialsProvider.setCredentials(AuthScope.ANY, credentials);
        }

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

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

            int proxyPortInt;
            if (proxyPort != null && proxyPort.length() > 0) {
                try {
                    proxyPortInt = Integer.parseInt(proxyPort);
                } catch (NumberFormatException e) {
                    throw new ManifoldCFException("Bad number: " + e.getMessage(), e);
                }
            } else
                proxyPortInt = 8080;

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

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

            HttpHost proxy = new HttpHost(proxyHost, proxyPortInt);
            requestBuilder.setProxy(proxy);
        }

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

        /*
        BasicHttpParams params = new BasicHttpParams();
        params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,true);
        params.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE,socketTimeout);
        params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,true);
        params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,true);
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,socketTimeout);
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,connectionTimeout);
        params.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,true);
        DefaultHttpClient localHttpClient = new DefaultHttpClient(connectionManager,params);
        // No retries
        localHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler()
          {
            public boolean retryRequest(
              IOException exception,
              int executionCount,
              HttpContext context)
            {
              return false;
            }
                 
          });
        */

        loginToAPI();

        hasBeenSetup = true;
    }
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

/**
 * Returns the URL for the passed in String. If the URL requires authentication, then the WSDL
 * is saved as a temp file and the URL for that file is returned.
 * /*from w w  w .  j a va2 s .  com*/
 * @param wsdlUrl
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private URL getWsdlUrl(DispatchContainer dispatchContainer) throws Exception {
    URI uri = new URI(dispatchContainer.getCurrentWsdlUrl());

    // If the URL points to file, just return it
    if (!uri.getScheme().equalsIgnoreCase("file")) {
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        CloseableHttpClient client = clientBuilder.build();

        try {
            clients.add(client);
            HttpClientContext context = HttpClientContext.create();

            if (dispatchContainer.getCurrentUsername() != null
                    && dispatchContainer.getCurrentPassword() != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,
                        AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(
                        dispatchContainer.getCurrentUsername(), dispatchContainer.getCurrentPassword());
                credsProvider.setCredentials(authScope, credentials);
                AuthCache authCache = new BasicAuthCache();
                RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder
                        .<AuthSchemeProvider>create();
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());

                context.setCredentialsProvider(credsProvider);
                context.setAuthSchemeRegistry(registryBuilder.build());
                context.setAuthCache(authCache);
            }

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setSocketTimeout(timeout).setStaleConnectionCheckEnabled(true).build();
            context.setRequestConfig(requestConfig);

            return getWsdl(client, context, dispatchContainer, new HashMap<String, File>(),
                    dispatchContainer.getCurrentWsdlUrl()).toURI().toURL();
        } finally {
            HttpClientUtils.closeQuietly(client);
            clients.remove(client);
        }
    }

    return uri.toURL();
}

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Create connection manager for http client.
 *
 * @return The connection manager for http client.
 *//*from w ww .j  av a2s.  c om*/
private HttpClientConnectionManager createHttpClientConnectionManager() {
    ConnectionSocketFactory socketFactory = PlainConnectionSocketFactory.getSocketFactory();
    LayeredConnectionSocketFactory sslSocketFactory;
    try {
        sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
    } catch (NoSuchAlgorithmException e) {
        throw new BceClientException("Fail to create SSLConnectionSocketFactory", e);
    }
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(Protocol.HTTP.toString(), socketFactory)
            .register(Protocol.HTTPS.toString(), sslSocketFactory).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setDefaultMaxPerRoute(this.config.getMaxConnections());
    connectionManager.setDefaultSocketConfig(SocketConfig.custom()
            .setSoTimeout(this.config.getSocketTimeoutInMillis()).setTcpNoDelay(true).build());
    connectionManager.setMaxTotal(this.config.getMaxConnections());
    return connectionManager;
}

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.apache.manifoldcf.crawler.connectors.sharepoint.SharePointRepository.java

/** Set up a session */
protected void getSession() throws ManifoldCFException {
    if (proxy == null) {
        String serverVersion = params.getParameter(SharePointConfig.PARAM_SERVERVERSION);
        if (serverVersion == null)
            serverVersion = "4.0";
        supportsItemSecurity = !serverVersion.equals("2.0");
        dspStsWorks = serverVersion.equals("2.0") || serverVersion.equals("3.0");
        attachmentsSupported = !serverVersion.equals("2.0");

        String authorityType = params.getParameter(SharePointConfig.PARAM_AUTHORITYTYPE);
        if (authorityType == null)
            authorityType = "ActiveDirectory";

        activeDirectoryAuthority = authorityType.equals("ActiveDirectory");

        serverProtocol = params.getParameter(SharePointConfig.PARAM_SERVERPROTOCOL);
        if (serverProtocol == null)
            serverProtocol = "http";
        try {/*  ww  w. j  a  v  a 2s  .  c  o m*/
            String serverPort = params.getParameter(SharePointConfig.PARAM_SERVERPORT);
            if (serverPort == null || serverPort.length() == 0) {
                if (serverProtocol.equals("https"))
                    this.serverPort = 443;
                else
                    this.serverPort = 80;
            } else
                this.serverPort = Integer.parseInt(serverPort);
        } catch (NumberFormatException e) {
            throw new ManifoldCFException(e.getMessage(), e);
        }
        serverLocation = params.getParameter(SharePointConfig.PARAM_SERVERLOCATION);
        if (serverLocation == null)
            serverLocation = "";
        if (serverLocation.endsWith("/"))
            serverLocation = serverLocation.substring(0, serverLocation.length() - 1);
        if (serverLocation.length() > 0 && !serverLocation.startsWith("/"))
            serverLocation = "/" + serverLocation;
        encodedServerLocation = serverLocation;
        serverLocation = decodePath(serverLocation);

        userName = params.getParameter(SharePointConfig.PARAM_SERVERUSERNAME);
        password = params.getObfuscatedParameter(SharePointConfig.PARAM_SERVERPASSWORD);
        int index = userName.indexOf("\\");
        if (index != -1) {
            strippedUserName = userName.substring(index + 1);
            ntlmDomain = userName.substring(0, index);
        } else {
            strippedUserName = null;
            ntlmDomain = null;
        }

        String proxyHost = params.getParameter(SharePointConfig.PARAM_PROXYHOST);
        String proxyPortString = params.getParameter(SharePointConfig.PARAM_PROXYPORT);
        int proxyPort = 8080;
        if (proxyPortString != null && proxyPortString.length() > 0) {
            try {
                proxyPort = Integer.parseInt(proxyPortString);
            } catch (NumberFormatException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
        String proxyUsername = params.getParameter(SharePointConfig.PARAM_PROXYUSER);
        String proxyPassword = params.getParameter(SharePointConfig.PARAM_PROXYPASSWORD);
        String proxyDomain = params.getParameter(SharePointConfig.PARAM_PROXYDOMAIN);

        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;

        // Set up ssl if indicated
        keystoreData = params.getParameter(SharePointConfig.PARAM_SERVERKEYSTORE);

        int connectionTimeout = 60000;
        int socketTimeout = 900000;

        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, userName, password,
                org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd",
                httpClient);

    }
    sessionTimeout = System.currentTimeMillis() + sessionExpirationInterval;
}

From source file:com.floragunn.searchguard.AbstractUnitTest.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(getAbsoluteFilePathFromClassPath("truststore.jks")),
                "changeit".toCharArray());

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

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

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }// w w w .j  ava  2 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();
}