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.northernwall.hadrian.HadrianBuilder.java

License:Apache License

public Hadrian builder() {
    client = new OkHttpClient();
    client.setConnectTimeout(2, TimeUnit.SECONDS);
    client.setReadTimeout(15, TimeUnit.SECONDS);
    client.setWriteTimeout(2, TimeUnit.SECONDS);
    client.setFollowSslRedirects(false);
    client.setFollowRedirects(false);//w  w w .  jav a  2s  .c o  m
    client.setConnectionPool(new ConnectionPool(5, 60 * 1000));

    if (metricRegistry == null) {
        metricRegistry = new MetricRegistry();

        final OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory
                .getOperatingSystemMXBean();
        metricRegistry.register("jvm.processCpuLoad", new Gauge<Double>() {
            @Override
            public Double getValue() {
                return osBean.getProcessCpuLoad();
            }
        });
        metricRegistry.register("jvm.systemCpuLoad", new Gauge<Double>() {
            @Override
            public Double getValue() {
                return osBean.getSystemCpuLoad();
            }
        });

        if (parameters.getBoolean("metrics.console", false)) {
            ConsoleReporter reporter = ConsoleReporter.forRegistry(metricRegistry)
                    .convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).build();
            reporter.start(1, TimeUnit.MINUTES);
        }

        String graphiteUrl = parameters.getString("metrics.graphite.url", null);
        int graphitePort = parameters.getInt("metrics.graphite.port", -1);
        if (graphiteUrl != null && graphitePort > -1) {
            Graphite graphite = new Graphite(new InetSocketAddress(graphiteUrl, graphitePort));
            GraphiteReporter reporter = GraphiteReporter.forRegistry(metricRegistry)
                    .prefixedWith(
                            parameters.getString("metrics.graphite.prefix", "hadrian") + "." + getHostname())
                    .convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS)
                    .filter(MetricFilter.ALL).build(graphite);
            reporter.start(parameters.getInt("metrics.graphite.poll", 20), TimeUnit.SECONDS);
        }
    }

    if (dataAccess == null) {
        String factoryName = parameters.getString(Const.DATA_ACCESS_FACTORY_CLASS_NAME,
                Const.DATA_ACCESS_FACTORY_CLASS_NAME_DEFAULT);
        Class c;
        try {
            c = Class.forName(factoryName);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not find DataAccess class " + factoryName);
        }
        DataAccessFactory factory;
        try {
            factory = (DataAccessFactory) c.newInstance();
        } catch (InstantiationException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not instantiation DataAccess class " + factoryName);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not access DataAccess class " + factoryName);
        }
        dataAccess = factory.createDataAccess(parameters, metricRegistry);
    }

    if (moduleArtifactHelper == null) {
        String factoryName = parameters.getString(Const.MODULE_ARTIFACT_HELPER_FACTORY_CLASS_NAME,
                Const.MODULE_ARTIFACT_HELPER_FACTORY_CLASS_NAME_DEFAULT);
        if (factoryName != null && !factoryName.isEmpty()) {
            Class c;
            try {
                c = Class.forName(factoryName);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not find ModuleArtifactHelper class " + factoryName);
            }
            ModuleArtifactHelperFactory moduleArtifactHelperFactory;
            try {
                moduleArtifactHelperFactory = (ModuleArtifactHelperFactory) c.newInstance();
            } catch (InstantiationException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not instantiation ModuleArtifactHelper class "
                                + factoryName);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not access ModuleArtifactHelper class " + factoryName);
            }
            moduleArtifactHelper = moduleArtifactHelperFactory.create(parameters, client);
        }
    }

    if (moduleConfigHelper == null) {
        String factoryName = parameters.getString(Const.MODULE_CONFIG_HELPER_FACTORY_CLASS_NAME, null);
        if (factoryName != null && !factoryName.isEmpty()) {
            Class c;
            try {
                c = Class.forName(factoryName);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not find ModuleConfigHelper class " + factoryName);
            }
            ModuleConfigHelperFactory moduleConfigHelperFactory;
            try {
                moduleConfigHelperFactory = (ModuleConfigHelperFactory) c.newInstance();
            } catch (InstantiationException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not instantiation ModuleConfigHelper class "
                                + factoryName);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not access ModuleConfigHelper class " + factoryName);
            }
            moduleConfigHelper = moduleConfigHelperFactory.create(parameters, client);
        }
    }

    configHelper = new ConfigHelper(parameters, moduleArtifactHelper, moduleConfigHelper);

    accessHelper = new AccessHelper(dataAccess);

    if (accessHandler == null) {
        String factoryName = parameters.getString(Const.ACCESS_HANDLER_FACTORY_CLASS_NAME,
                Const.ACCESS_HANDLER_FACTORY_CLASS_NAME_DEFAULT);
        Class c;
        try {
            c = Class.forName(factoryName);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException("Could not build Hadrian, could not find Access class " + factoryName);
        }
        AccessHandlerFactory accessHanlderFactory;
        try {
            accessHanlderFactory = (AccessHandlerFactory) c.newInstance();
        } catch (InstantiationException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not instantiation Access class " + factoryName);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException("Could not build Hadrian, could not access Access class " + factoryName);
        }
        accessHandler = accessHanlderFactory.create(accessHelper, parameters, metricRegistry);
    }

    if (hostDetailsHelper == null) {
        String factoryName = parameters.getString(Const.HOST_DETAILS_HELPER_FACTORY_CLASS_NAME,
                Const.HOST_DETAILS_HELPER_FACTORY_CLASS_NAME_DEFAULT);
        Class c;
        try {
            c = Class.forName(factoryName);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not find Host Details Helper class " + factoryName);
        }
        HostDetailsHelperFactory hostDetailsHelperFactory;
        try {
            hostDetailsHelperFactory = (HostDetailsHelperFactory) c.newInstance();
        } catch (InstantiationException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not instantiation Host Details Helper class "
                            + factoryName);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not access Host Details Helper class " + factoryName);
        }
        hostDetailsHelper = hostDetailsHelperFactory.create(client, parameters);
    }

    if (vipDetailsHelper == null) {
        String factoryName = parameters.getString(Const.VIP_DETAILS_HELPER_FACTORY_CLASS_NAME,
                Const.VIP_DETAILS_HELPER_FACTORY_CLASS_NAME_DEFAULT);
        if (factoryName != null && !factoryName.isEmpty()) {
            Class c;
            try {
                c = Class.forName(factoryName);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not find VIP Details Helper class " + factoryName);
            }
            VipDetailsHelperFactory vipDetailsHelperFactory;
            try {
                vipDetailsHelperFactory = (VipDetailsHelperFactory) c.newInstance();
            } catch (InstantiationException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not instantiation VIP Details Helper class "
                                + factoryName);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not access VIP Details Helper class " + factoryName);
            }
            vipDetailsHelper = vipDetailsHelperFactory.create(client, parameters, configHelper);
        }
    }

    if (calendarHelper == null) {
        String factoryName = parameters.getString(Const.CALENDAR_HELPER_FACTORY_CLASS_NAME,
                Const.CALENDAR_HELPER_FACTORY_CLASS_NAME_DEFAULT);
        Class c;
        try {
            c = Class.forName(factoryName);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not find Calendar Helper class " + factoryName);
        }
        CalendarHelperFactory calendarHelperFactory;
        try {
            calendarHelperFactory = (CalendarHelperFactory) c.newInstance();
        } catch (InstantiationException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not instantiation Calendar Helper class " + factoryName);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not access Calendar Helper class " + factoryName);
        }
        calendarHelper = calendarHelperFactory.create(parameters, client);
    }

    if (workItemSender == null) {
        String factoryName = parameters.getString(Const.WORK_ITEM_SENDER_FACTORY_CLASS_NAME,
                Const.WORK_ITEM_SENDER_FACTORY_CLASS_NAME_DEFAULT);
        Class c;
        try {
            c = Class.forName(factoryName);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not find WorkItemSender class " + factoryName);
        }
        WorkItemSenderFactory workItemSenderFactory;
        try {
            workItemSenderFactory = (WorkItemSenderFactory) c.newInstance();
        } catch (InstantiationException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not instantiation WorkItemSender class " + factoryName);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not access WorkItemSender class " + factoryName);
        }
        workItemSender = workItemSenderFactory.create(parameters, dataAccess, client, metricRegistry);
    }

    WorkItemProcessor workItemProcessor = new WorkItemProcessorImpl(dataAccess, workItemSender, metricRegistry);
    workItemSender.setWorkItemProcessor(workItemProcessor);

    DataAccessUpdater.update(dataAccess);

    return new Hadrian(parameters, client, configHelper, dataAccess, moduleArtifactHelper, moduleConfigHelper,
            accessHelper, accessHandler, hostDetailsHelper, vipDetailsHelper, calendarHelper, workItemProcessor,
            workItemSender, metricRegistry);
}

From source file:com.northernwall.hadrian.MessagingCoodinatorTest.java

License:Apache License

public MessagingCoodinatorTest() {
    client = new OkHttpClient();
    client.setConnectTimeout(2, TimeUnit.SECONDS);
    client.setReadTimeout(2, TimeUnit.SECONDS);
    client.setWriteTimeout(2, TimeUnit.SECONDS);
    client.setFollowSslRedirects(false);
    client.setFollowRedirects(false);//  w w w  .  j  a v a 2s . c om
    client.setConnectionPool(new ConnectionPool(5, 60 * 1000));
}

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

License:Apache License

@Test
public void connectionPoolIsInstrumented() throws Exception {
    server.enqueue(new MockResponse().setBody("one"));
    server.enqueue(new MockResponse().setBody("two"));
    HttpUrl baseUrl = server.url("/");

    ConnectionPool pool = new ConnectionPool(Integer.MAX_VALUE, 100L);
    new ConnectionPoolProxy(pool, emptyRunnable); // Used so that the connection pool can be properly unit tested
    rawClient.setConnectionPool(pool);//  w ww. j  a  va  2s . c o  m
    InstrumentedOkHttpClient client = new InstrumentedOkHttpClient(registry, rawClient, null);

    assertThat(registry.getGauges().get(client.metricId("connection-pool-count")).getValue()).isEqualTo(0);
    assertThat(registry.getGauges().get(client.metricId("connection-pool-count-http")).getValue()).isEqualTo(0);
    assertThat(registry.getGauges().get(client.metricId("connection-pool-count-multiplexed")).getValue())
            .isEqualTo(0);

    Request req1 = new Request.Builder().url(baseUrl).build();
    Request req2 = new Request.Builder().url(baseUrl).build();
    Response resp1 = client.newCall(req1).execute();
    Response resp2 = client.newCall(req2).execute();

    assertThat(registry.getGauges().get(client.metricId("connection-pool-count")).getValue()).isEqualTo(2);
    assertThat(registry.getGauges().get(client.metricId("connection-pool-count-http")).getValue()).isEqualTo(2);
    assertThat(registry.getGauges().get(client.metricId("connection-pool-count-multiplexed")).getValue())
            .isEqualTo(0);

    resp1.body().close();
    resp2.body().close();
    pool.evictAll();
}

From source file:com.spotify.apollo.http.client.OkHttpClientProvider.java

License:Apache License

@Override
public OkHttpClient get() {
    final OkHttpClient client = new OkHttpClient();

    //timeouts settings
    config.connectTimeoutMillis().ifPresent(millis -> client.setConnectTimeout(millis, TimeUnit.MILLISECONDS));

    config.readTimeoutMillis().ifPresent(millis -> client.setReadTimeout(millis, TimeUnit.MILLISECONDS));

    config.writeTimeoutMillis().ifPresent(millis -> client.setWriteTimeout(millis, TimeUnit.MILLISECONDS));

    // connection pool settings
    client.setConnectionPool(new ConnectionPool(
            // defaults that come from com.squareup.okhttp.ConnectionPool
            config.maxIdleConnections().orElse(5),
            config.connectionKeepAliveDurationMillis().orElse(5 * 60 * 1000)));

    // async dispatcher settings
    config.maxAsyncRequests().ifPresent(max -> client.getDispatcher().setMaxRequests(max));

    config.maxAsyncRequestsPerHost().ifPresent(max -> client.getDispatcher().setMaxRequestsPerHost(max));

    closer.register(ExecutorServiceCloser.of(client.getDispatcher().getExecutorService()));

    return client;
}

From source file:com.thanksmister.btcblue.data.api.ApiModule.java

License:Apache License

@Provides
@Singleton/*from  ww  w  . ja v a 2  s .  c o  m*/
Client provideClient(OkHttpClient client) {
    client = new OkHttpClient();
    client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout
    client.setConnectionPool(new ConnectionPool(0, 5 * 60 * 1000));
    return new OkClient(client);
}

From source file:com.tomtom.camera.api.v2.CameraApiV2.java

License:Apache License

public CameraApiV2(String baseUrl) {
    RestAdapter cameraApiAdapter = new RestAdapter.Builder()
            .setClient(new OkClient(BanditOkHttpClient.getSharedInstance())).setEndpoint(baseUrl)
            .setConverter(new CameraApiGsonConverter(ApiUtil.getDateHandlingGson())).build();
    mCameraApi = cameraApiAdapter.create(RetrofitCameraApiV2.class);

    mDownloadHttpClient = new BanditOkHttpClient();
    mDownloadHttpClient.setConnectionPool(new ConnectionPool(BanditOkHttpClient.MAX_IDLE_HTTP_CONNECTIONS,
            BanditOkHttpClient.KEEP_ALIVE_TIMEOUT_MS));
    mDownloadHttpClient.setReadTimeout(HTTP_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS);

    RestAdapter downloadApiAdapter = new RestAdapter.Builder().setClient(new OkClient(mDownloadHttpClient))
            .setEndpoint(baseUrl).setConverter(new CameraApiGsonConverter(ApiUtil.getDateHandlingGson()))
            .build();//from w w w  . j a v a  2 s  . c  o m
    mDownloadApi = downloadApiAdapter.create(RetrofitDownloadApiV2.class);
}

From source file:org.alfresco.mobile.android.application.manager.NetworkSingleton.java

License:Apache License

private NetworkSingleton() {
    httpClient = new OkHttpClient();
    httpClient.setConnectionPool(new ConnectionPool(1, 100));
    URL.setURLStreamHandlerFactory(httpClient);
}

From source file:org.alfresco.mobile.android.platform.network.NetworkSingleton.java

License:Apache License

private NetworkSingleton() {
    httpClient = new OkHttpClient();
    httpClient.setConnectionPool(new ConnectionPool(1, 100));
    httpClient.setProtocols(Arrays.asList(Protocol.HTTP_11));
    URL.setURLStreamHandlerFactory(httpClient);
}

From source file:twitter4j.AlternativeHttpClientImpl.java

License:Apache License

private void prepareOkHttpClient() {
    if (okHttpClient == null) {
        okHttpClient = new OkHttpClient();

        //set protocols
        List<Protocol> protocols = new ArrayList<Protocol>();
        protocols.add(Protocol.HTTP_1_1);
        if (sPreferHttp2)
            protocols.add(Protocol.HTTP_2);
        if (sPreferSpdy)
            protocols.add(Protocol.SPDY_3);
        okHttpClient.setProtocols(protocols);

        //connectionPool setup
        okHttpClient.setConnectionPool(new ConnectionPool(MAX_CONNECTIONS, KEEP_ALIVE_DURATION_MS));

        //redirect disable
        okHttpClient.setFollowSslRedirects(false);

        //for proxy
        if (isProxyConfigured()) {
            if (CONF.getHttpProxyUser() != null && !CONF.getHttpProxyUser().equals("")) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Proxy AuthUser: " + CONF.getHttpProxyUser());
                    logger.debug("Proxy AuthPassword: " + CONF.getHttpProxyPassword().replaceAll(".", "*"));
                }//  w w  w. j  a va2 s. c o m
                Authenticator.setDefault(new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        if (getRequestorType().equals(RequestorType.PROXY)) {
                            return new PasswordAuthentication(CONF.getHttpProxyUser(),
                                    CONF.getHttpProxyPassword().toCharArray());
                        } else {
                            return null;
                        }
                    }
                });
            }
            final Proxy proxy = new Proxy(Proxy.Type.HTTP,
                    InetSocketAddress.createUnresolved(CONF.getHttpProxyHost(), CONF.getHttpProxyPort()));
            if (logger.isDebugEnabled()) {
                logger.debug("Opening proxied connection(" + CONF.getHttpProxyHost() + ":"
                        + CONF.getHttpProxyPort() + ")");
            }
            okHttpClient.setProxy(proxy);
        }

        //connection timeout
        if (CONF.getHttpConnectionTimeout() > 0) {
            okHttpClient.setConnectTimeout(CONF.getHttpConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        //read timeout
        if (CONF.getHttpReadTimeout() > 0) {
            okHttpClient.setReadTimeout(CONF.getHttpReadTimeout(), TimeUnit.MILLISECONDS);
        }
    }
}