org.apache.http.config.Registry Java Examples

The following examples show how to use org.apache.http.config.Registry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MPRestClient.java    From dx-java with MIT License 10 votes vote down vote up
/**
 * Create a HttpClient
 * @return a HttpClient
 */
private HttpClient createHttpClient() {
    SSLContext sslContext = SSLContexts.createDefault();
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[]{"TLSv1.1", "TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory)
            .build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(MercadoPago.SDK.getMaxConnections());
    connectionManager.setDefaultMaxPerRoute(MercadoPago.SDK.getMaxConnections());
    connectionManager.setValidateAfterInactivity(VALIDATE_INACTIVITY_INTERVAL_MS);

    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(MercadoPago.SDK.getRetries(), false);

    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setKeepAliveStrategy(new KeepAliveStrategy())
            .setRetryHandler(retryHandler)
            .disableCookieManagement()
            .disableRedirectHandling();

    return httpClientBuilder.build();
}
 
Example #2
Source File: SmartRestTemplateConfig.java    From smart-admin with MIT License 7 votes vote down vote up
@Bean
public HttpClient httpClient() {
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", SSLConnectionSocketFactory.getSocketFactory())
            .build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(maxTotal);
    connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout)
            .build();
    return HttpClientBuilder.create()
            .setDefaultRequestConfig(requestConfig)
            .setConnectionManager(connectionManager)
            .build();
}
 
Example #3
Source File: ConfigServerApiImpl.java    From vespa with Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient createClient(SSLConnectionSocketFactory socketFactory) {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", socketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    cm.setMaxTotal(200); // Increase max total connections to 200, which should be enough

    // Have experienced hang in socket read, which may have been because of
    // system defaults, therefore set explicit timeouts.
    return HttpClientBuilder.create()
            .setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG)
            .disableAutomaticRetries()
            .setUserAgent("node-admin")
            .setConnectionManager(cm)
            .build();
}
 
Example #4
Source File: ApacheConnectionManagerFactory.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
private Registry<ConnectionSocketFactory> createSocketFactoryRegistry(ConnectionSocketFactory sslSocketFactory) {

        /*
         * If SSL cert checking for endpoints has been explicitly disabled,
         * register a new scheme for HTTPS that won't cause self-signed certs to
         * error out.
         */
        if (SDKGlobalConfiguration.isCertCheckingDisabled()) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("SSL Certificate checking for endpoints has been " +
                        "explicitly disabled.");
            }
            sslSocketFactory = new TrustingSocketFactory();
        }

        return RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
    }
 
Example #5
Source File: HttpProtocolParent.java    From dtsopensource with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient createHttpClient(String hostname, int port) {
    ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
    LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("http", plainsf).register("https", sslsf).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    // 将最大连接数增加
    cm.setMaxTotal(maxTotal);
    // 将每个路由基础的连接增加
    cm.setDefaultMaxPerRoute(maxPerRoute);
    HttpHost httpHost = new HttpHost(hostname, port);
    // 将目标主机的最大连接数增加
    cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
    // 请求重试处理
    return HttpClients.custom().setConnectionManager(cm).setRetryHandler(httpRequestRetryHandler).build();
}
 
Example #6
Source File: HttpClientPool.java    From FATE-Serving with Apache License 2.0 6 votes vote down vote up
public static void initPool() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
                Dict.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(
                Dict.HTTPS, sslsf).build();
        poolConnManager = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        poolConnManager.setMaxTotal(500);
        poolConnManager.setDefaultMaxPerRoute(200);
        int socketTimeout = 10000;
        int connectTimeout = 10000;
        int connectionRequestTimeout = 10000;
        requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
                connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
                connectTimeout).build();
        httpClient = getConnection();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        logger.error("init http client pool failed:", ex);
    }
}
 
Example #7
Source File: HttpProtocolParent.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient createHttpClient(String hostname, int port) {
	ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
	LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
	Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
			.register("http", plainsf).register("https", sslsf).build();
	PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
	// 将最大连接数增加
	cm.setMaxTotal(maxTotal);
	// 将每个路由基础的连接增加
	cm.setDefaultMaxPerRoute(maxPerRoute);
	HttpHost httpHost = new HttpHost(hostname, port);
	// 将目标主机的最大连接数增加
	cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
	// 请求重试处理
	return HttpClients.custom().setConnectionManager(cm).setRetryHandler(httpRequestRetryHandler).build();
}
 
Example #8
Source File: HttpUtils.java    From ScriptSpider with Apache License 2.0 6 votes vote down vote up
/**
 * 创建httpclient连接池,并初始化httpclient
 */
public void init() {
    try {
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
                new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslsf)
                .build();
        httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        // Increase max total connection to 200
        httpClientConnectionManager.setMaxTotal(maxTotalPool);
        // Increase default max connection per route to 20
        httpClientConnectionManager.setDefaultMaxPerRoute(maxConPerRoute);
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
        httpClientConnectionManager.setDefaultSocketConfig(socketConfig);
    } catch (Exception e) {

    }
}
 
Example #9
Source File: ClientConnection.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static PoolingHttpClientConnectionManager getConnctionManager(){

        Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
        try {
            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;
    }
 
Example #10
Source File: HttpClientBuilder.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private static Registry<ConnectionSocketFactory> getSslFactoryRegistry(String certPath) throws IOException {
    try
    {
        KeyStore keyStore = KeyStoreUtil.createDockerKeyStore(certPath);

        SSLContext sslContext =
                SSLContexts.custom()
                           .setProtocol(SSLConnectionSocketFactory.TLS)
                           .loadKeyMaterial(keyStore, "docker".toCharArray())
                           .loadTrustMaterial(keyStore, null)
                           .build();
        String tlsVerify = System.getenv("DOCKER_TLS_VERIFY");
        SSLConnectionSocketFactory sslsf =
                tlsVerify != null && !tlsVerify.equals("0") && !tlsVerify.equals("false") ?
                        new SSLConnectionSocketFactory(sslContext) :
                        new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        return RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();
    }
    catch (GeneralSecurityException e) {
        // this isn't ideal but the net effect is the same
        throw new IOException(e);
    }
}
 
Example #11
Source File: TelegramHttpClientBuilder.java    From TelegramBots with MIT License 6 votes vote down vote up
private static HttpClientConnectionManager createConnectionManager(DefaultBotOptions options) {
    Registry<ConnectionSocketFactory> registry;
    switch (options.getProxyType()) {
        case NO_PROXY:
            return null;
        case HTTP:
            registry = RegistryBuilder.<ConnectionSocketFactory> create()
                    .register("http", new HttpConnectionSocketFactory())
                    .register("https", new HttpSSLConnectionSocketFactory(SSLContexts.createSystemDefault())).build();
            return new PoolingHttpClientConnectionManager(registry);
        case SOCKS4:
        case SOCKS5:
            registry = RegistryBuilder.<ConnectionSocketFactory> create()
                    .register("http", new SocksConnectionSocketFactory())
                    .register("https", new SocksSSLConnectionSocketFactory(SSLContexts.createSystemDefault()))
                    .build();
            return new PoolingHttpClientConnectionManager(registry);
    }
    return null;
}
 
Example #12
Source File: HttpClientHelper.java    From cosmic with Apache License 2.0 6 votes vote down vote up
public static CloseableHttpClient createHttpClient(final int maxRedirects) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    s_logger.info("Creating new HTTP connection pool and client");
    final Registry<ConnectionSocketFactory> socketFactoryRegistry = createSocketFactoryConfigration();
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connManager.setDefaultMaxPerRoute(MAX_ALLOCATED_CONNECTIONS_PER_ROUTE);
    connManager.setMaxTotal(MAX_ALLOCATED_CONNECTIONS);
    final RequestConfig requestConfig = RequestConfig.custom()
                                                     .setCookieSpec(CookieSpecs.DEFAULT)
                                                     .setMaxRedirects(maxRedirects)
                                                     .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                                                     .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
                                                     .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
                                                     .build();
    return HttpClientBuilder.create()
                            .setConnectionManager(connManager)
                            .setRedirectStrategy(new LaxRedirectStrategy())
                            .setDefaultRequestConfig(requestConfig)
                            .setDefaultCookieStore(cookieStore)
                            .setRetryHandler(new StandardHttpRequestRetryHandler())
                            .build();
}
 
Example #13
Source File: YouTrackClient.java    From vk-java-sdk with MIT License 5 votes vote down vote up
public YouTrackClient(String host, String keyStoreType, String keyStorePath, String keyStorePassword, String keyPassword,
                      String trustStoreType, String trustStorePath, String trustStorePassword) {
    this.host = host;

    CookieStore cookieStore = new BasicCookieStore();
    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(SOCKET_TIMEOUT_MS)
            .setConnectTimeout(CONNECTION_TIMEOUT_MS)
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();

    LayeredConnectionSocketFactory sslFactory;

    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory());

    if (host.contains("https://")) {
        try {
            sslFactory = initSslContext(keyStoreType, keyStorePath, keyStorePassword, keyPassword, trustStoreType, trustStorePath, trustStorePassword);
            registryBuilder.register("https", sslFactory);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    Registry<ConnectionSocketFactory> registry = registryBuilder.build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);

    connectionManager.setMaxTotal(MAX_SIMULTANEOUS_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MAX_SIMULTANEOUS_CONNECTIONS);

    client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig)
            .setDefaultCookieStore(cookieStore)
            .build();
}
 
Example #14
Source File: HttpConnectionPoolBuilder.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
public PoolingHttpClientConnectionManager createConnectionManager(final Registry<ConnectionSocketFactory> registry) {
    if(log.isDebugEnabled()) {
        log.debug(String.format("Setup connection pool with registry %s", registry));
    }
    final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry);
    manager.setMaxTotal(preferences.getInteger("http.connections.total"));
    manager.setDefaultMaxPerRoute(preferences.getInteger("http.connections.route"));
    // Detect connections that have become stale (half-closed) while kept inactive in the pool
    manager.setValidateAfterInactivity(preferences.getInteger("http.connections.stale.check.ms"));
    return manager;
}
 
Example #15
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private static HttpClient createDefaultHttpClient() {
	Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
			.register("http", PlainConnectionSocketFactory.getSocketFactory())
			.register("https", SSLConnectionSocketFactory.getSocketFactory())
			.build();

	PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(schemeRegistry);
	connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
	connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

	return HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}
 
Example #16
Source File: HttpUtil.java    From ZhihuSpider with MIT License 5 votes vote down vote up
public static HttpClientContext getHttpClientContext() {
    HttpClientContext context = null;
    context = HttpClientContext.create();
    Registry<CookieSpecProvider> registry = RegistryBuilder
            .<CookieSpecProvider>create()
            .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
            .register(CookieSpecs.BROWSER_COMPATIBILITY,
                    new BrowserCompatSpecFactory()).build();
    context.setCookieSpecRegistry(registry);
    return context;
}
 
Example #17
Source File: HttpClientTest.java    From netcrusher-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    reactor = new NioReactor();

    crusher = TcpCrusherBuilder.builder()
            .withReactor(reactor)
            .withBindAddress("127.0.0.1", CRUSHER_PORT)
            .withConnectAddress(REMOTE_HOST, REMOTE_PORT)
            .buildAndOpen();

    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase(REMOTE_HOST)) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] {127, 0, 0, 1}) };
            } else {
                return super.resolve(host);
            }
        }
    };

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> httpConnectionFactory =
            new ManagedHttpClientConnectionFactory();

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

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, httpConnectionFactory, dnsResolver);

    http = HttpClients.createMinimal(connectionManager);
}
 
Example #18
Source File: HttpClientHelper.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private static Registry<ConnectionSocketFactory> createSocketFactoryConfigration() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    final Registry<ConnectionSocketFactory> socketFactoryRegistry;
    final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
    final SSLConnectionSocketFactory cnnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HTTPS, cnnectionSocketFactory)
            .build();

    return socketFactoryRegistry;
}
 
Example #19
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private Registry<ConnectionSocketFactory> createConnectionSocketFactory() {
  HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(PublicSuffixMatcherLoader.getDefault());
  ConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextOverride != null ?
      sslContextOverride : defaultSslContext, sslSupportedProtocols, null, hostnameVerifier);

  return RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", PlainConnectionSocketFactory.getSocketFactory())
      .register("https", sslSocketFactory)
      .build();
}
 
Example #20
Source File: IgnoreSSLUtils.java    From MixPush with Apache License 2.0 5 votes vote down vote up
/**
 * for ignoring verify SSL
 */
public static CloseableHttpClient createClient() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext sslcontext = createIgnoreVerifySSL();

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClients.custom().setConnectionManager(connManager);

    return HttpClients.custom().setConnectionManager(connManager).build();
}
 
Example #21
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
protected Registry<ConnectionSocketFactory> configureSocketFactories() {
  RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
  if (host.getSchemeName().equalsIgnoreCase("https")) {
    configureHttpsRegistry(registryBuilder);
  } else {
    configureHttpRegistry(registryBuilder);
  }
  return registryBuilder.build();
}
 
Example #22
Source File: ExtendedJestClientFactory.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
Registry<SchemeIOSessionStrategy> createSchemeIOSessionStrategyRegistry() {
    HttpClientConfig httpClientConfig = wrappedHttpClientConfig.getHttpClientConfig();
    return RegistryBuilder.<SchemeIOSessionStrategy>create()
                .register("http", httpClientConfig.getHttpIOSessionStrategy())
                .register("https", httpClientConfig.getHttpsIOSessionStrategy())
                .build();
}
 
Example #23
Source File: RestTemplateConfig.java    From plumdo-work with Apache License 2.0 5 votes vote down vote up
@Bean
public Registry<ConnectionSocketFactory> socketFactoryRegistry() {
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext(),
            hostnameVerifier);

    return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory).build();
}
 
Example #24
Source File: AccessApi.java    From nifi-swagger-client with Apache License 2.0 5 votes vote down vote up
private HttpClient createSPNEGOHttpClient()  throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    Credentials jaasCredentials = new Credentials() {
        public String getPassword() {
            return null;
        }
        public Principal getUserPrincipal() {
            return null;
        }
    };
    credsProvider.setCredentials(new AuthScope(null, -1, null), jaasCredentials);
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
            .register(AuthSchemes.SPNEGO,new SPNegoSchemeFactory(true, false))
            .build();

    RequestConfig config = RequestConfig.custom().setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.SPNEGO, AuthSchemes.KERBEROS, AuthSchemes.NTLM)).build();

    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setDefaultAuthSchemeRegistry(authSchemeRegistry)
            .setDefaultCredentialsProvider(credsProvider)
            .setDefaultRequestConfig(config);

    if (!this.apiClient.isVerifyingSsl()) {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        httpClientBuilder = httpClientBuilder
                                .setSSLContext(sslContext)
                                .setSSLHostnameVerifier(hostnameVerifier);
    }

    return httpClientBuilder.build();
}
 
Example #25
Source File: InsecurePilosaClientIT.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Registry<ConnectionSocketFactory> getRegistry() {
    HostnameVerifier verifier = new HostnameVerifier() {
        @Override
        public boolean verify(String hostName, SSLSession session) {
            return true;
        }
    };

    SSLContext sslContext = null;
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        e.printStackTrace();
    }
    if (sslContext == null) {
        throw new RuntimeException("SSL Context not created");
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslContext,
            new String[]{"TLSv1.2"}, null, verifier);
    return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();
}
 
Example #26
Source File: PilosaClient.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected Registry<ConnectionSocketFactory> getRegistry() {
    HostnameVerifier verifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            this.options.getSslContext(),
            new String[]{"TLSv1.2"}, null, verifier);
    return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();
}
 
Example #27
Source File: HttpClientConnectionManagerFactory.java    From data-highway with Apache License 2.0 5 votes vote down vote up
private static Registry<ConnectionSocketFactory> createRegistry(TLSConfig.Factory tlsConfigFactory) {
  RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
  TLSConfig tlsConfig = tlsConfigFactory == null ? null : tlsConfigFactory.create();
  if (tlsConfig != null) {
    SSLContext sslContext = tlsConfig.getSslContext();
    HostnameVerifier hostnameVerifier = tlsConfig.getHostnameVerifier();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    registryBuilder.register("https", socketFactory);
  } else {
    registryBuilder.register("https", SSLConnectionSocketFactory.getSocketFactory());
  }
  return registryBuilder.build();
}
 
Example #28
Source File: SimpleHttpClient.java    From vespa with Apache License 2.0 5 votes vote down vote up
public SimpleHttpClient(SSLContext sslContext, List<String> enabledProtocols, List<String> enabledCiphers,
                        int listenPort, boolean useCompression) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (!useCompression) {
        builder.disableContentCompression();
    }
    if (sslContext != null) {
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
                sslContext,
                toArray(enabledProtocols),
                toArray(enabledCiphers),
                new DefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslConnectionFactory);

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory)
                .build();
        builder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        scheme = "https";
    } else {
        scheme = "http";
    }
    this.delegate = builder.build();
    this.listenPort = listenPort;
}
 
Example #29
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static HttpClient createDefaultHttpClient() {
	Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
			.register("http", PlainConnectionSocketFactory.getSocketFactory())
			.register("https", SSLConnectionSocketFactory.getSocketFactory())
			.build();

	PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(schemeRegistry);
	connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
	connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

	return HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}
 
Example #30
Source File: RestClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
private Registry constructRegistry() {

        try {
            SSLContextBuilder builder = SSLContextBuilder.create();

            builder.useProtocol(this.supportedProtocols[0]);

            if (!StringUtils.isNullOrEmpty(clientConfigurator.getCertificateFileName())) {
                builder.loadKeyMaterial(SslUtils.loadKeystore(clientConfigurator.getCertificateFileName(),
                                                              clientConfigurator.getCertificateFilePassword()),
                                        clientConfigurator.getCertificateFilePassword().toCharArray());
            }

            // Trust all certificates
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted( X509Certificate[] chain, String authType ) throws CertificateException {

                    return true;
                }
            });
            SSLContext sslContext = builder.build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                                                                              new NoopHostnameVerifier());

            Registry registry = RegistryBuilder.create().register("https", sslsf).build();

            return registry;
        } catch (Exception e) {
            throw new RuntimeException("Unable to setup SSL context for REST client with Apache connector provider", e);
        }
    }