Example usage for com.squareup.okhttp OkHttpClient setReadTimeout

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

Introduction

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

Prototype

public void setReadTimeout(long timeout, TimeUnit unit) 

Source Link

Document

Sets the default read timeout for new connections.

Usage

From source file:io.fabric8.docker.client.impl.PullImage.java

License:Apache License

@Override
public OutputHandle fromRegistry() {
    try {/*from   w ww.  j a  v  a  2s.  c o  m*/
        StringBuilder sb = new StringBuilder().append(getOperationUrl(CREATE_OPERATION)).append(Q)
                .append(FROM_IMAGE).append(EQUALS).append(name);

        if (Utils.isNotNullOrEmpty(tag)) {
            sb.append(A).append(TAG).append(EQUALS).append(tag);
        }

        AuthConfig authConfig = RegistryUtils.getConfigForImage(name, config);
        Request request = new Request.Builder()
                .header("X-Registry-Auth",
                        new String(Base64.encodeBase64(JSON_MAPPER
                                .writeValueAsString(authConfig != null ? authConfig : new AuthConfig())
                                .getBytes("UTF-8")), "UTF-8"))
                .post(RequestBody.create(MEDIA_TYPE_TEXT, EMPTY)).url(sb.toString()).build();

        OkHttpClient clone = client.clone();
        clone.setReadTimeout(config.getImagePullTimeout(), TimeUnit.MILLISECONDS);
        PullImageHandle handle = new PullImageHandle(out, config.getImagePushTimeout(), TimeUnit.MILLISECONDS,
                listener);
        clone.newCall(request).enqueue(handle);
        return handle;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.docker.client.impl.PushImage.java

License:Apache License

@Override
public OutputHandle toRegistry() {
    try {/*  ww  w .j a  va2 s  .  co m*/
        StringBuilder sb = new StringBuilder().append(getOperationUrl(PUSH_OPERATION));
        sb.append(Q).append(FORCE).append(EQUALS).append(force);
        if (Utils.isNotNullOrEmpty(tag)) {
            sb.append(A).append(TAG).append(EQUALS).append(tag);
        }
        AuthConfig authConfig = RegistryUtils.getConfigForImage(name, config);
        RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, "{}");
        Request request = new Request.Builder()
                .header("X-Registry-Auth",
                        new String(Base64.encodeBase64(JSON_MAPPER
                                .writeValueAsString(authConfig != null ? authConfig : new AuthConfig())
                                .getBytes("UTF-8")), "UTF-8"))
                .post(body).url(sb.toString()).build();

        OkHttpClient clone = client.clone();
        clone.setReadTimeout(config.getImagePushTimeout(), TimeUnit.MILLISECONDS);
        PushImageHandle handle = new PushImageHandle(out, config.getImagePushTimeout(), TimeUnit.MILLISECONDS,
                listener);
        clone.newCall(request).enqueue(handle);
        return handle;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

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

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {/*from  ww w .j  a  va  2  s  . c  o  m*/
        OkHttpClient httpClient = new OkHttpClient();

        httpClient.setConnectionPool(ConnectionPool.getDefault());
        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        if (usesUnixSocket(config)) {
            URL masterURL = new URL(config.getDockerUrl().replaceFirst(UNIX_SCHEME, FILE_SCHEME));
            httpClient.setSocketFactory(new UnixSocketFactory(masterURL.getFile()));
            config.setDockerUrl(UNIX_FAKE_URL);
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    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(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getDockerUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getDockerUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new DockerClientException("Invalid proxy server configuration", e);
            }
        }

        return httpClient;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.kubernetes.client.dsl.internal.PodOperationsImpl.java

License:Apache License

@Override
public ExecWatch exec(String... command) {
    StringBuilder sb = new StringBuilder();
    String[] actualCommands = command.length >= 1 ? command : EMPTY_COMMAND;

    sb.append("exec?command=");

    boolean first = true;
    for (String cmd : actualCommands) {
        if (first) {
            first = false;//  www .  j  av  a2  s  .c o  m
        } else {
            sb.append("&command=");
        }
        sb.append(cmd);
    }

    if (containerId != null && !containerId.isEmpty()) {
        sb.append("&container=").append(containerId);
    }
    if (withTTY) {
        sb.append("&tty=true");
    }
    if (in != null || inPipe != null) {
        sb.append("&stdin=true");
    }
    if (out != null || outPipe != null) {
        sb.append("&stdout=true");
    }
    if (err != null || errPipe != null) {
        sb.append("&stderr=true");
    }

    try {
        URL url = new URL(URLUtils.join(getResourceUrl().toString(), sb.toString()));
        Request.Builder r = new Request.Builder().url(url).get();
        OkHttpClient clone = client.clone();
        clone.setReadTimeout(0, TimeUnit.MILLISECONDS);
        WebSocketCall webSocketCall = WebSocketCall.create(clone, r.build());
        final ExecWebSocketListener execWebSocketListener = new ExecWebSocketListener(in, out, err, inPipe,
                outPipe, errPipe, execListener);
        webSocketCall.enqueue(execWebSocketListener);
        execWebSocketListener.waitUntilReady();
        return execWebSocketListener;
    } catch (Throwable t) {
        throw KubernetesClientException.launderThrowable(t);
    }
}

From source file:io.fabric8.kubernetes.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {//from  w  ww. ja v a  2  s . c o  m
        OkHttpClient httpClient = new OkHttpClient();

        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    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(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getMasterUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new KubernetesClientException("Invalid proxy server configuration", e);
            }
        }

        if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
            httpClient.networkInterceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent())
                            .build();
                    return chain.proceed(agent);
                }
            });
        }

        return httpClient;
    } catch (Exception e) {
        throw KubernetesClientException.launderThrowable(e);
    }
}

From source file:io.takari.aether.okhttp.OkHttpAetherClient.java

License:Open Source License

public OkHttpAetherClient(AetherClientConfig config) {
    this.config = config;

    // headers are modified during http auth handshake
    // make a copy to avoid cross-talk among client instances
    headers = new HashMap<String, String>();
    if (config.getHeaders() != null) {
        headers.putAll(config.getHeaders());
    }//from   w  w w  .jav  a 2 s.c o  m

    //
    // If the User-Agent has been overriden in the headers then we will use that
    //
    if (!headers.containsKey("User-Agent")) {
        headers.put("User-Agent", config.getUserAgent());
    }

    OkHttpClient httpClient = new OkHttpClient();
    httpClient.setProxy(getProxy(config.getProxy()));
    httpClient.setHostnameVerifier(OkHostnameVerifier.INSTANCE);
    httpClient.setAuthenticator(NOAUTH); // see #authenticate below
    httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
    httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
    httpClient.setSslSocketFactory(config.getSslSocketFactory());
    this.httpClient = httpClient;
}

From source file:library.util.OkHttpStack.java

License:Apache License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    Builder okHttpRequestBuilder = new Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/*from   ww w. ja  va  2  s. com*/
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:me.drakeet.meizhi.DrakeetRetrofit.java

License:Open Source License

DrakeetRetrofit() {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(12, TimeUnit.SECONDS);

    RestAdapter.Builder builder = new RestAdapter.Builder();
    builder.setClient(new OkClient(client)).setLogLevel(RestAdapter.LogLevel.FULL)
            .setEndpoint("http://gank.io/api").setConverter(new GsonConverter(gson));
    RestAdapter gankRestAdapter = builder.build();
    builder.setEndpoint("https://leancloud.cn:443/1.1/classes");
    RestAdapter drakeetRestAdapter = builder.build();
    gankService = gankRestAdapter.create(GankApi.class);
    drakeetService = drakeetRestAdapter.create(DrakeetApi.class);
}

From source file:me.hoangchunghien.popularmovies.data.api.ApiModule.java

License:Apache License

@Provides
@Singleton//from  w ww  .  j  av a  2  s.c o  m
OkHttpClient provideOkHttpClient(@ForApplication Context app) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, SECONDS);
    client.setReadTimeout(10, SECONDS);
    client.setWriteTimeout(10, SECONDS);

    // Install an HTTP cache in the application cache directory.
    File cacheDir = new File(app.getCacheDir(), "http");
    Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
    client.setCache(cache);

    return client;
}

From source file:meteor.operations.Meteor.java

License:Apache License

/**
 * Opens a connection to the server over websocket
 *
 * @param isReconnect whether this is a re-connect attempt or not
 *///ww w. j  a  v  a  2 s . co m
public void openConnection(final boolean isReconnect) {

    if (isReconnect) {
        if (isConnected()) {
            connect(mSessionID);
            return;
        }
    }

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(1, TimeUnit.MINUTES);
    client.setReadTimeout(1, TimeUnit.MINUTES);
    client.setWriteTimeout(1, TimeUnit.MINUTES);
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
    client.networkInterceptors().add(loggingInterceptor);

    Request request = new Request.Builder().url(mServerUri).build();
    WebSocketCall.create(client, request).enqueue(mWebSocketObserver);
}