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

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

Introduction

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

Prototype

public static Builder custom() 

Source Link

Usage

From source file:com.github.lpezet.antiope.dao.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient(APIConfiguration pConfiguration) {

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory(
            new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory());

    SSLContext oSslContext = null;
    X509HostnameVerifier oHostnameVerifier = null;
    if (pConfiguration.isCheckSSLCertificates()) {
        oSslContext = SSLContexts.createSystemDefault();
        oHostnameVerifier = new BrowserCompatHostnameVerifier();
    } else {//  ww w. j a va2  s  .  c o m
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        // Install the all-trusting trust manager
        try {
            final SSLContext sslContext = SSLContext.getInstance(SSL);
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            //final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            oSslContext = sslContext;
        } catch (NoSuchAlgorithmException e) {
            throw new APIClientException(e);
        } catch (KeyManagementException e) {
            throw new APIClientException(e);
        }
        oHostnameVerifier = new AllowAllHostnameVerifier();
    }

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HTTP, PlainConnectionSocketFactory.INSTANCE)
            .register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver oDnsResolver = new SystemDefaultDnsResolver(); /* {
                                                               @Override
                                                               public InetAddress[] resolve(final String host) throws UnknownHostException {
                                                               if (host.equalsIgnoreCase("myhost")) {
                                                               return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
                                                               } else {
                                                               return super.resolve(host);
                                                               }
                                                               }
                                                               };*/

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager(
            oSocketFactoryRegistry, oConnFactory, oDnsResolver);

    // Create socket configuration
    SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true)
            .setSoTimeout(pConfiguration.getSocketTimeout()).build();

    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    oConnManager.setDefaultSocketConfig(oSocketConfig);
    // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig);

    // Create message constraints
    MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig oConnectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(oMessageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    oConnManager.setDefaultConnectionConfig(oConnectionConfig);
    // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    oConnManager.setMaxTotal(100);
    oConnManager.setDefaultMaxPerRoute(10);
    //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore oCookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    //
    // Create global request configuration
    RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            //.setExpectContinueEnabled(true)         // WARNING: setting it to true slows things down by 4s!!!!
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setConnectTimeout(pConfiguration.getConnectionTimeout()).build();

    CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider();
    HttpHost oProxy = null;

    if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) {
        String proxyHost = pConfiguration.getProxyHost();
        int proxyPort = pConfiguration.getProxyPort();
        String proxyUsername = pConfiguration.getProxyUsername();
        String proxyPassword = pConfiguration.getProxyPassword();
        String proxyDomain = pConfiguration.getProxyDomain();
        String proxyWorkstation = pConfiguration.getProxyWorkstation();

        oProxy = new HttpHost(proxyHost, proxyPort);

        if (proxyUsername != null && proxyPassword != null) {
            oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager)
            .setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider)
            .setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build();

    return oHttpClient;
    /*
    RequestConfig oRequestConfig = RequestConfig.custom()
    .setConnectTimeout(pConfiguration.getConnectionTimeout())
    .setSocketTimeout(pConfiguration.getSocketTimeout())
    .setStaleConnectionCheckEnabled(true)
    .build();
    */
}

From source file:com.okta.sdk.impl.http.httpclient.HttpClientRequestExecutor.java

/**
 * Creates a new {@code HttpClientRequestExecutor} using the specified {@code ClientCredentials} and optional {@code Proxy}
 * configuration./* www .  ja  v a  2 s .c o m*/
 * @param clientCredentials the Okta account API Key that will be used to authenticate the client with Okta's API sever
 * @param proxy the HTTP proxy to be used when communicating with the Okta API server (can be null)
 * @param authenticationScheme the HTTP authentication scheme to be used when communicating with the Okta API server.
 *                             If null, then SSWS will be used.
 */
public HttpClientRequestExecutor(ClientCredentials clientCredentials, Proxy proxy,
        AuthenticationScheme authenticationScheme, RequestAuthenticatorFactory requestAuthenticatorFactory,
        Integer connectionTimeout) {
    Assert.notNull(clientCredentials, "clientCredentials argument is required.");
    Assert.isTrue(connectionTimeout >= 0, "Timeout cannot be a negative number.");

    RequestAuthenticatorFactory factory = (requestAuthenticatorFactory != null) ? requestAuthenticatorFactory
            : new DefaultRequestAuthenticatorFactory();

    this.requestAuthenticator = factory.create(authenticationScheme, clientCredentials);

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();

    if (MAX_CONNECTIONS_TOTAL >= MAX_CONNECTIONS_PER_ROUTE) {
        connMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(MAX_CONNECTIONS_TOTAL);
    } else {
        connMgr.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(DEFAULT_MAX_CONNECTIONS_TOTAL);

        log.warn(
                "{} ({}) is less than {} ({}). "
                        + "Reverting to defaults: connectionMaxTotal ({}) and connectionMaxPerRoute ({}).",
                MAX_CONNECTIONS_TOTAL_PROPERTY_KEY, MAX_CONNECTIONS_TOTAL,
                MAX_CONNECTIONS_PER_ROUTE_PROPERTY_KEY, MAX_CONNECTIONS_PER_ROUTE,
                DEFAULT_MAX_CONNECTIONS_TOTAL, DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
    }

    // The connectionTimeout value is specified in seconds in Okta configuration settings.
    // Therefore, multiply it by 1000 to be milliseconds since RequestConfig expects milliseconds.
    int connectionTimeoutAsMilliseconds = connectionTimeout * 1000;

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeoutAsMilliseconds)
            .setSocketTimeout(connectionTimeoutAsMilliseconds).setRedirectsEnabled(false).build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .disableCookieManagement().setDefaultConnectionConfig(connectionConfig)
            .setConnectionManager(connMgr);

    this.httpClientRequestFactory = new HttpClientRequestFactory(requestConfig);

    if (proxy != null) {
        //We have some proxy setting to use!
        HttpHost httpProxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        httpClientBuilder.setProxy(httpProxyHost);

        if (proxy.isAuthenticationRequired()) {
            AuthScope authScope = new AuthScope(proxy.getHost(), proxy.getPort());
            Credentials credentials = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword());
            CredentialsProvider credentialsProviderProvider = new BasicCredentialsProvider();
            credentialsProviderProvider.setCredentials(authScope, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProviderProvider);
        }
    }

    this.httpClient = httpClientBuilder.build();
}

From source file:com.stormpath.sdk.impl.http.httpclient.HttpClientRequestExecutor.java

/**
 * Creates a new {@code HttpClientRequestExecutor} using the specified {@code ApiKey} and optional {@code Proxy}
 * configuration./*from  ww  w  . ja v a 2s  . c o  m*/
 * @param clientCredentials the Stormpath account API Key that will be used to authenticate the client with Stormpath's API sever
 * @param proxy the HTTP proxy to be used when communicating with the Stormpath API server (can be null)
 * @param authenticationScheme the HTTP authentication scheme to be used when communicating with the Stormpath API server.
 *                             If null, then Sauthc1 will be used.
 */
public HttpClientRequestExecutor(ClientCredentials clientCredentials, Proxy proxy,
        AuthenticationScheme authenticationScheme, RequestAuthenticatorFactory requestAuthenticatorFactory,
        Integer connectionTimeout) {
    Assert.notNull(clientCredentials, "clientCredentials argument is required.");
    Assert.isTrue(connectionTimeout >= 0, "Timeout cannot be a negative number.");

    RequestAuthenticatorFactory factory = (requestAuthenticatorFactory != null) ? requestAuthenticatorFactory
            : new DefaultRequestAuthenticatorFactory();

    this.requestAuthenticator = factory.create(authenticationScheme, clientCredentials);

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();

    if (MAX_CONNECTIONS_TOTAL >= MAX_CONNECTIONS_PER_ROUTE) {
        connMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(MAX_CONNECTIONS_TOTAL);
    } else {
        connMgr.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(DEFAULT_MAX_CONNECTIONS_TOTAL);

        log.warn(
                "{} ({}) is less than {} ({}). "
                        + "Reverting to defaults: connectionMaxTotal ({}) and connectionMaxPerRoute ({}).",
                MAX_CONNECTIONS_TOTAL_PROPERTY_KEY, MAX_CONNECTIONS_TOTAL,
                MAX_CONNECTIONS_PER_ROUTE_PROPERTY_KEY, MAX_CONNECTIONS_PER_ROUTE,
                DEFAULT_MAX_CONNECTIONS_TOTAL, DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
    }

    // The connectionTimeout value is specified in seconds in Stormpath configuration settings.
    // Therefore, multiply it by 1000 to be milliseconds since RequestConfig expects milliseconds.
    int connectionTimeoutAsMilliseconds = connectionTimeout * 1000;

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeoutAsMilliseconds)
            .setSocketTimeout(connectionTimeoutAsMilliseconds).setRedirectsEnabled(false).build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .disableCookieManagement().setDefaultConnectionConfig(connectionConfig)
            .setConnectionManager(connMgr);

    this.httpClientRequestFactory = new HttpClientRequestFactory(requestConfig);

    if (proxy != null) {
        //We have some proxy setting to use!
        HttpHost httpProxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        httpClientBuilder.setProxy(httpProxyHost);

        if (proxy.isAuthenticationRequired()) {
            AuthScope authScope = new AuthScope(proxy.getHost(), proxy.getPort());
            Credentials credentials = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword());
            CredentialsProvider credentialsProviderProvider = new BasicCredentialsProvider();
            credentialsProviderProvider.setCredentials(authScope, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProviderProvider);
        }
    }

    this.httpClient = httpClientBuilder.build();
}

From source file:ch.cyberduck.core.http.HttpConnectionPoolBuilder.java

public HttpClientBuilder build(final TranscriptListener listener) {
    // Use HTTP Connect proxy implementation provided here instead of
    // relying on internal proxy support in socket factory
    final Proxy proxy = proxyFinder.find(host);
    if (proxy.getType() == Proxy.Type.HTTP) {
        final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.http.name());
        if (log.isInfoEnabled()) {
            log.info(String.format("Setup proxy %s", h));
        }/*from  w  w  w .  j a  v  a  2s.  com*/
        builder.setProxy(h);
    }
    if (proxy.getType() == Proxy.Type.HTTPS) {
        final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.https.name());
        if (log.isInfoEnabled()) {
            log.info(String.format("Setup proxy %s", h));
        }
        builder.setProxy(h);
    }
    builder.setUserAgent(new PreferencesUseragentProvider().get());
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(timeout).build());
    builder.setDefaultRequestConfig(RequestConfig.custom().setRedirectsEnabled(true)
            // Disable use of Expect: Continue by default for all methods
            .setExpectContinueEnabled(false).setAuthenticationEnabled(true).setConnectTimeout(timeout)
            // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager
            .setConnectionRequestTimeout(preferences.getInteger("http.manager.timeout"))
            .setSocketTimeout(timeout).build());
    final String encoding;
    if (null == host.getEncoding()) {
        encoding = preferences.getProperty("browser.charset.encoding");
    } else {
        encoding = host.getEncoding();
    }
    builder.setDefaultConnectionConfig(
            ConnectionConfig.custom().setBufferSize(preferences.getInteger("http.socket.buffer"))
                    .setCharset(Charset.forName(encoding)).build());
    if (preferences.getBoolean("http.connections.reuse")) {
        builder.setConnectionReuseStrategy(new DefaultConnectionReuseStrategy());
    } else {
        builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    }
    builder.setRetryHandler(
            new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry")));
    if (!preferences.getBoolean("http.compression.enable")) {
        builder.disableContentCompression();
    }
    builder.setRequestExecutor(new LoggingHttpRequestExecutor(listener));
    // Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the
    // default port and the socket factory to be used to create the java.net.Socket instances for the given protocol
    builder.setConnectionManager(this.pool(this.registry().build()));
    builder.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC,
                    new BasicSchemeFactory(
                            Charset.forName(preferences.getProperty("http.credentials.charset"))))
            .register(AuthSchemes.DIGEST,
                    new DigestSchemeFactory(
                            Charset.forName(preferences.getProperty("http.credentials.charset"))))
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build());
    return builder;
}

From source file:com.joyent.manta.http.MantaConnectionFactory.java

/**
 * Builds and configures a {@link ConnectionConfig} instance.
 *
 * @return fully configured instance/*from w  w  w  . j av  a  2 s. c o  m*/
 */
protected ConnectionConfig buildConnectionConfig() {
    final int bufferSize = ObjectUtils.firstNonNull(config.getHttpBufferSize(),
            DefaultsConfigContext.DEFAULT_HTTP_BUFFER_SIZE);

    return ConnectionConfig.custom().setBufferSize(bufferSize).build();
}

From source file:org.callimachusproject.client.HttpClientFactory.java

private ConnectionConfig getDefaultConnectionConfig() {
    return ConnectionConfig.custom().setBufferSize(8 * 1024).build();
}

From source file:com.northernwall.hadrian.Main.java

private void startHttpClient() {
    try {//from  w  ww  .  j av  a 2  s  . c o  m
        int maxConnections = Integer.parseInt(properties.getProperty("http.maxConnections", "100"));
        int maxPerRoute = Integer.parseInt(properties.getProperty("http.maxPerRoute", "10"));
        int socketTimeout = Integer.parseInt(properties.getProperty("http.socketTimeout", "1000"));
        int connectionTimeout = Integer.parseInt(properties.getProperty("http.connectionTimeout", "1000"));

        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
                .<ConnectionSocketFactory>create();
        Registry<ConnectionSocketFactory> registry = registryBuilder
                .register("http", PlainConnectionSocketFactory.INSTANCE).build();

        PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(registry);
        ccm.setMaxTotal(maxConnections);
        ccm.setDefaultMaxPerRoute(maxPerRoute);

        HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(ccm)
                .setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Consts.UTF_8).build())
                .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(socketTimeout)
                        .setConnectTimeout(connectionTimeout).build());
        client = clientBuilder.build();
    } catch (NumberFormatException nfe) {
        throw new IllegalStateException("Error Creating HTTPClient, could not parse property");
    } catch (Exception e) {
        throw new IllegalStateException("Error Creating HTTPClient: ", e);
    }
}

From source file:org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduitFactory.java

public synchronized void setupNIOClient(HTTPClientPolicy clientPolicy) throws IOReactorException {
    if (client != null) {
        return;/* w ww  .  jav a 2s  .  c o  m*/
    }

    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(ioThreadCount)
            .setSelectInterval(selectInterval).setInterestOpQueued(interestOpQueued).setSoLinger(soLinger)
            .setSoTimeout(soTimeout).setSoKeepAlive(soKeepalive).setTcpNoDelay(tcpNoDelay).build();

    Registry<SchemeIOSessionStrategy> ioSessionFactoryRegistry = RegistryBuilder
            .<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE)
            .register("https", SSLIOSessionStrategy.getSystemDefaultStrategy()).build();

    ManagedNHttpClientConnectionFactory connectionFactory = new ManagedNHttpClientConnectionFactory() {

        @Override
        public ManagedNHttpClientConnection create(final IOSession iosession, final ConnectionConfig config) {
            ManagedNHttpClientConnection conn = super.create(iosession, config);
            return conn;
        }
    };

    DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(config);
    connectionManager = new PoolingNHttpClientConnectionManager(ioreactor, connectionFactory,
            ioSessionFactoryRegistry, DefaultSchemePortResolver.INSTANCE, SystemDefaultDnsResolver.INSTANCE,
            connectionTTL, TimeUnit.MILLISECONDS);

    connectionManager.setDefaultMaxPerRoute(maxPerRoute);
    connectionManager.setMaxTotal(maxConnections);

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setBufferSize(clientPolicy.getChunkLength() > 0 ? clientPolicy.getChunkLength() : 16332).build();

    connectionManager.setDefaultConnectionConfig(connectionConfig);

    RedirectStrategy redirectStrategy = new RedirectStrategy() {

        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            return false;
        }

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

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom()
            .setConnectionManager(connectionManager).setRedirectStrategy(redirectStrategy)
            .setDefaultCookieStore(new BasicCookieStore() {
                private static final long serialVersionUID = 1L;

                public void addCookie(Cookie cookie) {
                }
            });

    adaptClientBuilder(httpAsyncClientBuilder);

    client = httpAsyncClientBuilder.build();
    // Start the client thread
    client.start();
    if (this.connectionTTL == 0) {
        //if the connection does not have an expiry deadline
        //use the ConnectionMaxIdle to close the idle connection
        new CloseIdleConnectionThread(connectionManager, client).start();
    }
}

From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java

protected ConnectionConfig createConnectionConfig() {
    if (StringUtils.isNotBlank(proxyUsername)) {
        return ConnectionConfig.custom().setCharset(Consts.UTF_8).build();
    }// w  w w. j a  v  a2  s  .c  o  m
    return null;
}