Example usage for com.squareup.okhttp ConnectionPool ConnectionPool

List of usage examples for com.squareup.okhttp ConnectionPool ConnectionPool

Introduction

In this page you can find the example usage for com.squareup.okhttp ConnectionPool ConnectionPool.

Prototype

public ConnectionPool(int maxIdleConnections, long keepAliveDurationMs) 

Source Link

Usage

From source file:com.android.mms.service_alt.MmsHttpClient.java

License:Apache License

/**
 * Open an HTTP connection//  www .  j a  v  a  2 s.c  o m
 *
 * TODO: The following code is borrowed from android.net.Network.openConnection
 * Once that method supports proxy, we should use that instead
 * Also we should remove the associated HostResolver and ConnectionPool from
 * MmsNetworkManager
 *
 * @param url The URL to connect to
 * @param proxy The proxy to use
 * @return The opened HttpURLConnection
 * @throws MalformedURLException If URL is malformed
 */
private HttpURLConnection openConnection(URL url, final Proxy proxy) throws MalformedURLException {
    final String protocol = url.getProtocol();
    OkHttpClient okHttpClient;
    if (protocol.equals("http")) {
        okHttpClient = new OkHttpClient();
        okHttpClient.setFollowRedirects(false);
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        okHttpClient.setProxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                if (proxy != null) {
                    return Arrays.asList(proxy);
                } else {
                    return new ArrayList<Proxy>();
                }
            }

            @Override
            public void connectFailed(URI uri, SocketAddress address, IOException failure) {

            }
        });
        okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
        okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
        okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
        okHttpClient.setSocketFactory(SocketFactory.getDefault());
        Internal.instance.setNetwork(okHttpClient, mHostResolver);

        if (proxy != null) {
            okHttpClient.setProxy(proxy);
        }

        return new HttpURLConnectionImpl(url, okHttpClient);
    } else if (protocol.equals("https")) {
        okHttpClient = new OkHttpClient();
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
        okHttpClient.setHostnameVerifier(verifier);
        okHttpClient.setSslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory());
        okHttpClient.setProxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                return Arrays.asList(proxy);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress address, IOException failure) {

            }
        });
        okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
        okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
        okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
        Internal.instance.setNetwork(okHttpClient, mHostResolver);

        return new HttpsURLConnectionImpl(url, okHttpClient);
    } else {
        throw new MalformedURLException("Invalid URL or unrecognized protocol " + protocol);
    }
}

From source file:com.android.mms.service_alt.MmsNetworkManager.java

License:Apache License

private ConnectionPool getOrCreateConnectionPoolLocked() {
    if (mConnectionPool == null) {
        mConnectionPool = new ConnectionPool(httpMaxConnections, httpKeepAliveDurationMs);
    }// w ww  .  j ava  2s  .  co m
    return mConnectionPool;
}

From source file:com.cloudant.client.org.lightcouch.CouchDbClient.java

License:Open Source License

CouchDbClient(CouchDbConfig config) {
    final CouchDbProperties props = config.getProperties();

    try {//from  w ww . ja va  2  s  .co m
        this.clientUri = props.getCouchDbURL().toURI();
    } catch (URISyntaxException e) {
        throw new RuntimeException("Error converting account URL to URI.", e);
    }

    this.gson = GsonHelper.initGson(new GsonBuilder()).create();

    // If OkHttp is available then use it for connection pooling, otherwise default to the
    // JVM built-in pooling for HttpUrlConnection
    if (OkHttpClientHttpUrlConnectionFactory.isOkUsable()) {
        log.config("Using OkHttp");
        OkHttpClientHttpUrlConnectionFactory factory = new OkHttpClientHttpUrlConnectionFactory();
        final int maxConns = props.getMaxConnections();
        if (maxConns > 0) {
            log.config("Setting max connections to " + maxConns);
            //keep connections open for as long as possible, anything over 2.5 minutes will be
            //longer than the server so we'll use a 3 minute timeout
            ConnectionPool pool = new ConnectionPool(maxConns, TimeUnit.MINUTES.toMillis(3));
            factory.getOkHttpClient().setConnectionPool(pool);
        }
        this.factory = factory;
    } else {
        log.config("Using built-in HttpUrlConnection");
        this.factory = new DefaultHttpUrlConnectionFactory();
    }

    //set the proxy if it has been configured
    if (props.getProxyURL() != null) {
        factory.setProxy(props.getProxyURL());
    }

    this.requestInterceptors = new ArrayList<HttpConnectionRequestInterceptor>();
    this.responseInterceptors = new ArrayList<HttpConnectionResponseInterceptor>();

    if (props.getRequestInterceptors() != null) {
        this.requestInterceptors.addAll(props.getRequestInterceptors());
    }

    if (props.getResponseInterceptors() != null) {
        this.responseInterceptors.addAll(props.getResponseInterceptors());
    }
}

From source file:com.facebook.buck.artifact_cache.ArtifactCaches.java

License:Apache License

private static ArtifactCache createHttpArtifactCache(ArtifactCacheBuckConfig buckConfig,
        BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem) {
    URI uri = buckConfig.getHttpCacheUrl();
    int timeoutSeconds = buckConfig.getHttpCacheTimeoutSeconds();
    boolean doStore = buckConfig.getHttpCacheReadMode();
    final String host = buckConfig.getHostToReportToRemoteCacheServer();

    // Setup the defaut client to use.
    OkHttpClient client = new OkHttpClient();
    client.networkInterceptors().add(new Interceptor() {
        @Override//ww w .ja  v a  2s  .  c o  m
        public Response intercept(Chain chain) throws IOException {
            return chain.proceed(chain.request().newBuilder()
                    .addHeader("X-BuckCache-User", System.getProperty("user.name", "<unknown>"))
                    .addHeader("X-BuckCache-Host", host).build());
        }
    });
    client.setConnectTimeout(timeoutSeconds, TimeUnit.SECONDS);
    client.setConnectionPool(new ConnectionPool(
            // It's important that this number is greater than the `-j` parallelism,
            // as if it's too small, we'll overflow the reusable connection pool and
            // start spamming new connections.  While this isn't the best location,
            // the other current option is setting this wherever we construct a `Build`
            // object and have access to the `-j` argument.  However, since that is
            // created in several places leave it here for now.
            /* maxIdleConnections */ 200, /* keepAliveDurationMs */ TimeUnit.MINUTES.toMillis(5)));

    // For fetches, use a client with a read timeout.
    OkHttpClient fetchClient = client.clone();
    fetchClient.setReadTimeout(timeoutSeconds, TimeUnit.SECONDS);

    return new HttpArtifactCache("http", fetchClient, client, uri, doStore, projectFilesystem, buckEventBus);
}

From source file:com.facebook.buck.cli.ArtifactCaches.java

License:Apache License

private static ArtifactCache createHttpArtifactCache(ArtifactCacheBuckConfig buckConfig,
        BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem) {
    URL url = buckConfig.getHttpCacheUrl();
    int timeoutSeconds = buckConfig.getHttpCacheTimeoutSeconds();
    boolean doStore = buckConfig.getHttpCacheReadMode();
    final String host = buckConfig.getHostToReportToRemoteCacheServer();

    // Setup the defaut client to use.
    OkHttpClient client = new OkHttpClient();
    client.networkInterceptors().add(new Interceptor() {
        @Override//from w  w w  . j  a v a  2 s .  c  om
        public Response intercept(Chain chain) throws IOException {
            return chain.proceed(chain.request().newBuilder()
                    .addHeader("X-BuckCache-User", System.getProperty("user.name", "<unknown>"))
                    .addHeader("X-BuckCache-Host", host).build());
        }
    });
    client.setConnectTimeout(timeoutSeconds, TimeUnit.SECONDS);
    client.setConnectionPool(new ConnectionPool(
            // It's important that this number is greater than the `-j` parallelism,
            // as if it's too small, we'll overflow the reusable connection pool and
            // start spamming new connections.  While this isn't the best location,
            // the other current option is setting this wherever we construct a `Build`
            // object and have access to the `-j` argument.  However, since that is
            // created in several places leave it here for now.
            /* maxIdleConnections */ 200, /* keepAliveDurationMs */ TimeUnit.MINUTES.toMillis(5)));

    // For fetches, use a client with a read timeout.
    OkHttpClient fetchClient = client.clone();
    fetchClient.setReadTimeout(timeoutSeconds, TimeUnit.SECONDS);

    return new HttpArtifactCache("http", fetchClient, client, url, doStore, projectFilesystem, buckEventBus,
            Hashing.crc32());
}

From source file:com.facebook.buck.cli.BuckConfig.java

License:Apache License

private ArtifactCache createHttpArtifactCache() {
    URL url;/*from   w w w . j a  v a 2 s .c  o  m*/
    try {
        url = new URL(getValue("cache", "http_url").or(DEFAULT_HTTP_URL));
    } catch (MalformedURLException e) {
        throw new HumanReadableException(e, "Malformed [cache]http_url: %s", e.getMessage());
    }

    int timeoutSeconds = Integer
            .parseInt(getValue("cache", "http_timeout_seconds").or(DEFAULT_HTTP_CACHE_TIMEOUT_SECONDS));

    boolean doStore = readCacheMode("http_mode", DEFAULT_HTTP_CACHE_MODE);

    // Setup the defaut client to use.
    OkHttpClient client = new OkHttpClient();
    final String localhost = getLocalhost();
    client.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            return chain.proceed(chain.request().newBuilder()
                    .addHeader("X-BuckCache-User", System.getProperty("user.name", "<unknown>"))
                    .addHeader("X-BuckCache-Host", localhost).build());
        }
    });
    client.setConnectTimeout(timeoutSeconds, TimeUnit.SECONDS);
    client.setConnectionPool(new ConnectionPool(
            // It's important that this number is greater than the `-j` parallelism,
            // as if it's too small, we'll overflow the reusable connection pool and
            // start spamming new connections.  While this isn't the best location,
            // the other current option is setting this wherever we construct a `Build`
            // object and have access to the `-j` argument.  However, since that is
            // created in several places leave it here for now.
            /* maxIdleConnections */ 200, /* keepAliveDurationMs */ TimeUnit.MINUTES.toMillis(5)));

    // For fetches, use a client with a read timeout.
    OkHttpClient fetchClient = client.clone();
    fetchClient.setReadTimeout(timeoutSeconds, TimeUnit.SECONDS);

    return new HttpArtifactCache(fetchClient, client, url, doStore, projectFilesystem, Hashing.crc32());
}

From source file:com.facebook.react.devsupport.DevServerHelper.java

License:Open Source License

public void startPollingOnChangeEndpoint(OnServerContentChangeListener onServerContentChangeListener) {
    if (mOnChangePollingEnabled) {
        // polling already enabled
        return;// w w  w .j ava 2  s  .com
    }
    mOnChangePollingEnabled = true;
    mOnServerContentChangeListener = onServerContentChangeListener;
    mOnChangePollingClient = new OkHttpClient();
    mOnChangePollingClient.setConnectionPool(new ConnectionPool(1, LONG_POLL_KEEP_ALIVE_DURATION_MS))
            .setConnectTimeout(HTTP_CONNECT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    enqueueOnChangeEndpointLongPolling();
}

From source file:com.netflix.spinnaker.echo.config.Front50Config.java

License:Apache License

@Bean
public OkHttpClient okHttpClient(OkHttpClientConfiguration okHttpClientConfig) {
    OkHttpClient cli = okHttpClientConfig.create();
    cli.setConnectionPool(new ConnectionPool(maxIdleConnections, keepAliveDurationMs));
    cli.setRetryOnConnectionFailure(retryOnConnectionFailure);
    return cli;/*from w w w. j  a va2 s  .c o  m*/
}

From source file:com.netflix.spinnaker.fiat.config.RetrofitConfig.java

License:Apache License

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
OkClient okClient() {/*from  www . ja va2s .c om*/
    val client = okHttpClientConfig.create();
    client.setConnectionPool(new ConnectionPool(maxIdleConnections, keepAliveDurationMs));
    client.setRetryOnConnectionFailure(retryOnConnectionFailure);
    client.interceptors().add(new RetryingInterceptor(maxElapsedBackoffMs));
    return new OkClient(client);
}

From source file:com.netflix.spinnaker.halyard.config.config.v1.RetrofitConfig.java

License:Apache License

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
OkClient okClient() {/*from  ww w  .  j av a  2  s .co m*/
    OkHttpClient client = okHttpClientConfig.create();
    client.setConnectionPool(new ConnectionPool(maxIdleConnections, keepAliveDurationMs));
    client.setRetryOnConnectionFailure(retryOnConnectionFailure);
    return new OkClient(client);
}