Create connection manager for http client.

@return The connection manager for http client.
548401
private HttpClientConnectionManager createHttpClientConnectionManager() {
        ConnectionSocketFactory socketFactory = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslSocketFactory;
        try {
            sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                    SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
        } catch (NoSuchAlgorithmException e) {
            throw new BceClientException("Fail to create SSLConnectionSocketFactory", e);
        }
        Registry<ConnectionSocketFactory> registry =
                RegistryBuilder.<ConnectionSocketFactory>create().register(Protocol.HTTP.toString(), socketFactory)
                        .register(Protocol.HTTPS.toString(), sslSocketFactory).build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setDefaultMaxPerRoute(this.config.getMaxConnections());
        connectionManager
                .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(this.config.getSocketTimeoutInMillis())
                        .setTcpNoDelay(true).build());
        connectionManager.setMaxTotal(this.config.getMaxConnections());
        return connectionManager;
    }
1350299
public NewRelicClient initialize()
    {    
        Client client = provider.getClient();
        String protocol = provider.useSsl() ? "https" : "http";
        httpContext = new HttpContext(client, protocol, hostname, port);
        httpContext.setUriPrefix(getUriPrefix());
        httpContext.setThrowExceptions(handleErrors);
        String className = getClass().getName();
        logger.fine(className.substring(className.lastIndexOf(".")+1)+" initialized");
        return this;
    }
610916
public CloseableHttpClient getHttpClient() {
        CloseableHttpClient result = httpClient;
        if (result == null) {
            synchronized (DocumentLoader.class) {
                result = httpClient;
                if (result == null) {
                    result = httpClient = JsonUtils.getDefaultHttpClient();
                }
            }
        }
        return result;
    }
659411
public static HttpHubConnectionBuilder create(String url) {
        if (url == null || url.isEmpty()) {
            throw new IllegalArgumentException("A valid url is required.");
        }
        return new HttpHubConnectionBuilder(url);
    }
774544
public static boolean removeConnectionManager(HttpClientConnectionManager connectionManager) {
        boolean wasRemoved = connectionManagers.remove(connectionManager) != null;
        if (connectionManagers.isEmpty()) {
            shutdown();
        }
        return wasRemoved;
    }
439034
protected final CommPortConnectionFactory createCommPortConnectionFactory()
    {
        //create new instance
        CommPortConnectionFactory factory=(CommPortConnectionFactory)ReflectionHelper.createInstance(this.commConnectionFactoryClassName);
            
        //initialize
        factory.initialize(this);
        
        return factory;
    }
997268
private HttpConnectorList getHttpConnectors() throws Exception {
        logger.info("Searching HTTP connectors.");
        HttpConnectorList httpConnectorList = null;
        //find Jboss first as is typical setup
        httpConnectorList = jBossConnectorDiscover.findConnectors();
        if (httpConnectorList == null || httpConnectorList.getConnectors().isEmpty()) {
            //if not found try tomcat
            httpConnectorList = new TomcatConnectorDiscover().findConnectors();
        }
        return httpConnectorList;
    }
836478
protected ConfiguredCloseableHttpClient createClient(
            final org.apache.http.impl.client.HttpClientBuilder builder,
            final InstrumentedHttpClientConnectionManager manager,
            final String name) {
        final String cookiePolicy = configuration.isCookiesEnabled() ? CookieSpecs.DEFAULT : CookieSpecs.IGNORE_COOKIES;
        final Integer timeout = (int) configuration.getTimeout().toMilliseconds();
        final Integer connectionTimeout = (int) configuration.getConnectionTimeout().toMilliseconds();
        final Integer connectionRequestTimeout = (int) configuration.getConnectionRequestTimeout().toMilliseconds();
        final long keepAlive = configuration.getKeepAlive().toMilliseconds();
        final ConnectionReuseStrategy reuseStrategy = keepAlive == 0
                ? new NoConnectionReuseStrategy()
                : new DefaultConnectionReuseStrategy();
        final HttpRequestRetryHandler retryHandler = configuration.getRetries() == 0
                ? NO_RETRIES
                : (httpRequestRetryHandler == null ? new DefaultHttpRequestRetryHandler(configuration.getRetries(),
                false) : httpRequestRetryHandler);

        final RequestConfig requestConfig
                = RequestConfig.custom().setCookieSpec(cookiePolicy)
                .setSocketTimeout(timeout)
                .setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .build();
        final SocketConfig socketConfig = SocketConfig.custom()
                .setTcpNoDelay(true)
                .setSoTimeout(timeout)
                .build();

        customizeBuilder(builder)
                .setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy, name))
                .setConnectionManager(manager)
                .setDefaultRequestConfig(requestConfig)
                .setDefaultSocketConfig(socketConfig)
                .setConnectionReuseStrategy(reuseStrategy)
                .setRetryHandler(retryHandler)
                .setUserAgent(createUserAgent(name));

        if (keepAlive != 0) {
            // either keep alive based on response header Keep-Alive,
            // or if the server can keep a persistent connection (-1), then override based on client's configuration
            builder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    final long duration = super.getKeepAliveDuration(response, context);
                    return (duration == -1) ? keepAlive : duration;
                }
            });
        }

        // create a tunnel through a proxy host if it's specified in the config
        final ProxyConfiguration proxy = configuration.getProxyConfiguration();
        if (proxy != null) {
            final HttpHost httpHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getScheme());
            builder.setRoutePlanner(new NonProxyListProxyRoutePlanner(httpHost, proxy.getNonProxyHosts()));
            // if the proxy host requires authentication then add the host credentials to the credentials provider
            final AuthConfiguration auth = proxy.getAuth();
            if (auth != null) {
                if (credentialsProvider == null) {
                    credentialsProvider = new BasicCredentialsProvider();
                }
                // set the AuthScope
                AuthScope authScope = new AuthScope(httpHost, auth.getRealm(), auth.getAuthScheme());

                // set the credentials type
                Credentials credentials = configureCredentials(auth);

                credentialsProvider.setCredentials(authScope, credentials);
            }
        }


        if (credentialsProvider != null) {
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }

        if (routePlanner != null) {
            builder.setRoutePlanner(routePlanner);
        }

        if (disableContentCompression) {
            builder.disableContentCompression();
        }

        if (redirectStrategy != null) {
            builder.setRedirectStrategy(redirectStrategy);
        }

        if (defaultHeaders != null) {
            builder.setDefaultHeaders(defaultHeaders);
        }

        if (verifier != null) {
            builder.setSSLHostnameVerifier(verifier);
        }

        if (httpProcessor != null) {
            builder.setHttpProcessor(httpProcessor);
        }

        if (serviceUnavailableRetryStrategy != null) {
            builder.setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy);
        }

        return new ConfiguredCloseableHttpClient(builder.build(), requestConfig);
    }
29412
public Object openConnection(String endpointUri) throws ConnectionException {
        try {
            Map<String,String> params = getRequestParameters();
            if (params != null && !params.isEmpty()) {
                StringBuffer query = new StringBuffer();
                query.append(endpointUri.indexOf('?') < 0 ? '?' : '&');
                int count = 0;
                for (String name : params.keySet()) {
                    if (count > 0)
                        query.append('&');
                    String encoding = getUrlEncoding();
                    query.append(encoding == null ? name : URLEncoder.encode(name, encoding)).append("=");
                    query.append(encoding == null ? params.get(name) : URLEncoder.encode(params.get(name), encoding));
                    count++;
                }
                endpointUri += query;
            }
            URL url = new URL(endpointUri);

            HttpConnection httpConnection;
            if ("PATCH".equals(getHttpMethod()))
                httpConnection = new HttpAltConnection(url);
            else
                httpConnection = new HttpConnection(url);

            httpConnection.open();
            return httpConnection;
        }
        catch (Exception ex) {
            throw new ConnectionException(ConnectionException.CONNECTION_DOWN, ex.getMessage(), ex);
        }
    }
242866
private CloseableHttpAsyncClient createClient(HttpSettings settings, ApacheHttpClientConfiguration conf) {
        IOReactorConfig ioReactor = IOReactorConfig.custom().setIoThreadCount(conf.getMaxThreadCount()).build();
        HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom()
                .useSystemProperties()
                        // allow POST redirects
                .setRedirectStrategy(new LaxRedirectStrategy()).setMaxConnTotal(conf.getMaxTotalConnectionCount()).setMaxConnPerRoute(conf.getMaxRouteConnectionCount()).setDefaultIOReactorConfig(ioReactor)
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).setDefaultRequestConfig(createDefaultRequestConfig(settings));
        if (settings.getProxyUrl() != null) {
            DefaultProxyRoutePlanner routePlanner = createProxyRoutePlanner(settings, httpClientBuilder);
            httpClientBuilder.setRoutePlanner(routePlanner);
        }
        CloseableHttpAsyncClient httpClient = httpClientBuilder.build();
        httpClient.start();
        return httpClient;
    }
433427
public HttpClient get() {
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
    cm.setMaxTotal(nrOfThreads);
    cm.setDefaultMaxPerRoute(maxToRoute);
    final DefaultHttpClient client = HTTPSFaker.getClientThatAllowAnyHTTPS(cm);

    client.getParams().setParameter("http.socket.timeout", socketTimeout);
    client.getParams().setParameter("http.connection.timeout", connectionTimeout);

    client.addRequestInterceptor(new RequestAcceptEncoding());
    client.addResponseInterceptor(new ResponseContentEncoding());
    
    CookieSpecFactory csf = new CookieSpecFactory() {
      public CookieSpec newInstance(HttpParams params) {
        return new BestMatchSpecWithURLErrorLog();
      }
    };

    client.getCookieSpecs().register("bestmatchwithurl", csf);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, "bestmatchwithurl");

    if (!"".equals(proxy)) {
      StringTokenizer token = new StringTokenizer(proxy, ":");

      if (token.countTokens() == 3) {
        String proxyProtocol = token.nextToken();
        String proxyHost = token.nextToken();
        int proxyPort = Integer.parseInt(token.nextToken());

        HttpHost proxy = new HttpHost(proxyHost, proxyPort, proxyProtocol);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      } else
        System.err.println("Invalid proxy configuration: " + proxy);
    }

    if (auths.size() > 0) {

      for (Auth authObject : auths) {
        client.getCredentialsProvider().setCredentials(
            new AuthScope(authObject.getScope(), authObject.getPort()),
            new UsernamePasswordCredentials(authObject.getUserName(), authObject.getPassword()));
      }
    }

    return client;
  }
386501
public HttpClient createClient(int maxConnPerRoute, int connTimeoutMillis, int soTimeoutMillis, @Nullable String proxyHostAnPort) {
		Registry<ConnectionSocketFactory> defaultRegistry = RegistryBuilder
			.<ConnectionSocketFactory> create()
			.register("http", PlainConnectionSocketFactory.getSocketFactory())
			.register("https", SSLConnectionSocketFactory.getSocketFactory())
			.build();
		PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(defaultRegistry);
			connMgr.setDefaultMaxPerRoute(maxConnPerRoute);
		RequestConfig rCfg = RequestConfig.custom()
			.setConnectTimeout(connTimeoutMillis)
			.setSocketTimeout(soTimeoutMillis)
			.build();
		HttpClientBuilder hcb = HttpClientBuilder.create()
			.setConnectionManager(connMgr)
			.setDefaultRequestConfig(rCfg);
		if (proxyHostAnPort == null) {
			// do something?
		} else if("jvm".equalsIgnoreCase(proxyHostAnPort)) {
			SystemDefaultRoutePlanner rp = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
			hcb.setRoutePlanner(rp);
		} else {
			String[] hostAndPort = proxyHostAnPort.split(":");
			Check.illegalargument.assertTrue(hostAndPort.length < 3, "wrong hostAndPort:"+proxyHostAnPort);
			String host = hostAndPort[0];
			int port = 80;
			if (hostAndPort.length > 1) {
				port = Integer.valueOf(hostAndPort[1]);
			}
			HttpHost proxy = new HttpHost(host, port);
			hcb.setProxy(proxy);
		}
		HttpClient httpClient = hcb.build();
		return httpClient;
	}
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;
    }
579570
protected synchronized OkHttpClient getOkHttpClient() {
    if (okHttpClient == null) {
      if (isEnableDebug()) {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(logging);
        okHttpClient = httpClient.build();
      } else {
        okHttpClient = new OkHttpClient();
      }
    }
    return okHttpClient;
  }
1337798
@SneakyThrows
    private CloseableHttpClient buildHttpClient() {
        val plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
        val registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainSocketFactory)
            .register("https", this.sslSocketFactory)
            .build();

        val connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(this.maxPooledConnections);
        connectionManager.setDefaultMaxPerRoute(this.maxConnectionsPerRoute);
        connectionManager.setValidateAfterInactivity(DEFAULT_TIMEOUT);

        val httpHost = new HttpHost(InetAddress.getLocalHost());
        val httpRoute = new HttpRoute(httpHost);
        connectionManager.setMaxPerRoute(httpRoute, MAX_CONNECTIONS_PER_ROUTE);

        val requestConfig = RequestConfig.custom()
            .setSocketTimeout(this.readTimeout)
            .setConnectTimeout((int) this.connectionTimeout)
            .setConnectionRequestTimeout((int) this.connectionTimeout)
            .setCircularRedirectsAllowed(this.circularRedirectsAllowed)
            .setRedirectsEnabled(this.redirectsEnabled)
            .setAuthenticationEnabled(this.authenticationEnabled)
            .build();

        val builder = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig)
            .setSSLSocketFactory(this.sslSocketFactory)
            .setSSLHostnameVerifier(this.hostnameVerifier)
            .setRedirectStrategy(this.redirectionStrategy)
            .setDefaultCredentialsProvider(this.credentialsProvider)
            .setDefaultCookieStore(this.cookieStore)
            .setConnectionReuseStrategy(this.connectionReuseStrategy)
            .setConnectionBackoffStrategy(this.connectionBackoffStrategy)
            .setServiceUnavailableRetryStrategy(this.serviceUnavailableRetryStrategy)
            .setProxyAuthenticationStrategy(this.proxyAuthenticationStrategy)
            .setDefaultHeaders(this.defaultHeaders)
            .useSystemProperties();
        return builder.build();
    }
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);
	}
930461
def _new_conn(self):
        
        self.num_connections += 1
        log.debug("Starting new HTTP connection (%d): %s",
                  self.num_connections, self.host)

        conn = self.ConnectionCls(host=self.host, port=self.port,
                                  timeout=self.timeout.connect_timeout,
                                  strict=self.strict, **self.conn_kw)
        return conn