Creates custom Http Client connection pool to be used by Http Client

@return {@link PoolingHttpClientConnectionManager}
345236
private PoolingHttpClientConnectionManager createConnectionMgr() {
        PoolingHttpClientConnectionManager connectionMgr;

        // prepare SSLContext
        SSLContext sslContext = buildSslContext();
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        // we allow to disable host name verification against CA certificate,
        // notice: in general this is insecure and should be avoided in production,
        // (this type of configuration is useful for development purposes)
        boolean noHostVerification = false;
        LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                noHostVerification ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier()
        );
        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf)
                .register("https", sslsf)
                .build();
        connectionMgr = new PoolingHttpClientConnectionManager(r, null, null,
                null, connectionPoolTimeToLive, TimeUnit.SECONDS);

        connectionMgr.setMaxTotal(maxConnectionsTotal);
        connectionMgr.setDefaultMaxPerRoute(maxConnectionsPerRoute);
        HttpHost localhost = new HttpHost("localhost", 80);
        connectionMgr.setMaxPerRoute(new HttpRoute(localhost), maxConnectionsPerRoute);
        return connectionMgr;
    }
1231155
private ClientConnection createHttpClientConnection(final StreamConnection connection, final OptionMap options, final ByteBufferPool bufferPool) {
		try {
			Class<?> cls = Class.forName("io.undertow.client.http.HttpClientConnection");
			
			Constructor<?> o = cls.getDeclaredConstructor(StreamConnection.class, OptionMap.class, ByteBufferPool.class);
			
			o.setAccessible(true);
			
			return (ClientConnection) o.newInstance(connection, options, bufferPool);			
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
		}

		return null;
	}
310960
private synchronized PoolableConnection newConnection() {
        synchronized (xpool) {
            if (xpool.size() >= maxActive) {
                return null;
            }

            try {
                PoolableConnection conn = null;

                if (xpool.size() < minIdle) {
                    conn = new PoolableConnection(this, ds.getConnection(), liveTime, Integer.MAX_VALUE, maxOpenPreparedStatementsPerConnection);
                } else if (xpool.size() < maxIdle) {
                    conn = new PoolableConnection(this, ds.getConnection(), liveTime, maxIdleTime, maxOpenPreparedStatementsPerConnection);
                } else {
                    conn = new PoolableConnection(this, ds.getConnection(), liveTime, 60 * 1000L, maxOpenPreparedStatementsPerConnection);
                }

                xpool.put(conn, conn);

                if (logger.isWarnEnabled()) {
                    logger.warn("The " + xpool.size() + "th of " + maxActive + " connections is created for data source: " + url);
                }

                return conn;
            } catch (SQLException e) {
                String msg = "Faied to create new connection for data source '" + url + "'." + " [Active connection number]: " + (xpool.size() + 1) + ". "
                        + AbacusException.getErrorMsg(e);
                logger.error(msg, e);
                throw new UncheckedSQLException(msg, e);
            }
        }
    }
659411
public static HttpHubConnectionBuilder create(String url) {
        if (url == null || url.isEmpty()) {
            throw new IllegalArgumentException("A valid url is required.");
        }
        return new HttpHubConnectionBuilder(url);
    }
748715
@Override
    protected Object createPoolOrConnection()
    {
        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()
                .getPersistenceUnitMetadata(getPersistenceUnit());

        Properties props = persistenceUnitMetadata.getProperties();

        String host = externalProperties != null ? (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES)
                : null;
        String port = externalProperties != null ? (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT)
                : null;

        if (host == null)
        {
            host = props.getProperty(PersistenceProperties.KUNDERA_NODES);
        }

        if (port == null)
        {
            port = props.getProperty(PersistenceProperties.KUNDERA_PORT);
        }

        String[] hosts = getHosts(host);

        Properties properties = ((ESClientPropertyReader) propertyReader).getConnectionProperties();

        Builder builder = Settings.settingsBuilder();

        builder.put("client.transport.sniff", true);

        if (properties != null)
        {
            builder.put(properties);
        }

        Settings settings = builder.build();

        TransportClient client = TransportClient.builder().settings(settings).build();

        for (String h : hosts)
        {
            client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(h, new Integer(port))));
        }

        return client;
    }
970537
public static HttpClientBuilder createBuilder(DigipostHttpClientSettings settings) {
        if (settings.timeoutsMs.isPotentiallyDangerous()) {
            settings.logger.warn("New http client with potential dangerous settings. These settings should probably not be used in production:\n{}", settings);
        } else {
            settings.logger.info("New http client:\n{}", settings);
        }

        return HttpClientBuilder.create()
                .setDefaultConnectionConfig(settings.connectionConfig)
                .setDefaultSocketConfig(createSocketConfig(settings.timeoutsMs))
                .setDefaultRequestConfig(createRequestConfig(settings.timeoutsMs))
                .setMaxConnTotal(settings.connectionAmount.maxTotal)
                .setMaxConnPerRoute(settings.connectionAmount.maxPerRoute)
                .setProxy(settings.httpProxy);
    }
120839
@Override
    protected Object createPoolOrConnection()
    {
        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()
                .getPersistenceUnitMetadata(getPersistenceUnit());

        Properties props = persistenceUnitMetadata.getProperties();
        String keyspace = null;

        if (externalProperties != null)
        {
            keyspace = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);
        }

        if (keyspace == null)
        {
            keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);
        }

        for (Host host : ((CassandraHostConfiguration) configuration).getCassandraHosts())
        {
            PoolConfiguration prop = new PoolProperties();
            prop.setHost(host.getHost());
            prop.setPort(host.getPort());
            prop.setKeySpace(keyspace);

            CassandraUtilities.setPoolConfigPolicy((CassandraHost) host, prop);
            try
            {
                ConnectionPool pool = new ConnectionPool(prop);
                hostPools.put(host, pool);
            }
            catch (TException e)
            {
                logger.warn("Node {} are down, Caused by {} .", host.getHost(), e.getMessage());
                if (host.isRetryHost())
                {
                    logger.warn("Scheduling node for future retry");
                    ((CassandraRetryService) hostRetryService).add((CassandraHost) host);
                }
            }
        }
        return null;
    }
135545
@Override
    protected Client instantiateClient(String persistenceUnit)
    {
        ConnectionPool pool = getPoolUsingPolicy();
        return new ThriftClient(this, indexManager, reader, persistenceUnit, pool, externalProperties, kunderaMetadata, timestampGenerator);
    }
245303
private CloseableHttpClient createHttpClient(HttpClientConnectionManager connectionManager) {
        HttpClientBuilder builder =
                HttpClients.custom().setConnectionManager(connectionManager).disableAutomaticRetries();

        int socketBufferSizeInBytes = this.config.getSocketBufferSizeInBytes();
        if (socketBufferSizeInBytes > 0) {
            builder.setDefaultConnectionConfig(
                    ConnectionConfig.custom().setBufferSize(socketBufferSizeInBytes).build());
        }

        return builder.build();
    }
611034
public static ClientHttpConnector create(ClientOptions options) {
		HttpClient httpClient = HttpClient.create();

		if (usingCustomCerts(options)) {
			TrustManagerFactory trustManagerFactory =
					sslCertificateUtils.createTrustManagerFactory(options.getCaCertFiles());

			httpClient = httpClient.secure(sslContextSpec -> sslContextSpec
					.sslContext(SslContextBuilder.forClient()
							.sslProvider(SslProvider.JDK)
							.trustManager(trustManagerFactory)));
		} else {
			httpClient = httpClient.secure(sslContextSpec -> sslContextSpec
					.sslContext(SslContextBuilder.forClient()
							.sslProvider(SslProvider.JDK)));
		}

		if (options.getConnectionTimeout() != null) {
			httpClient = httpClient.tcpConfiguration(tcpClient ->
					tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
							Math.toIntExact(options.getConnectionTimeout().toMillis())));
		}

		return new ReactorClientHttpConnector(httpClient);
	}
1268978
@Override
    protected Object createPoolOrConnection()
    {
        try
        {
            this.connection = ConnectionFactory.createConnection(conf);
            return connection;
        }
        catch (IOException e)
        {
            logger.error("Connection could not be established", e);
            throw new KunderaException("Connection could not be established", e);
        }
    }
587668
public static ClientHttpRequestFactory create(ClientOptions options) {

		Assert.notNull(options, "ClientOptions must not be null");

		try {
			if (HTTP_COMPONENTS_PRESENT) {
				logger.info("Using Apache HttpComponents HttpClient for HTTP connections");
				return HttpComponents.usingHttpComponents(options);
			}

			if (OKHTTP3_PRESENT) {
				logger.info("Using OkHttp3 for HTTP connections");
				return OkHttp3.usingOkHttp3(options);
			}

			if (NETTY_PRESENT) {
				logger.info("Using Netty for HTTP connections");
				return Netty.usingNetty(options);
			}
		} catch (GeneralSecurityException | IOException e) {
			logger.warn("Error configuring HTTP connections", e);
		}

		logger.info("Defaulting to java.net.HttpUrlConnection for HTTP connections");
		return HttpURLConnection.usingJdk(options);
	}
1034342
public ApiClient setHttpClient(OkHttpClient newHttpClient) {
        if (!httpClient.equals(newHttpClient)) {
            newHttpClient.networkInterceptors().addAll(httpClient.networkInterceptors());
            httpClient.networkInterceptors().clear();
            newHttpClient.interceptors().addAll(httpClient.interceptors());
            httpClient.interceptors().clear();
            this.httpClient = newHttpClient;
        }
        return this;
    }
518563
protected Connection createHttpConnection(Dsn dsn) {
        URL sentryApiUrl = HttpConnection.getSentryApiUrl(dsn.getUri(), dsn.getProjectId());

        String proxyHost = getProxyHost(dsn);
        String proxyUser = getProxyUser(dsn);
        String proxyPass = getProxyPass(dsn);
        int proxyPort = getProxyPort(dsn);

        Proxy proxy = null;
        if (proxyHost != null) {
            InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
            proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
            if (proxyUser != null && proxyPass != null) {
                Authenticator.setDefault(new ProxyAuthenticator(proxyUser, proxyPass));
            }
        }

        Double sampleRate = getSampleRate(dsn);
        EventSampler eventSampler = null;
        if (sampleRate != null) {
            eventSampler = new RandomEventSampler(sampleRate);
        }

        HttpConnection httpConnection = new HttpConnection(sentryApiUrl, dsn.getPublicKey(),
            dsn.getSecretKey(), proxy, eventSampler);

        Marshaller marshaller = createMarshaller(dsn);
        httpConnection.setMarshaller(marshaller);

        int timeout = getTimeout(dsn);
        httpConnection.setConnectionTimeout(timeout);

        boolean bypassSecurityEnabled = getBypassSecurityEnabled(dsn);
        httpConnection.setBypassSecurity(bypassSecurityEnabled);

        return httpConnection;
    }
954859
public static HttpClient<ByteBuf, ByteBuf> newClient(ConnectionProviderFactory<ByteBuf, ByteBuf> providerFactory,
                                                         Observable<Host> hostStream) {
        return HttpClientImpl.create(providerFactory, hostStream);
    }
136429
def create_jdbc_connection_pool(name, server=None, **kwargs):
    '''
    
    '''
    defaults = {
        'allowNonComponentCallers': False,
        'associateWithThread': False,
        'connectionCreationRetryAttempts': '0',
        'connectionCreationRetryIntervalInSeconds': '10',
        'connectionLeakReclaim': False,
        'connectionLeakTimeoutInSeconds': '0',
        'connectionValidationMethod': 'table',
        'datasourceClassname': '',
        'description': '',
        'driverClassname': '',
        'failAllConnections': False,
        'idleTimeoutInSeconds': '300',
        'initSql': '',
        'isConnectionValidationRequired': False,
        'isIsolationLevelGuaranteed': True,
        'lazyConnectionAssociation': False,
        'lazyConnectionEnlistment': False,
        'matchConnections': False,
        'maxConnectionUsageCount': '0',
        'maxPoolSize': '32',
        'maxWaitTimeInMillis': 60000,
        'name': name,
        'nonTransactionalConnections': False,
        'ping': False,
        'poolResizeQuantity': '2',
        'pooling': True,
        'resType': '',
        'sqlTraceListeners': '',
        'statementCacheSize': '0',
        'statementLeakReclaim': False,
        'statementLeakTimeoutInSeconds': '0',
        'statementTimeoutInSeconds': '-1',
        'steadyPoolSize': '8',
        'target': 'server',
        'transactionIsolationLevel': '',
        'validateAtmostOncePeriodInSeconds': '0',
        'validationClassname': '',
        'validationTableName': '',
        'wrapJdbcObjects': True
    }

    # Data = defaults + merge kwargs + poolname
    data = defaults
    data.update(kwargs)

    # Check resType against acceptable values
    if data['resType'] not in (
            'javax.sql.DataSource',
            'javax.sql.XADataSource',
            'javax.sql.ConnectionPoolDataSource',
            'java.sql.Driver'
       ):
        raise CommandExecutionError('Invalid resource type')

    # Check connectionValidationMethod against acceptable velues
    if data['connectionValidationMethod'] not in (
            'auto-commit',
            'meta-data',
            'table',
            'custom-validation'
       ):
        raise CommandExecutionError('Invalid connection validation method')

    if data['transactionIsolationLevel'] \
       and data['transactionIsolationLevel'] not in (
               'read-uncommitted',
               'read-committed',
               'repeatable-read',
               'serializable'
       ):
        raise CommandExecutionError('Invalid transaction isolation level')

    if not data['datasourceClassname'] \
       and data['resType'] in (
               'javax.sql.DataSource',
               'javax.sql.ConnectionPoolDataSource',
               'javax.sql.XADataSource'
       ):
        raise CommandExecutionError('No datasource class name while using datasource resType')
    if not data['driverClassname'] and data['resType'] == 'java.sql.Driver':
        raise CommandExecutionError('No driver class nime while using driver resType')

    return _create_element(name, 'resources/jdbc-connection-pool', data, server)
559700
def _build_http_client(cls, session: AppSession):
        '''
        '''
        # TODO:
        # recorder = self._build_recorder()

        stream_factory = functools.partial(
            HTTPStream,
            ignore_length=session.args.ignore_length,
            keep_alive=session.args.http_keep_alive)

        return session.factory.new(
            'HTTPClient',
            connection_pool=session.factory['ConnectionPool'],
            stream_factory=stream_factory
         )