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

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

Introduction

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

Prototype

PlainConnectionSocketFactory INSTANCE

To view the source code for org.apache.http.conn.socket PlainConnectionSocketFactory INSTANCE.

Click Source Link

Usage

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

private void startHttpClient() {
    try {/* w  w w  .ja va  2 s .  co  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.maven.wagon.providers.http.AbstractHttpClientWagon.java

private static PoolingHttpClientConnectionManager createConnManager() {

    String sslProtocolsStr = System.getProperty("https.protocols");
    String cipherSuitesStr = System.getProperty("https.cipherSuites");
    String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null;
    String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null;

    SSLConnectionSocketFactory sslConnectionSocketFactory;
    if (SSL_INSECURE) {
        try {// ww  w  .j  av  a 2 s.c o  m
            SSLContext sslContext = new SSLContextBuilder().useSSL()
                    .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build();
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites,
                    SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
                            : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        } catch (Exception ex) {
            throw new SSLInitializationException(ex.getMessage(), ex);
        }
    } else {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }

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

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
    if (PERSISTENT_POOL) {
        connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE);
        connManager.setMaxTotal(MAX_CONN_TOTAL);
    } else {
        connManager.setMaxTotal(1);
    }
    return connManager;
}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagonFixed.java

@SuppressWarnings("checkstyle:linelength")
private static PoolingHttpClientConnectionManager createConnManager() {

    String sslProtocolsStr = System.getProperty("https.protocols");
    String cipherSuitesStr = System.getProperty("https.cipherSuites");
    String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null;
    String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null;

    SSLConnectionSocketFactory sslConnectionSocketFactory;
    if (SSL_INSECURE) {
        try {// ww w  .j  ava2 s.c  om
            SSLContext sslContext = new SSLContextBuilder().useSSL()
                    .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build();
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites,
                    SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
                            : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        } catch (Exception ex) {
            throw new SSLInitializationException(ex.getMessage(), ex);
        }
    } else {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }

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

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
    if (persistentPool) {
        connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE);
        connManager.setMaxTotal(MAX_CONN_TOTAL);
    } else {
        connManager.setMaxTotal(1);
    }
    return connManager;
}

From source file:org.apache.solr.cloud.TestMiniSolrCloudClusterSSL.java

/**
 * Returns a new HttpClient that supports both HTTP and HTTPS (with the default test truststore), but 
 * has no keystore -- so servers requiring client authentication should fail.
 *///  w ww  .ja  va 2s. c  o  m
private static CloseableHttpClient getSslAwareClientWithNoClientCerts() throws Exception {

    // NOTE: This method explicitly does *NOT* use HttpClientUtil code because that
    // will muck with the global static HttpClientBuilder / SchemeRegistryProvider
    // and we can't do that and still test the entire purpose of what we are trying to test here.

    final SSLTestConfig clientConfig = new SSLTestConfig(true, false);

    final SSLConnectionSocketFactory sslFactory = clientConfig.buildClientSSLConnectionSocketFactory();
    assert null != sslFactory;

    final Registry<ConnectionSocketFactory> socketFactoryReg = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslFactory).register("http", PlainConnectionSocketFactory.INSTANCE).build();

    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryReg));

    return builder.build();
}

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

private Registry<ConnectionSocketFactory> getSocketFactoryRegistry() {
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();

    return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();
}

From source file:org.archive.modules.fetcher.FetchHTTPRequest.java

protected HttpClientConnectionManager buildConnectionManager() {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE).register("https",
                    new SSLConnectionSocketFactory(fetcher.sslContext(), new AllowAllHostnameVerifier()) {

                        @Override
                        public Socket createLayeredSocket(final Socket socket, final String target,
                                final int port, final HttpContext context) throws IOException {

                            return super.createLayeredSocket(socket, isDisableSNI() ? "" : target, port,
                                    context);
                        }/*from  www.  j  a  v  a2s .  com*/
                    })
            .build();

    DnsResolver dnsResolver = new ServerCacheResolver(fetcher.getServerCache());

    ManagedHttpClientConnectionFactory connFactory = new ManagedHttpClientConnectionFactory() {
        private static final int DEFAULT_BUFSIZE = 8 * 1024;

        @Override
        public ManagedHttpClientConnection create(HttpRoute route, ConnectionConfig config) {
            final ConnectionConfig cconfig = config != null ? config : ConnectionConfig.DEFAULT;
            CharsetDecoder chardecoder = null;
            CharsetEncoder charencoder = null;
            final Charset charset = cconfig.getCharset();
            final CodingErrorAction malformedInputAction = cconfig.getMalformedInputAction() != null
                    ? cconfig.getMalformedInputAction()
                    : CodingErrorAction.REPORT;
            final CodingErrorAction unmappableInputAction = cconfig.getUnmappableInputAction() != null
                    ? cconfig.getUnmappableInputAction()
                    : CodingErrorAction.REPORT;
            if (charset != null) {
                chardecoder = charset.newDecoder();
                chardecoder.onMalformedInput(malformedInputAction);
                chardecoder.onUnmappableCharacter(unmappableInputAction);
                charencoder = charset.newEncoder();
                charencoder.onMalformedInput(malformedInputAction);
                charencoder.onUnmappableCharacter(unmappableInputAction);
            }
            return new RecordingHttpClientConnection(DEFAULT_BUFSIZE, DEFAULT_BUFSIZE, chardecoder, charencoder,
                    cconfig.getMessageConstraints(), null, null, DefaultHttpRequestWriterFactory.INSTANCE,
                    DefaultHttpResponseParserFactory.INSTANCE);
        }
    };
    BasicHttpClientConnectionManager connMan = new BasicHttpClientConnectionManager(socketFactoryRegistry,
            connFactory, null, dnsResolver);

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoTimeout(fetcher.getSoTimeoutMs());
    connMan.setSocketConfig(socketConfigBuilder.build());

    return connMan;
}

From source file:org.apache.sling.discovery.etcd.EtcdDiscoveryService.java

private void buildHttpClient(@Nonnull String keystoreFilePath, @Nonnull String keystorePwdFilePath) {

    boolean hasKeyStore = !isEmpty(keystoreFilePath);

    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectionTimeout).setRedirectsEnabled(true).setStaleConnectionCheckEnabled(true)
            .build();//from   w  w w  .  j a v a  2  s.c om

    HttpClientBuilder builder = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .addInterceptorFirst(new GzipRequestInterceptor())
            .addInterceptorFirst(new GzipResponseInterceptor());

    if (hasKeyStore) {

        final SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        LOG.info("Loading keystore from file: {}", keystoreFilePath);
        char[] pwd = readPwd(keystorePwdFilePath);
        try {
            KeyStore keystore = loadKeyStore(keystoreFilePath, pwd);
            sslContextBuilder.loadTrustMaterial(keystore);
            sslContextBuilder.loadKeyMaterial(keystore, pwd);
            LOG.info("Setup custom SSL context");
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslContextBuilder.build());
            Registry<ConnectionSocketFactory> connectionSocketFactory = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", sslConnectionSocketFactory).build();

            builder.setSSLSocketFactory(sslConnectionSocketFactory);

            connectionManager = new PoolingHttpClientConnectionManager(connectionSocketFactory);

        } catch (UnrecoverableKeyException e) {
            throw wrap(e);
        } catch (NoSuchAlgorithmException e) {
            throw wrap(e);
        } catch (KeyStoreException e) {
            throw wrap(e);
        } catch (KeyManagementException e) {
            throw wrap(e);
        } finally {
            reset(pwd);
        }

    } else {
        connectionManager = new PoolingHttpClientConnectionManager();
    }

    builder.setConnectionManager(connectionManager);
    httpClient = builder.build();
}

From source file:com.networknt.client.Client.java

private Registry<ConnectionSocketFactory> registry() throws ClientException {
    Registry<ConnectionSocketFactory> registry = null;
    try {//from   ww  w  . jav  a 2s.  co m
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext(),
                new String[] { "TLSv1" }, null, hostnameVerifier());
        // Create a registry of custom connection factory
        registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", sslFactory).build();
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException: in registry", e);
        throw new ClientException("NoSuchAlgorithmException: in registry", e);
    } catch (KeyManagementException e) {
        logger.error("KeyManagementException: in registry", e);
        throw new ClientException("KeyManagementException: in registry", e);
    } catch (IOException e) {
        logger.error("IOException: in registry", e);
        throw new ClientException("IOException: in registry", e);
    }
    return registry;
}

From source file:org.opennms.core.web.HttpClientWrapper.java

protected void configureSSLContext(final HttpClientBuilder builder) {
    final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
            .<ConnectionSocketFactory>create();
    for (final Map.Entry<String, SSLContext> entry : m_sslContext.entrySet()) {
        final SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(entry.getValue(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registryBuilder.register(entry.getKey(), sslConnectionFactory);
    }/* w w w.j a  v a  2s.co m*/
    if (!m_sslContext.containsKey("http")) {
        registryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    }
    if (!m_sslContext.containsKey("https")) {
        registryBuilder.register("https", SSLConnectionSocketFactory.getSystemSocketFactory());
    }

    final HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registryBuilder.build());
    builder.setConnectionManager(ccm);
}