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

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

Introduction

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

Prototype

public static PlainConnectionSocketFactory getSocketFactory() 

Source Link

Usage

From source file:io.wcm.caravan.commons.httpclient.impl.HttpClientItem.java

private static PoolingHttpClientConnectionManager buildConnectionManager(HttpClientConfig config,
        SSLContext sslContext) {/*from w  w  w . j  a v  a  2s . c om*/
    // scheme configuration
    ConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
    Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // pooling settings
    PoolingHttpClientConnectionManager conmgr = new PoolingHttpClientConnectionManager(schemeRegistry);
    conmgr.setMaxTotal(config.getMaxTotalConnections());
    conmgr.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    return conmgr;
}

From source file:info.bonjean.beluga.connection.BelugaHTTPClient.java

private BelugaHTTPClient() {
    BelugaConfiguration configuration = BelugaConfiguration.getInstance();
    HttpClientBuilder clientBuilder = HttpClients.custom();

    // timeout// ww  w . j  a  v  a2s .  c  om
    RequestConfig config = RequestConfig.custom().setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT)
            .setConnectionRequestTimeout(TIMEOUT).build();
    clientBuilder.setDefaultRequestConfig(config);

    switch (configuration.getConnectionType()) {
    case PROXY_DNS:
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
        BelugaDNSResolver dnsOverrider = new BelugaDNSResolver(DNSProxy.PROXY_DNS);
        connectionManager = new PoolingHttpClientConnectionManager(registry, dnsOverrider);
        break;
    case HTTP_PROXY:
        HttpHost proxy = new HttpHost(configuration.getProxyHost(), configuration.getProxyPort(), "http");
        clientBuilder.setProxy(proxy);
        break;
    default:
    }

    // limit the pool size
    connectionManager.setDefaultMaxPerRoute(2);

    // add interceptor, currently for debugging only
    clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
            HttpInetConnection connection = (HttpInetConnection) context
                    .getAttribute(HttpCoreContext.HTTP_CONNECTION);
            log.debug("Remote address: " + connection.getRemoteAddress());
            // TODO: reimplement blacklisting for DNS proxy by maintaining a
            // map [DNS IP,RESOLVED IP] in the DNS resolver for reverse
            // lookup
        }
    });

    // finally create the HTTP client
    clientBuilder.setConnectionManager(connectionManager);
    httpClient = clientBuilder.build();
}

From source file:org.talend.dataprep.configuration.HttpClient.java

/**
 * @return the http connection manager.//from   w  w  w . j  a v  a  2s.c o m
 */
@Bean(destroyMethod = "shutdown")
public PoolingHttpClientConnectionManager getConnectionManager() {

    // fallback to default implementation
    if (sslSocketFactory == null) {
        sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
    }

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

    connectionManager.setMaxTotal(maxPoolSize);
    connectionManager.setDefaultMaxPerRoute(maxPerRoute);
    return connectionManager;
}

From source file:com.vmware.bdd.cli.http.HttpClientProvider.java

@Bean(name = SECURE_HTTP_CLIENT)
@Qualifier(SECURE_HTTP_CLIENT)/*ww w  .  j av a 2s  .c  om*/
public HttpClient secureHttpClient()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContext sslContext = SSLContexts.custom().useTLS().build();

    sslContext.init(null, new TrustManager[] { trustManager }, null);

    String[] supportedProtocols = cliProperties.getSupportedProtocols();
    String[] supportedCipherSuites = cliProperties.getSupportedCipherSuites();
    String hostnameVerifier = cliProperties.getHostnameVerifier();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("supported protocols: " + ArrayUtils.toString(supportedProtocols));
        LOGGER.debug("supported cipher suites: " + ArrayUtils.toString(supportedCipherSuites));
        LOGGER.debug("hostname verifier: " + hostnameVerifier);
    }

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols,
            supportedCipherSuites, getHostnameVerifier(hostnameVerifier));

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", socketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    cm.setMaxTotal(20);
    cm.setDefaultMaxPerRoute(10);
    //      HttpHost proxy = new HttpHost("127.0.0.1", 8810, "http");
    //      HttpClient  client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).setProxy(proxy).build();

    HttpClient client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    return client1;
}

From source file:com.questdb.test.tools.HttpTestUtils.java

private static HttpClientBuilder createHttpClient_AcceptsUntrustedCerts() throws Exception {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    ///*  w  w w.  ja v  a2 s.  c o  m*/
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();

    b.setSSLContext(sslContext);

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    b.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));

    return b;
}

From source file:sachin.spider.WebSpider.java

/**
 *
 * @param config//from  www .  j  a  v a2  s. co  m
 * @param latch
 */
@SuppressWarnings("deprecation")
public void setValues(SpiderConfig config, CountDownLatch latch) {
    try {
        this.config = config;
        this.latch = latch;
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setUserAgent(config.getUserAgentString());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws java.security.cert.CertificateException {
                return true;
            }
        }).build();
        builder.setSslcontext(sslContext);
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setDefaultMaxPerRoute(config.getTotalSpiders() * 2);
        cm.setMaxTotal(config.getTotalSpiders() * 2);
        if (config.isAuthenticate()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
            httpclient = HttpClients.custom().setUserAgent(config.getUserAgentString())
                    .setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(cm).build();

        } else {
            httpclient = HttpClients.custom().setConnectionManager(cm).setUserAgent(config.getUserAgentString())
                    .build();
        }
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:io.cloudslang.content.httpclient.build.conn.ConnectionManagerBuilder.java

public PoolingHttpClientConnectionManager buildConnectionManager() {
    if (connectionPoolHolder != null) {
        PoolingHttpClientConnectionManager connManager = null;
        synchronized (connectionPoolHolder) {
            Map<String, PoolingHttpClientConnectionManager> connectionManagerMap = connectionPoolHolder.get();

            if (connectionManagerMap == null) {
                final HashMap<String, PoolingHttpClientConnectionManager> connectionManagerMapFinal = new HashMap<>();
                connectionPoolHolder//from   ww  w . ja va 2  s.  com
                        .setResource(new SessionResource<Map<String, PoolingHttpClientConnectionManager>>() {
                            @Override
                            public Map<String, PoolingHttpClientConnectionManager> get() {
                                return connectionManagerMapFinal;
                            }

                            @Override
                            public void release() {
                            }
                        });
                connectionManagerMap = connectionPoolHolder.get();
            }

            connManager = connectionManagerMap.get(connectionManagerMapKey);
            if (connManager == null) {
                Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                        .<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", sslsf).build();
                connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

                connectionManagerMap.put(connectionManagerMapKey, connManager);
            }
        }

        //the DefaultMaxPerRoute default is 2
        if (!StringUtils.isEmpty(defaultMaxPerRoute)) {
            try {
                connManager.setDefaultMaxPerRoute(Integer.parseInt(defaultMaxPerRoute));
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("the '" + HttpClientInputs.CONNECTIONS_MAX_PER_ROUTE
                        + "' input should be integer" + e.getMessage(), e);
            }
        }
        //the Default totalMax default is 20
        if (!StringUtils.isEmpty(totalMax)) {
            try {
                connManager.setMaxTotal(Integer.parseInt(totalMax));
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("the '" + HttpClientInputs.CONNECTIONS_MAX_TOTAL
                        + "' input should be integer" + e.getMessage(), e);
            }
        }
        return connManager;
    }
    return null;
}

From source file:com.sonatype.nexus.ssl.plugin.internal.CertificateRetriever.java

/**
 * Retrieves certificate chain of specified host:port using https protocol.
 *
 * @param host to get certificate chain from (cannot be null)
 * @param port of host to connect to//  ww  w  .j  a va  2  s. c  o  m
 * @return certificate chain
 * @throws Exception Re-thrown from accessing the remote host
 */
public Certificate[] retrieveCertificatesFromHttpsServer(final String host, final int port) throws Exception {
    checkNotNull(host);

    log.info("Retrieving certificate from https://{}:{}", host, port);

    // setup custom connection manager so we can configure SSL to trust-all
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, new TrustManager[] { ACCEPT_ALL_TRUST_MANAGER }, null);
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sc,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HttpSchemes.HTTP, PlainConnectionSocketFactory.getSocketFactory())
            .register(HttpSchemes.HTTPS, sslSocketFactory).build();
    final HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry);

    try {
        final AtomicReference<Certificate[]> certificates = new AtomicReference<>();

        HttpClient httpClient = httpClientManager.create(new Customizer() {
            @Override
            public void customize(final HttpClientPlan plan) {
                // replace connection-manager with customized version needed to fetch SSL certificates
                plan.getClient().setConnectionManager(connectionManager);

                // add interceptor to grab peer-certificates
                plan.getClient().addInterceptorFirst(new HttpResponseInterceptor() {
                    @Override
                    public void process(final HttpResponse response, final HttpContext context)
                            throws HttpException, IOException {
                        ManagedHttpClientConnection connection = HttpCoreContext.adapt(context)
                                .getConnection(ManagedHttpClientConnection.class);

                        // grab the peer-certificates from the session
                        if (connection != null) {
                            SSLSession session = connection.getSSLSession();
                            if (session != null) {
                                certificates.set(session.getPeerCertificates());
                            }
                        }
                    }
                });
            }
        });

        httpClient.execute(new HttpGet("https://" + host + ":" + port));

        return certificates.get();
    } finally {
        // shutdown single-use connection manager
        connectionManager.shutdown();
    }
}

From source file:com.github.horrorho.liquiddonkey.http.HttpClientFactory.java

Registry<ConnectionSocketFactory> relaxedSocketFactoryRegistry() {
    return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", new SSLConnectionSocketFactory(relaxedSSLContext(), (hostname, session) -> true))
            .build();/*from w w  w . j  a v a 2s .c om*/
}

From source file:org.jboss.arquillian.ce.httpclient.HttpClientBuilder.java

public HttpClientBuilder untrustedConnectionClientBuilder() throws Exception {
    // setup a Trust Strategy that allows all certificates.
    ///*from   ww  w  . j a  va  2s .  c  o  m*/
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws java.security.cert.CertificateException {
            return true;
        }

    }).build();
    builder.setSslcontext(sslContext);

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            (X509HostnameVerifier) hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    builder.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    return this;
}