Example usage for org.apache.http.conn.socket PlainConnectionSocketFactory PlainConnectionSocketFactory

List of usage examples for org.apache.http.conn.socket PlainConnectionSocketFactory PlainConnectionSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.socket PlainConnectionSocketFactory PlainConnectionSocketFactory.

Prototype

public PlainConnectionSocketFactory() 

Source Link

Usage

From source file:com.arangodb.http.HttpManager.java

public void init() {
    // socket factory for HTTP
    ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory();

    // socket factory for HTTPS
    SSLConnectionSocketFactory sslsf = null;
    if (configure.getSslContext() != null) {
        sslsf = new SSLConnectionSocketFactory(configure.getSslContext());
    } else {/*  ww  w .  jav a2 s .  c o  m*/
        sslsf = new SSLConnectionSocketFactory(SSLContexts.createSystemDefault());
    }

    // register socket factories
    Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainsf).register("https", sslsf).build();

    // ConnectionManager
    cm = new PoolingHttpClientConnectionManager(r);
    cm.setDefaultMaxPerRoute(configure.getMaxPerConnection());
    cm.setMaxTotal(configure.getMaxTotalConnection());

    Builder custom = RequestConfig.custom();

    // RequestConfig
    if (configure.getConnectionTimeout() >= 0) {
        custom.setConnectTimeout(configure.getConnectionTimeout());
    }
    if (configure.getTimeout() >= 0) {
        custom.setConnectionRequestTimeout(configure.getTimeout());
        custom.setSocketTimeout(configure.getTimeout());
    }
    custom.setStaleConnectionCheckEnabled(configure.isStaleConnectionCheck());

    RequestConfig requestConfig = custom.build();

    HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig);
    builder.setConnectionManager(cm);

    // KeepAlive Strategy
    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {

        @Override
        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) {
                    }
                }
            }
            // otherwise keep alive for 30 seconds
            return 30 * 1000;
        }

    };
    builder.setKeepAliveStrategy(keepAliveStrategy);

    // Retry Handler
    builder.setRetryHandler(new DefaultHttpRequestRetryHandler(configure.getRetryCount(), false));

    // Proxy
    if (configure.getProxyHost() != null && configure.getProxyPort() != 0) {
        HttpHost proxy = new HttpHost(configure.getProxyHost(), configure.getProxyPort(), "http");

        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        builder.setRoutePlanner(routePlanner);
    }

    // Client
    client = builder.build();

    // Basic Auth
    // if (configure.getUser() != null && configure.getPassword() != null) {
    // AuthScope scope = AuthScope.ANY; // TODO
    // this.credentials = new
    // UsernamePasswordCredentials(configure.getUser(),
    // configure.getPassword());
    // client.getCredentialsProvider().setCredentials(scope, credentials);
    // }

}

From source file:com.arvato.thoroughly.util.RestTemplateUtil.java

@PostConstruct
private RestTemplate initializationTemplate() {
    ConnectionConfig connConfig = ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build();
    SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(100000).build();
    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
            .<ConnectionSocketFactory>create();
    ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
    registryBuilder.register("http", plainSF);

    registryBuilder.register("https", setUpSSL());

    Registry<ConnectionSocketFactory> registry = registryBuilder.build();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
    connManager.setDefaultConnectionConfig(connConfig);
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setMaxTotal(1000);/*  ww  w  .  j a  v  a 2s. c  o m*/
    connManager.setDefaultMaxPerRoute(1000);
    HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();

    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    clientHttpRequestFactory.setConnectTimeout(30000);
    clientHttpRequestFactory.setReadTimeout(30000);
    clientHttpRequestFactory.setConnectionRequestTimeout(30000);

    restTemplate = new RestTemplate();
    restTemplate.setRequestFactory(clientHttpRequestFactory);
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler());

    reInitMessageConverter(restTemplate);

    return restTemplate;
}

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

protected HttpConnectionPoolBuilder(final Host host, final X509TrustManager trust, final X509KeyManager key,
        final ProxyFinder proxy, final SocketFactory socketFactory) {
    this(host, new PlainConnectionSocketFactory() {
        @Override/*ww  w.j  av  a2s . c  o  m*/
        public Socket createSocket(final HttpContext context) throws IOException {
            return socketFactory.createSocket();
        }
    }, new SSLConnectionSocketFactory(new CustomTrustSSLProtocolSocketFactory(trust, key),
            new DisabledX509HostnameVerifier()) {
        @Override
        public Socket createSocket(final HttpContext context) throws IOException {
            return socketFactory.createSocket();
        }

        @Override
        public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
                final InetSocketAddress remoteAddress, final InetSocketAddress localAddress,
                final HttpContext context) throws IOException {
            if (trust instanceof ThreadLocalHostnameDelegatingTrustManager) {
                ((ThreadLocalHostnameDelegatingTrustManager) trust).setTarget(remoteAddress.getHostName());
            }
            return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
        }
    }, proxy);
}

From source file:net.yacy.grid.http.ClientConnection.java

public static PoolingHttpClientConnectionManager getConnctionManager() {

    Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
    try {//w  w w.jav a  2  s .  com
        SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
                new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                new TrustAllHostNameVerifier());
        socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory())
                .register("https", trustSelfSignedSocketFactory).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        Data.logger.warn("", e);
    }

    PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null)
            ? new PoolingHttpClientConnectionManager(socketFactoryRegistry)
            : new PoolingHttpClientConnectionManager();

    // twitter specific options
    cm.setMaxTotal(2000);
    cm.setDefaultMaxPerRoute(200);

    return cm;
}

From source file:microsoft.exchange.webservices.data.ExchangeServiceBase.java

/**
 * Initializes a new instance./*  w  w  w. jav  a2 s.co m*/
 *
 * @param requestedServerVersion The requested server version.
 */
protected ExchangeServiceBase() {
    //real init -- ONLY WAY TO BUILD AN OBJECT => each constructor must call this() to build properly the httpConnectionManager
    this.timeZone = TimeZone.getDefault();
    this.setUseDefaultCredentials(true);

    try {
        EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(null);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory()).register("https", factory).build();
        this.httpConnectionManager = new PoolingHttpClientConnectionManager(registry);
    } catch (Exception err) {
        err.printStackTrace();
    }
}

From source file:org.kuali.rice.ksb.messaging.serviceconnectors.DefaultHttpClientConfigurer.java

/**
 * Builds the HttpClientConnectionManager.
 *
 * <p>Note that this calls {@link #buildSslConnectionSocketFactory()} and registers the resulting {@link SSLConnectionSocketFactory}
 * (if non-null) with its socket factory registry.</p>
 *
 * @return the HttpClientConnectionManager
 *//*ww w  .  ja  v  a 2  s .  co m*/
protected HttpClientConnectionManager buildConnectionManager() {
    PoolingHttpClientConnectionManager poolingConnectionManager = null;

    SSLConnectionSocketFactory sslConnectionSocketFactory = buildSslConnectionSocketFactory();
    if (sslConnectionSocketFactory != null) {
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", sslConnectionSocketFactory)
                .register("http", new PlainConnectionSocketFactory()).build();
        poolingConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    } else {
        poolingConnectionManager = new PoolingHttpClientConnectionManager();
    }

    // Configure the connection manager
    poolingConnectionManager
            .setMaxTotal(MAX_TOTAL_CONNECTIONS.getValueOrDefault(DEFAULT_MAX_TOTAL_CONNECTIONS));

    // By default we'll set the max connections per route (essentially that means per host for us) to the max total
    poolingConnectionManager
            .setDefaultMaxPerRoute(MAX_TOTAL_CONNECTIONS.getValueOrDefault(DEFAULT_MAX_TOTAL_CONNECTIONS));

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoTimeout(SO_TIMEOUT.getValueOrDefault(DEFAULT_SOCKET_TIMEOUT));

    Integer soLinger = SO_LINGER.getValue();
    if (soLinger != null) {
        socketConfigBuilder.setSoLinger(soLinger);
    }

    Boolean isTcpNoDelay = TCP_NODELAY.getValue();
    if (isTcpNoDelay != null) {
        socketConfigBuilder.setTcpNoDelay(isTcpNoDelay);
    }

    poolingConnectionManager.setDefaultSocketConfig(socketConfigBuilder.build());

    ConnectionConfig.Builder connectionConfigBuilder = ConnectionConfig.custom();

    Integer sendBuffer = SO_SNDBUF.getValue();
    Integer receiveBuffer = SO_RCVBUF.getValue();

    // if either send or recieve buffer size is set, we'll set the buffer size to whichever is greater
    if (sendBuffer != null || receiveBuffer != null) {
        Integer bufferSize = -1;
        if (sendBuffer != null) {
            bufferSize = sendBuffer;
        }

        if (receiveBuffer != null && receiveBuffer > bufferSize) {
            bufferSize = receiveBuffer;
        }

        connectionConfigBuilder.setBufferSize(bufferSize);
    }

    String contentCharset = HTTP_CONTENT_CHARSET.getValue();
    if (contentCharset != null) {
        connectionConfigBuilder.setCharset(Charset.forName(contentCharset));
    }

    poolingConnectionManager.setDefaultConnectionConfig(connectionConfigBuilder.build());

    return poolingConnectionManager;
}

From source file:ai.susi.server.ClientConnection.java

private static PoolingHttpClientConnectionManager getConnctionManager(boolean useAuthentication) {

    // allow opportunistic encryption if needed

    boolean trustAllCerts = !"none".equals(DAO.getConfig("httpsclient.trustselfsignedcerts", "peers"))
            && (!useAuthentication || "all".equals(DAO.getConfig("httpsclient.trustselfsignedcerts", "peers")));

    Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
    if (trustAllCerts) {
        try {/*from  www  .j  a v  a 2s  .c o m*/
            SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
                    new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    new TrustAllHostNameVerifier());
            socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", trustSelfSignedSocketFactory).build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            Log.getLog().warn(e);
        }
    }

    PoolingHttpClientConnectionManager cm = (trustAllCerts && socketFactoryRegistry != null)
            ? new PoolingHttpClientConnectionManager(socketFactoryRegistry)
            : new PoolingHttpClientConnectionManager();

    // twitter specific options
    cm.setMaxTotal(200);
    cm.setDefaultMaxPerRoute(20);
    HttpHost twitter = new HttpHost("twitter.com", 443);
    cm.setMaxPerRoute(new HttpRoute(twitter), 50);

    return cm;
}

From source file:microsoft.exchange.webservices.data.core.ExchangeServiceBase.java

/**
 * Create registry with configured {@link ConnectionSocketFactory} instances.
 * Override this method to change how to work with different schemas.
 *
 * @return registry object//ww  w . j a v  a  2s. co m
 */
protected Registry<ConnectionSocketFactory> createConnectionSocketFactoryRegistry() {
    try {
        return RegistryBuilder.<ConnectionSocketFactory>create()
                .register(EWSConstants.HTTP_SCHEME, new PlainConnectionSocketFactory())
                .register(EWSConstants.HTTPS_SCHEME, EwsSSLProtocolSocketFactory.build(null)).build();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(
                "Could not initialize ConnectionSocketFactory instances for HttpClientConnectionManager", e);
    }
}

From source file:org.drugis.addis.config.MainConfig.java

@Bean
public HttpClient httpClient(RequestConfig requestConfig) throws KeyStoreException, IOException,
        CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(KEYSTORE_PATH), KEYSTORE_PASSWORD.toCharArray());
    String ADDIS_LOCAL = System.getenv("ADDIS_LOCAL");

    SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadKeyMaterial(keyStore,
            KEYSTORE_PASSWORD.toCharArray());
    if (ADDIS_LOCAL != null) {
        String TRUSTSTORE_PATH = WebConstants.loadSystemEnv("TRUSTSTORE_PATH");
        sslContextBuilder.loadTrustMaterial(new File(TRUSTSTORE_PATH));
    }//w  ww .ja  v  a2  s. c o m
    sslContextBuilder.build();
    SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build());

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", connectionSocketFactory).register("http", new PlainConnectionSocketFactory())
            .build();
    HttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(registry);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    return httpClientBuilder.setConnectionManager(clientConnectionManager).setMaxConnTotal(20)
            .setMaxConnPerRoute(2).setDefaultRequestConfig(requestConfig).build();
}