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:org.hawkular.agent.monitor.util.BaseHttpClientGenerator.java

License:Apache License

public BaseHttpClientGenerator(Configuration configuration) {
    this.configuration = configuration;

    OkHttpClient httpClient = new OkHttpClient();

    /* set the timeouts explicitly only if they were set through the config */
    configuration.getConnectTimeoutSeconds()
            .ifPresent(timeout -> httpClient.setConnectTimeout(timeout.intValue(), TimeUnit.SECONDS));
    configuration.getReadTimeoutSeconds()
            .ifPresent(timeout -> httpClient.setReadTimeout(timeout.intValue(), TimeUnit.SECONDS));

    if (this.configuration.isUseSSL()) {
        SSLContext theSslContextToUse;

        if (this.configuration.getSslContext() == null) {
            if (this.configuration.getKeystorePath() != null) {
                theSslContextToUse = buildSSLContext(this.configuration.getKeystorePath(),
                        this.configuration.getKeystorePassword());
            } else {
                theSslContextToUse = null; // rely on the JVM default
            }/*from  w w  w .ja v a 2s  .c  o m*/
        } else {
            theSslContextToUse = this.configuration.getSslContext();
        }

        if (theSslContextToUse != null) {
            httpClient.setSslSocketFactory(theSslContextToUse.getSocketFactory());
        }

        // does not perform any hostname verification when looking at the remote end's cert
        /*
        httpClient.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            log.debugf("HTTP client is blindly approving cert for [%s]", hostname);
            return true;
        }
        });
        */
    }

    this.httpClient = httpClient;
}

From source file:org.hawkular.client.android.util.WebSocketClientGenerator.java

License:Apache License

public WebSocketClientGenerator(Configuration configuration) {
    this.configuration = configuration;

    OkHttpClient httpClient = new OkHttpClient();

    if (configuration.getConnectTimeoutSeconds() != -1) {
        httpClient.setConnectTimeout(configuration.getConnectTimeoutSeconds(), TimeUnit.SECONDS);
    }/*from ww w .j ava 2 s .c  o m*/

    if (configuration.getReadTimeoutSeconds() != -1) {
        httpClient.setReadTimeout(configuration.getReadTimeoutSeconds(), TimeUnit.SECONDS);
    }
    if (this.configuration.isUseSSL()) {
        SSLContext theSslContextToUse;

        if (this.configuration.getSslContext() == null) {
            if (this.configuration.getKeystorePath() != null) {
                theSslContextToUse = buildSSLContext(this.configuration.getKeystorePath(),
                        this.configuration.getKeystorePassword());
            } else {
                theSslContextToUse = null; // rely on the JVM default
            }
        } else {
            theSslContextToUse = this.configuration.getSslContext();
        }

        if (theSslContextToUse != null) {
            httpClient.setSslSocketFactory(theSslContextToUse.getSocketFactory());
        }

        // does not perform any hostname verification when looking at the remote end's cert
        /*
        httpClient.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            log.debugf("HTTP client is blindly approving cert for [%s]", hostname);
            return true;
        }
        });
        */
    }

    this.httpClient = httpClient;
}

From source file:org.hawkular.cmdgw.ws.test.TestWebSocketClient.java

License:Apache License

private TestWebSocketClient(Request request, TestListener testListener, int connectTimeoutSeconds,
        int readTimeoutSeconds) {
    super();/*from ww w.  jav a  2  s  .  c o  m*/
    if (request == null) {
        throw new IllegalStateException(
                "Cannot build a [" + TestWebSocketClient.class.getName() + "] with a null request");
    }
    this.listener = testListener;
    OkHttpClient c = new OkHttpClient();
    c.setConnectTimeout(connectTimeoutSeconds, TimeUnit.SECONDS);
    c.setReadTimeout(readTimeoutSeconds, TimeUnit.SECONDS);
    this.client = c;

    WebSocketCall.create(client, request).enqueue(testListener);
}

From source file:org.koboc.collect.android.adapters.PreCompleteListAdapter.java

License:Apache License

private void isCaseExist(final Long id) {

    BASE_URL = mContext.getString(R.string.default_java_server_url);

    AuthUser authUser = AuthUser.findLoggedInUser();
    String token = authUser.getApi_token();
    String username = authUser.getUsername();
    String basicAuth = "Basic "
            + Base64.encodeToString(String.format("%s:%s", username, token).getBytes(), Base64.NO_WRAP);

    InstanceProvider.DatabaseHelper databaseHelper = new InstanceProvider.DatabaseHelper(DATABASE_NAME);
    db = databaseHelper.getWritableDatabase();

    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(1000, TimeUnit.MILLISECONDS);

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(BASE_URL)
            .setLogLevel(RestAdapter.LogLevel.FULL).setClient(new OkClient(okHttpClient)).build();
    myApi = restAdapter.create(MyApi.class);

    myApi.isCaseDeleted(basicAuth, id, new Callback<Boolean>() {
        @Override//from w ww . ja  v  a2 s . c o m
        public void success(Boolean caseResponseVMs, Response response) {
            System.out.println("success :::: " + caseResponseVMs);

            if (!caseResponseVMs) {
                List<String> instances = new ArrayList<String>();
                Cursor cursor = db.rawQuery("SELECT * FROM instances where caseId = " + id, null);
                System.out.println("cursor ::: " + cursor.getCount());

                while (cursor.moveToNext()) {
                    System.out.println("path :::: " + cursor.getString(4));
                    instances.add(cursor.getString(4));
                }

                for (String s : instances) {
                    String path = s.substring(0, s.lastIndexOf('/'));
                    File file = new File(path);
                    //Boolean aBoolean = file.delete();
                    System.out.println("deleteDirectory :::: " + s);
                    System.out.println("deleteDirectory :::: " + file);
                    deleteDirectory(file);
                }

                db.execSQL("delete from instances where caseId = " + id);
                CaseRecord.deleteAll(CaseRecord.class, "case_id = ?", id + "");
                ((MyCaseActivity) mContext).onResume();

            } else {
                Toast.makeText(mContext, "Sorry. You can'delete this case.", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void failure(RetrofitError error) {

            error.printStackTrace();

        }
    });

}

From source file:org.matrix.androidsdk.RestClient.java

License:Apache License

/**
 * Public constructor./*  w  ww.j  a v  a  2 s.c o  m*/
 * @param hsUri The http[s] URI to the home server.
 */
public RestClient(Uri hsUri, Class<T> type) {
    // sanity check
    if (hsUri == null || (!"http".equals(hsUri.getScheme()) && !"https".equals(hsUri.getScheme()))) {
        throw new RuntimeException("Invalid home server URI: " + hsUri);
    }

    // The JSON -> object mapper
    gson = JsonUtils.getGson();

    // HTTP client
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(READ_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    // Rest adapter for turning API interfaces into actual REST-calling objects
    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(hsUri.toString() + URI_PREFIX)
            .setConverter(new GsonConverter(gson)).setClient(new OkClient(okHttpClient))
            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestInterceptor.RequestFacade request) {
                    // Add the access token to all requests if it is set
                    if ((mCredentials != null) && (mCredentials.accessToken != null)) {
                        request.addEncodedQueryParam(PARAM_ACCESS_TOKEN, mCredentials.accessToken);
                    }
                }
            }).build();

    restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);

    mApi = restAdapter.create(type);
}

From source file:org.openhab.binding.bosesoundtouch.handler.BoseSoundTouchHandler.java

License:Open Source License

protected void openConnection() {
    zoneState = ZoneState.None;/*from ww w .  jav  a2  s.  c o m*/
    zoneMaster = null;
    zoneMembers = Collections.emptyList();
    updateStatus(ThingStatus.INITIALIZING, ThingStatusDetail.NONE);
    OkHttpClient client = new OkHttpClient();
    // we need longer timeouts for websocket.
    client.setReadTimeout(300, TimeUnit.SECONDS);
    Map<String, Object> props = thing.getConfiguration().getProperties();
    String host = (String) props.get(BoseSoundTouchBindingConstants.DEVICE_PARAMETER_HOST);

    // try {
    // BigDecimal port = (BigDecimal) props.get(BoseSoundTouchBindingConstants.DEVICE_PARAMETER_PORT);
    // String urlBase = "http://" + host + ":" + port + "/";
    // Request request = new Request.Builder().url(urlBase + "info").build();
    // Response response = client.newCall(request).execute();
    // if (response.code() != 200) {
    // throw new IOException("Invalid response code: " + response.code());
    // }
    // String resp = response.body().string();
    // } catch (IOException e) {
    // updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
    // }
    String wsUrl = "http://" + host + ":8080/"; // TODO port 8080 is hardcoded ?
    Request request = new Request.Builder().url(wsUrl).addHeader("Sec-WebSocket-Protocol", "gabbo").build();
    WebSocketCall call = WebSocketCall.create(client, request);
    call.enqueue(this);
}

From source file:org.openlmis.core.network.LMISRestManager.java

License:Open Source License

protected Client getSSLClient() {
    OkHttpClient httpClient = new OkHttpClient();
    httpClient.setReadTimeout(1, TimeUnit.MINUTES);
    httpClient.setConnectTimeout(15, TimeUnit.SECONDS);
    httpClient.setWriteTimeout(30, TimeUnit.SECONDS);

    return new OkClient(httpClient);
}

From source file:org.sonar.runner.impl.OkHttpClientFactory.java

License:Open Source License

static OkHttpClient create(JavaVersion javaVersion) {
    OkHttpClient httpClient = new OkHttpClient();
    httpClient.setConnectTimeout(CONNECT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS);
    httpClient.setReadTimeout(READ_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS);
    ConnectionSpec tls = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).allEnabledTlsVersions()
            .allEnabledCipherSuites().supportsTlsExtensions(true).build();
    httpClient.setConnectionSpecs(asList(tls, ConnectionSpec.CLEARTEXT));
    if (javaVersion.isJava7()) {
        // OkHttp executes SSLContext.getInstance("TLS") by default (see
        // https://github.com/square/okhttp/blob/c358656/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java#L616)
        // As only TLS 1.0 is enabled by default in Java 7, the SSLContextFactory must be changed
        // in order to support all versions from 1.0 to 1.2.
        // Note that this is not overridden for Java 8 as TLS 1.2 is enabled by default.
        // Keeping getInstance("TLS") allows to support potential future versions of TLS on Java 8.
        try {//from w  w  w  .j  av  a2 s  . c om
            httpClient.setSslSocketFactory(
                    new Tls12Java7SocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()));
        } catch (Exception e) {
            throw new IllegalStateException("Fail to init TLS context", e);
        }
    }
    return httpClient;
}

From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyserver.java

License:Apache License

/**
 * returns a client with pinned certificate if necessary
 *
 * @param url   url to be queried by client
 * @param proxy proxy to be used by client
 * @return client with a pinned certificate if necessary
 *//*from www .j ava 2 s . c  om*/
public static OkHttpClient getClient(URL url, Proxy proxy) throws IOException {
    OkHttpClient client = new OkHttpClient();

    try {
        TlsHelper.usePinnedCertificateIfAvailable(client, url);
    } catch (TlsHelper.TlsHelperException e) {
        Log.w(Constants.TAG, e);
    }

    // don't follow any redirects
    client.setFollowRedirects(false);
    client.setFollowSslRedirects(false);

    if (proxy != null) {
        client.setProxy(proxy);
        client.setConnectTimeout(30000, TimeUnit.MILLISECONDS);
    } else {
        client.setProxy(Proxy.NO_PROXY);
        client.setConnectTimeout(5000, TimeUnit.MILLISECONDS);
    }
    client.setReadTimeout(45000, TimeUnit.MILLISECONDS);

    return client;
}

From source file:org.wso2.carbon.identity.authenticator.duo.DuoHttp.java

License:Open Source License

public Response executeHttpRequest() throws Exception {
    String url = "https://" + host + uri;
    String queryString = createQueryString();
    Request.Builder builder = new Request.Builder();
    if (method.equals("POST")) {
        builder.post(RequestBody.create(FORM_ENCODED, queryString));
    } else if (method.equals("PUT")) {
        builder.put(RequestBody.create(FORM_ENCODED, queryString));
    } else if (method.equals("GET")) {
        if (queryString.length() > 0) {
            url += "?" + queryString;
        }/*  w  ww .  j  a va  2  s.com*/
        builder.get();
    } else if (method.equals("DELETE")) {
        if (queryString.length() > 0) {
            url += "?" + queryString;
        }
        builder.delete();
    } else {
        throw new UnsupportedOperationException("Unsupported method: " + method);
    }
    Request request = builder.url(url).build();
    // Set up client.
    OkHttpClient httpclient = new OkHttpClient();
    if (proxy != null) {
        httpclient.setProxy(proxy);
    }
    httpclient.setConnectTimeout(timeout, TimeUnit.SECONDS);
    httpclient.setWriteTimeout(timeout, TimeUnit.SECONDS);
    httpclient.setReadTimeout(timeout, TimeUnit.SECONDS);
    // finish and execute request
    builder.headers(headers.build());
    return httpclient.newCall(builder.build()).execute();
}