Example usage for com.squareup.okhttp OkHttpClient getConnectionPool

List of usage examples for com.squareup.okhttp OkHttpClient getConnectionPool

Introduction

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

Prototype

public ConnectionPool getConnectionPool() 

Source Link

Usage

From source file:com.raskasa.dropwizard.okhttp.OkHttpClientBuilder.java

License:Apache License

/** Builds the {@link OkHttpClient}. */
public OkHttpClient build() {
    final OkHttpClient rawClient = new OkHttpClient();
    if (configuration.getConnectTimeout() > 0L) {
        rawClient.setConnectTimeout(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
    }/*from w  w w .j ava2 s  . c  o m*/
    if (configuration.getReadTimeout() > 0L) {
        rawClient.setReadTimeout(configuration.getReadTimeout(), TimeUnit.MILLISECONDS);
    }
    if (configuration.getWriteTimeout() > 0L) {
        rawClient.setWriteTimeout(configuration.getWriteTimeout(), TimeUnit.MILLISECONDS);
    }
    if (configuration.getCacheDir() != null && configuration.getCacheSize() > 0L) {
        rawClient.setCache(new Cache(configuration.getCacheDir(), configuration.getCacheSize()));
    }
    final OkHttpClient client = InstrumentedOkHttpClients.create(registry, rawClient, name);

    // If the environment is present, we tie the client with the server lifecycle
    if (environment != null) {
        environment.lifecycle().manage(new Managed() {
            @Override
            public void start() throws Exception {
            }

            @Override
            public void stop() throws Exception {
                client.getConnectionPool().evictAll();
            }
        });
    }
    return client;
}

From source file:com.raskasa.metrics.okhttp.InstrumentedOkHttpClientsTest.java

License:Apache License

private void assertThatClientsAreEqual(OkHttpClient clientA, OkHttpClient clientB) {
    assertThat(clientA.getDispatcher()).isEqualTo(clientB.getDispatcher());
    assertThat(clientA.getProxy()).isEqualTo(clientB.getProxy());
    assertThat(clientA.getProtocols()).isEqualTo(clientB.getProtocols());
    assertThat(clientA.getConnectionSpecs()).isEqualTo(clientB.getConnectionSpecs());
    assertThat(clientA.getProxySelector()).isEqualTo(clientB.getProxySelector());
    assertThat(clientA.getCookieHandler()).isEqualTo(clientB.getCookieHandler());
    assertThat(clientA.getCache()).isEqualTo(clientB.getCache());
    assertThat(clientA.getSocketFactory()).isEqualTo(clientB.getSocketFactory());
    assertThat(clientA.getSslSocketFactory()).isEqualTo(clientB.getSslSocketFactory());
    assertThat(clientA.getHostnameVerifier()).isEqualTo(clientB.getHostnameVerifier());
    assertThat(clientA.getCertificatePinner()).isEqualTo(clientB.getCertificatePinner());
    assertThat(clientA.getAuthenticator()).isEqualTo(clientB.getAuthenticator());
    assertThat(clientA.getConnectionPool()).isEqualTo(clientB.getConnectionPool());
    assertThat(clientA.getFollowSslRedirects()).isEqualTo(clientB.getFollowSslRedirects());
    assertThat(clientA.getFollowRedirects()).isEqualTo(clientB.getFollowRedirects());
    assertThat(clientA.getRetryOnConnectionFailure()).isEqualTo(clientB.getRetryOnConnectionFailure());
    assertThat(clientA.getConnectTimeout()).isEqualTo(clientB.getConnectTimeout());
    assertThat(clientA.getReadTimeout()).isEqualTo(clientB.getReadTimeout());
    assertThat(clientA.getWriteTimeout()).isEqualTo(clientB.getWriteTimeout());
}

From source file:io.fabric8.devops.connector.DevOpsConnector.java

License:Apache License

protected void createGerritRepo(String repoName, String gerritUser, String gerritPwd,
        String gerritGitInitialCommit, String gerritGitRepoDescription) throws Exception {

    // lets add defaults if not env vars
    final String username = Strings.isNullOrBlank(gerritUser) ? "admin" : gerritUser;
    final String password = Strings.isNullOrBlank(gerritPwd) ? "secret" : gerritPwd;

    log.info("A Gerrit git repo will be created for this name : " + repoName);

    String gerritAddress = KubernetesHelper.getServiceURL(kubernetes, ServiceNames.GERRIT, namespace, "http",
            true);//from   w w w  .j a  v a2s .  co m
    log.info("Found gerrit address: " + gerritAddress + " for namespace: " + namespace
            + " on Kubernetes address: " + kubernetes.getMasterUrl());

    if (Strings.isNullOrBlank(gerritAddress)) {
        throw new Exception("No address for service " + ServiceNames.GERRIT + " in namespace: " + namespace
                + " on Kubernetes address: " + kubernetes.getMasterUrl());
    }

    String GERRIT_URL = gerritAddress + "/a/projects/" + repoName;

    OkHttpClient client = new OkHttpClient();
    if (isNotNullOrEmpty(gerritUser) && isNotNullOrEmpty(gerritPwd)) {
        client.setAuthenticator(new Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                List<Challenge> challenges = response.challenges();
                Request request = response.request();
                for (int i = 0, size = challenges.size(); i < size; i++) {
                    Challenge challenge = challenges.get(i);
                    if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                        continue;

                    String credential = Credentials.basic(username, password);
                    return request.newBuilder().header("Authorization", credential).build();
                }
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
    }

    System.out.println("Requesting : " + GERRIT_URL);

    try {
        CreateRepositoryDTO createRepoDTO = new CreateRepositoryDTO();
        createRepoDTO.setDescription(gerritGitRepoDescription);
        createRepoDTO.setName(repoName);
        createRepoDTO.setCreate_empty_commit(Boolean.valueOf(gerritGitInitialCommit));

        RequestBody body = RequestBody.create(JSON, MAPPER.writeValueAsString(createRepoDTO));
        Request request = new Request.Builder().post(body).url(GERRIT_URL).build();
        Response response = client.newCall(request).execute();
        System.out.println("responseBody : " + response.body().string());

    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (client != null && client.getConnectionPool() != null) {
            client.getConnectionPool().evictAll();
        }
    }
}

From source file:io.fabric8.docker.client.utils.SSLUtils.java

License:Apache License

public static boolean isHttpsAvailable(Config config) {
    Config sslConfig = new ConfigBuilder(config)
            .withDockerUrl(URLUtils.withProtocol(config.getDockerUrl(), Config.HTTPS_PROTOCOL_PREFIX))
            .withRequestTimeout(1000).withConnectionTimeout(1000).build();

    OkHttpClient client = HttpClientUtils.createHttpClient(config);
    Response response = null;//from  w  w w  . j ava  2s .  c om
    try {
        Request request = new Request.Builder().get().url(sslConfig.getDockerUrl()).build();
        response = client.newCall(request).execute();
        return response.handshake() != null;
    } catch (Throwable t) {
        LOG.warn("SSL handshake failed. Falling back to insecure connection.");
    } finally {
        if (response != null) {
            try {
                response.body().close();
            } catch (IOException e) {
                //ignore
            }
        }
        if (client != null && client.getConnectionPool() != null) {
            client.getConnectionPool().evictAll();
        }
    }
    return false;
}

From source file:io.fabric8.kubernetes.client.internal.SSLUtils.java

License:Apache License

public static boolean isHttpsAvailable(Config config) {
    Config sslConfig = new ConfigBuilder(config)
            .withMasterUrl(Config.HTTPS_PROTOCOL_PREFIX + config.getMasterUrl()).withRequestTimeout(1000)
            .withConnectionTimeout(1000).build();

    OkHttpClient client = HttpClientUtils.createHttpClient(config);
    try {//from   www  .  ja v  a  2 s  .  c o m
        Request request = new Request.Builder().get().url(sslConfig.getMasterUrl()).build();
        Response response = client.newCall(request).execute();
        try (ResponseBody body = response.body()) {
            return response.isSuccessful();
        }
    } catch (Throwable t) {
        LOG.warn("SSL handshake failed. Falling back to insecure connection.");
    } finally {
        if (client != null && client.getConnectionPool() != null) {
            client.getConnectionPool().evictAll();
        }
    }
    return false;
}

From source file:twitter4j.Http2ClientTest.java

License:Apache License

public void testNoPreferOption() throws Exception {
    AlternativeHttpClientImpl http = callOembed();

    // check HTTP/2.0
    Field f = http.getClass().getDeclaredField("okHttpClient");
    f.setAccessible(true);//from  ww  w  . j ava 2s  .  c  o m
    OkHttpClient client = (OkHttpClient) f.get(http);
    assertNotNull("ensure that OkHttpClient is used", client);

    ConnectionPool p = client.getConnectionPool();
    assertEquals(1, p.getConnectionCount());
    assertEquals(0, p.getHttpConnectionCount());
    assertEquals(1, p.getMultiplexedConnectionCount());

    assertEquals("h2", http.getLastRequestProtocol());
}

From source file:twitter4j.Http2ClientTest.java

License:Apache License

public void testSpdy() throws Exception {
    AlternativeHttpClientImpl.sPreferSpdy = true;
    AlternativeHttpClientImpl.sPreferHttp2 = false;
    AlternativeHttpClientImpl http = callOembed();

    // check SPDY
    Field f = http.getClass().getDeclaredField("okHttpClient");
    f.setAccessible(true);/*from   www  . j a  v a2  s  . c  om*/
    OkHttpClient client = (OkHttpClient) f.get(http);
    assertNotNull("ensure that OkHttpClient is used", client);

    ConnectionPool p = client.getConnectionPool();
    assertEquals(1, p.getConnectionCount());
    assertEquals(0, p.getHttpConnectionCount());
    assertEquals(1, p.getMultiplexedConnectionCount());

    assertEquals("spdy/3.1", http.getLastRequestProtocol());
}

From source file:twitter4j.Http2ClientTest.java

License:Apache License

public void testHttp2() throws Exception {
    AlternativeHttpClientImpl.sPreferSpdy = false;
    AlternativeHttpClientImpl.sPreferHttp2 = true;
    AlternativeHttpClientImpl http = callOembed();

    // check HTTP/2.0
    Field f = http.getClass().getDeclaredField("okHttpClient");
    f.setAccessible(true);/*from w ww . j av  a  2s  . c  o m*/
    OkHttpClient client = (OkHttpClient) f.get(http);
    assertNotNull("ensure that OkHttpClient is used", client);

    ConnectionPool p = client.getConnectionPool();
    assertEquals(1, p.getConnectionCount());
    assertEquals(0, p.getHttpConnectionCount());
    assertEquals(1, p.getMultiplexedConnectionCount());

    assertEquals("h2", http.getLastRequestProtocol());
}

From source file:twitter4j.Http2ClientTest.java

License:Apache License

public void testNoSpdy() throws Exception {
    AlternativeHttpClientImpl.sPreferSpdy = false;
    AlternativeHttpClientImpl.sPreferHttp2 = false;

    AlternativeHttpClientImpl http = callOembed();

    // check not SPDY
    Field f = http.getClass().getDeclaredField("okHttpClient");
    f.setAccessible(true);/*from   ww w .  j  a v a2s  .c o m*/
    OkHttpClient client = (OkHttpClient) f.get(http);

    ConnectionPool p = client.getConnectionPool();
    assertEquals(1, p.getConnectionCount());
    assertEquals(1, p.getHttpConnectionCount());
    assertEquals(0, p.getMultiplexedConnectionCount());

    assertEquals("http/1.1", http.getLastRequestProtocol());
}

From source file:twitter4j.SpdyHttpClientTest.java

License:Apache License

public void testNoPreferOption() throws Exception {
    AlternativeHttpClientImpl http = callOembed();

    // check HTTP/2.0
    Field f = http.getClass().getDeclaredField("client");
    f.setAccessible(true);/*from   w  ww . j  a v a2 s .c  o  m*/
    OkHttpClient client = (OkHttpClient) f.get(http);
    assertNotNull("ensure that OkHttpClient is used", client);

    ConnectionPool p = client.getConnectionPool();
    assertEquals(1, p.getConnectionCount());
    assertEquals(0, p.getHttpConnectionCount());
    assertEquals(1, p.getSpdyConnectionCount());

    assertEquals("HTTP-draft-09/2.0", http.getLastRequestProtocol());
}