Example usage for com.squareup.okhttp OkHttpClient OkHttpClient

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

Introduction

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

Prototype

public OkHttpClient() 

Source Link

Usage

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//w  w  w . ja  v  a2s .  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, 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/* w ww  . j  a v a2 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  .ja v  a2  s  . com
    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.buck.cli.BuildCommand.java

License:Apache License

private int executeDistributedBuild(CommandRunnerParams params) throws IOException {
    ProjectFilesystem filesystem = params.getCell().getFilesystem();

    if (distributedBuildStateFile != null) {
        Path stateDumpPath = Paths.get(distributedBuildStateFile);
        TTransport transport;/*from  w ww . j av a 2  s . c om*/
        boolean loading = Files.exists(stateDumpPath);
        if (loading) {
            transport = new TIOStreamTransport(filesystem.newFileInputStream(stateDumpPath));
        } else {
            transport = new TIOStreamTransport(filesystem.newFileOutputStream(stateDumpPath));
        }
        transport = new TZlibTransport(transport);
        TProtocol protocol = new TTupleProtocol(transport);

        try {
            if (loading) {
                DistributedBuildState state = DistributedBuildState.load(protocol);
                BuckConfig buckConfig = state.createBuckConfig(filesystem);
                params.getBuckEventBus()
                        .post(ConsoleEvent.info("Done loading state. Aliases: %s", buckConfig.getAliases()));
            } else {
                BuckConfig buckConfig = params.getBuckConfig();
                BuildJobState jobState = DistributedBuildState.dump(buckConfig);
                jobState.write(protocol);
                transport.flush();
            }
        } catch (TException e) {
            throw new RuntimeException(e);
        } finally {
            transport.close();
        }
    }

    DistBuildConfig config = new DistBuildConfig(params.getBuckConfig());
    ClientSideSlb slb = config.getFrontendConfig().createHttpClientSideSlb(params.getClock(),
            params.getBuckEventBus());
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(config.getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS);
    client.setReadTimeout(config.getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS);
    client.setWriteTimeout(config.getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS);

    try (HttpService httpService = new LoadBalancedService(slb, client, params.getBuckEventBus());
            ThriftService<FrontendRequest, FrontendResponse> service = new ThriftOverHttpService<>(
                    ThriftOverHttpServiceConfig.of(httpService))) {
        DistributedBuild build = new DistributedBuild(new DistBuildService(service, params.getBuckEventBus()));
        return build.executeAndPrintFailuresToEventBus();
    }
}

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

License:Apache License

public ClientSideSlb createHttpClientSideSlb(Clock clock, BuckEventBus eventBus) {
    ClientSideSlbConfig.Builder configBuilder = ClientSideSlbConfig.builder()
            .setSchedulerService(Executors.newScheduledThreadPool(1)).setClock(clock)
            .setPingHttpClient(new OkHttpClient()).setServerPool(getServerPool()).setEventBus(eventBus);

    if (buckConfig.getValue(parentSection, PING_ENDPOINT).isPresent()) {
        configBuilder.setPingEndpoint(buckConfig.getValue(parentSection, PING_ENDPOINT).get());
    }/*from  w w  w .  jav a2  s  .com*/

    if (buckConfig.getValue(parentSection, TIMEOUT_MILLIS).isPresent()) {
        configBuilder
                .setConnectionTimeoutMillis(buckConfig.getLong(parentSection, TIMEOUT_MILLIS).get().intValue());
    }

    if (buckConfig.getValue(parentSection, HEALTH_CHECK_INTERVAL_MILLIS).isPresent()) {
        configBuilder.setHealthCheckIntervalMillis(
                buckConfig.getLong(parentSection, HEALTH_CHECK_INTERVAL_MILLIS).get().intValue());
    }

    if (buckConfig.getValue(parentSection, ERROR_CHECK_TIME_RANGE_MILLIS).isPresent()) {
        configBuilder.setErrorCheckTimeRangeMillis(
                buckConfig.getLong(parentSection, ERROR_CHECK_TIME_RANGE_MILLIS).get().intValue());
    }

    if (buckConfig.getValue(parentSection, MAX_ACCEPTABLE_LATENCY_MILLIS).isPresent()) {
        configBuilder.setMaxAcceptableLatencyMillis(
                buckConfig.getLong(parentSection, MAX_ACCEPTABLE_LATENCY_MILLIS).get().intValue());
    }

    if (buckConfig.getValue(parentSection, LATENCY_CHECK_TIME_RANGE_MILLIS).isPresent()) {
        configBuilder.setLatencyCheckTimeRangeMillis(
                buckConfig.getLong(parentSection, LATENCY_CHECK_TIME_RANGE_MILLIS).get().intValue());
    }

    if (buckConfig.getValue(parentSection, MAX_ERROR_PERCENTAGE).isPresent()) {
        configBuilder.setMaxErrorPercentage(buckConfig.getFloat(parentSection, MAX_ERROR_PERCENTAGE).get());
    }

    return new ClientSideSlb(configBuilder.build());
}

From source file:com.facebook.react.bridge.JSDebuggerWebSocketClient.java

License:Open Source License

public void connect(String url, JSDebuggerCallback callback) {
    if (mHttpClient != null) {
        throw new IllegalStateException("JSDebuggerWebSocketClient is already initialized.");
    }/*  w  w w  .j a v a2  s .  c o m*/
    mConnectCallback = callback;
    mHttpClient = new OkHttpClient();
    mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
    mHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
    // Disable timeouts for read
    mHttpClient.setReadTimeout(0, TimeUnit.MINUTES);

    Request request = new Request.Builder().url(url).build();
    WebSocketCall call = WebSocketCall.create(mHttpClient, request);
    call.enqueue(this);
}

From source file:com.facebook.react.bridge.webworkers.WebWorkers.java

License:Open Source License

/**
 * Utility method used to help develop web workers on debug builds. In release builds, worker
 * scripts need to be packaged with the app, but in dev mode we want to fetch/reload the worker
 * script on the fly from the packager. This method fetches the given URL *synchronously* and
 * writes it to the specified temp file.
 *
 * This is exposed from Java only because we don't want to add a C++ networking library dependency
 *
 * NB: The caller is responsible for deleting the file specified by outFileName when they're done
 * with it./*ww w . ja  v  a2  s  .c  om*/
 * NB: We write to a temp file instead of returning a String because, depending on the size of the
 * worker script, allocating the full script string on the Java heap can cause an OOM.
 */
public static void downloadScriptToFileSync(String url, String outFileName) {
    if (!ReactBuildConfig.DEBUG) {
        throw new RuntimeException(
                "For security reasons, downloading scripts is only allowed in debug builds.");
    }

    OkHttpClient client = new OkHttpClient();
    final File out = new File(outFileName);

    Request request = new Request.Builder().url(url).build();

    try {
        Response response = client.newCall(request).execute();

        Sink output = Okio.sink(out);
        Okio.buffer(response.body().source()).readAll(output);
    } catch (IOException e) {
        throw new RuntimeException("Exception downloading web worker script to file", e);
    }
}

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

License:Open Source License

public DevServerHelper(DevInternalSettings settings) {
    mSettings = settings;//from   w  w w  .ja v a  2  s.c om
    mClient = new OkHttpClient();
    mClient.setConnectTimeout(HTTP_CONNECT_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    // No read or write timeouts by default
    mClient.setReadTimeout(0, TimeUnit.MILLISECONDS);
    mClient.setWriteTimeout(0, TimeUnit.MILLISECONDS);
    mRestartOnChangePollingHandler = new Handler();
}

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

License:Open Source License

public void startPollingOnChangeEndpoint(OnServerContentChangeListener onServerContentChangeListener) {
    if (mOnChangePollingEnabled) {
        // polling already enabled
        return;/*from w  w w.j a v  a 2 s  .c  o m*/
    }
    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.facebook.react.modules.network.OkHttpClientProvider.java

License:Open Source License

public static OkHttpClient getOkHttpClient() {
    if (sClient == null) {
        // TODO: #7108751 plug in stetho
        sClient = new OkHttpClient();

        // No timeouts by default
        sClient.setConnectTimeout(0, TimeUnit.MILLISECONDS);
        sClient.setReadTimeout(0, TimeUnit.MILLISECONDS);
        sClient.setWriteTimeout(0, TimeUnit.MILLISECONDS);
    }//from   w ww.  jav a  2  s.  c o m
    return sClient;
}