Search in sources :

Example 21 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project mollyim-android by mollyim.

the class PushServiceSocket method makeCallingRequest.

public CallingResponse makeCallingRequest(long requestId, String url, String httpMethod, List<Pair<String, String>> headers, byte[] body) {
    ConnectionHolder connectionHolder = getRandom(serviceClients, random);
    OkHttpClient okHttpClient = connectionHolder.getClient().newBuilder().followRedirects(false).connectTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).readTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).build();
    RequestBody requestBody = body != null ? RequestBody.create(null, body) : null;
    Request.Builder builder = new Request.Builder().url(url).method(httpMethod, requestBody);
    if (headers != null) {
        for (Pair<String, String> header : headers) {
            builder.addHeader(header.first(), header.second());
        }
    }
    Request request = builder.build();
    for (int i = 0; i < MAX_FOLLOW_UPS; i++) {
        try (Response response = okHttpClient.newCall(request).execute()) {
            int responseStatus = response.code();
            if (responseStatus != 307) {
                return new CallingResponse.Success(requestId, responseStatus, response.body() != null ? response.body().bytes() : new byte[0]);
            }
            String location = response.header("Location");
            HttpUrl newUrl = location != null ? request.url().resolve(location) : null;
            if (newUrl != null) {
                request = request.newBuilder().url(newUrl).build();
            } else {
                return new CallingResponse.Error(requestId, new IOException("Received redirect without a valid Location header"));
            }
        } catch (IOException e) {
            Log.w(TAG, "Exception during ringrtc http call.", e);
            return new CallingResponse.Error(requestId, e);
        }
    }
    Log.w(TAG, "Calling request max redirects exceeded");
    return new CallingResponse.Error(requestId, new IOException("Redirect limit exceeded"));
}
Also used : CallingResponse(org.whispersystems.signalservice.api.messages.calls.CallingResponse) OkHttpClient(okhttp3.OkHttpClient) ReceiptCredentialRequest(org.signal.zkgroup.receipts.ReceiptCredentialRequest) Request(okhttp3.Request) ChangePhoneNumberRequest(org.whispersystems.signalservice.api.account.ChangePhoneNumberRequest) DiscoveryRequest(org.whispersystems.signalservice.internal.contacts.entities.DiscoveryRequest) KeyBackupRequest(org.whispersystems.signalservice.internal.contacts.entities.KeyBackupRequest) ProfileKeyCredentialRequest(org.signal.zkgroup.profiles.ProfileKeyCredentialRequest) GroupsV2AuthorizationString(org.whispersystems.signalservice.api.groupsv2.GroupsV2AuthorizationString) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) CallingResponse(org.whispersystems.signalservice.api.messages.calls.CallingResponse) Response(okhttp3.Response) KeyBackupResponse(org.whispersystems.signalservice.internal.contacts.entities.KeyBackupResponse) ReceiptCredentialResponse(org.signal.zkgroup.receipts.ReceiptCredentialResponse) CredentialResponse(org.whispersystems.signalservice.api.groupsv2.CredentialResponse) StorageAuthResponse(org.whispersystems.signalservice.api.storage.StorageAuthResponse) VerifyDeviceResponse(org.whispersystems.signalservice.api.messages.multidevice.VerifyDeviceResponse) DiscoveryResponse(org.whispersystems.signalservice.internal.contacts.entities.DiscoveryResponse) ProfileKeyCredentialResponse(org.signal.zkgroup.profiles.ProfileKeyCredentialResponse) TokenResponse(org.whispersystems.signalservice.internal.contacts.entities.TokenResponse) DigestingRequestBody(org.whispersystems.signalservice.internal.push.http.DigestingRequestBody) RequestBody(okhttp3.RequestBody)

Example 22 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project mollyim-android by mollyim.

the class PushServiceSocket method getServiceConnection.

private Response getServiceConnection(String urlFragment, String method, RequestBody body, Map<String, String> headers, Optional<UnidentifiedAccess> unidentifiedAccess, boolean doNotAddAuthenticationOrUnidentifiedAccessKey) throws PushNetworkException {
    try {
        OkHttpClient okHttpClient = buildOkHttpClient(unidentifiedAccess.isPresent());
        Call call = okHttpClient.newCall(buildServiceRequest(urlFragment, method, body, headers, unidentifiedAccess, doNotAddAuthenticationOrUnidentifiedAccessKey));
        synchronized (connections) {
            connections.add(call);
        }
        try {
            return call.execute();
        } finally {
            synchronized (connections) {
                connections.remove(call);
            }
        }
    } catch (IOException e) {
        throw new PushNetworkException(e);
    }
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) PushNetworkException(org.whispersystems.signalservice.api.push.exceptions.PushNetworkException) IOException(java.io.IOException)

Example 23 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project mollyim-android by mollyim.

the class EmojiSearchIndexDownloadJob method onRun.

@Override
protected void onRun() throws Exception {
    OkHttpClient client = ApplicationDependencies.getOkHttpClient();
    Manifest manifest = downloadManifest(client);
    Locale locale = DynamicLanguageContextWrapper.getUsersSelectedLocale(context);
    String remoteLanguage = findMatchingLanguage(locale, manifest.getLanguages());
    if (manifest.getVersion() == SignalStore.emojiValues().getSearchVersion() && remoteLanguage.equals(SignalStore.emojiValues().getSearchLanguage())) {
        Log.i(TAG, "Already using the latest version of " + manifest.getVersion() + " with the correct language " + remoteLanguage);
        SignalStore.emojiValues().setLastSearchIndexCheck(System.currentTimeMillis());
        return;
    }
    Log.i(TAG, "Need to get a new search index. Downloading version: " + manifest.getVersion() + ", language: " + remoteLanguage);
    List<EmojiSearchData> searchIndex = downloadSearchIndex(client, manifest.getVersion(), remoteLanguage);
    SignalDatabase.emojiSearch().setSearchIndex(searchIndex);
    SignalStore.emojiValues().onSearchIndexUpdated(manifest.getVersion(), remoteLanguage);
    SignalStore.emojiValues().setLastSearchIndexCheck(System.currentTimeMillis());
    Log.i(TAG, "Success! Now at version: " + manifest.getVersion() + ", language: " + remoteLanguage);
}
Also used : Locale(java.util.Locale) OkHttpClient(okhttp3.OkHttpClient) EmojiSearchData(org.thoughtcrime.securesms.database.model.EmojiSearchData)

Example 24 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project ouidb-to-json-publisher by jfisbein.

the class OUIDBDownloader method download.

public Reader download() {
    Cache cache = new Cache(new File(System.getProperty("java.io.tmpdir")), TEN_MB);
    OkHttpClient client = new OkHttpClient.Builder().cache(cache).build();
    Reader result = null;
    Iterator<String> urlIterator = Arrays.asList(ouiDbUrls).iterator();
    while (result == null && urlIterator.hasNext()) {
        String ouiDbUrl = urlIterator.next();
        Request request = new Request.Builder().url(ouiDbUrl).build();
        log.info("Trying to download info from {}", ouiDbUrl);
        try {
            Response response = client.newCall(request).execute();
            if (response.body() != null) {
                String contentTypeHeader = getContentTypeHeader(response).orElse("text/plain; charset=utf-8");
                if (contentTypeHeader.equalsIgnoreCase("application/x-gzip")) {
                    result = new InputStreamReader(new GZIPInputStream(response.body().byteStream()));
                } else if (contentTypeHeader.equalsIgnoreCase("application/x-bzip2")) {
                    result = new InputStreamReader(new BZip2CompressorInputStream(response.body().byteStream()));
                } else {
                    result = response.body().charStream();
                }
            }
        } catch (IOException e) {
            log.warn("Error downloading OUIs from {} - {}: {}", ouiDbUrl, e.getClass().getSimpleName(), e.getMessage());
        }
    }
    if (result == null) {
        throw new NoRecordsFoundException("No records found");
    }
    return result;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) InputStreamReader(java.io.InputStreamReader) Request(okhttp3.Request) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) NoRecordsFoundException(com.sputnik.ouidb.exception.NoRecordsFoundException) Response(okhttp3.Response) GZIPInputStream(java.util.zip.GZIPInputStream) BZip2CompressorInputStream(org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream) File(java.io.File) Cache(okhttp3.Cache)

Example 25 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project che-server by eclipse-che.

the class OpenShiftClientFactory method buildKubernetesInterceptor.

@Override
protected Interceptor buildKubernetesInterceptor(Config config) {
    final String oauthToken;
    if (Utils.isNotNullOrEmpty(config.getUsername()) && Utils.isNotNullOrEmpty(config.getPassword())) {
        synchronized (getHttpClient()) {
            try {
                OkHttpClient.Builder builder = getHttpClient().newBuilder();
                builder.interceptors().clear();
                OkHttpClient clone = builder.build();
                String credential = Credentials.basic(config.getUsername(), config.getPassword());
                URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZE_PATH));
                Response response = clone.newCall(new Request.Builder().get().url(url).header(AUTHORIZATION, credential).build()).execute();
                // False positive warn: according to javadocs response.body() returns non-null value
                // if called after Call.execute()
                response.body().close();
                response = response.priorResponse() != null ? response.priorResponse() : response;
                response = response.networkResponse() != null ? response.networkResponse() : response;
                String token = response.header(LOCATION);
                if (token == null || token.isEmpty()) {
                    throw new KubernetesClientException("Unexpected response (" + response.code() + " " + response.message() + "), to the authorization request. Missing header:[" + LOCATION + "]!");
                }
                token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length());
                token = token.substring(0, token.indexOf(AFTER_TOKEN));
                oauthToken = token;
            } catch (Exception e) {
                throw KubernetesClientException.launderThrowable(e);
            }
        }
    } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) {
        oauthToken = config.getOauthToken();
    } else {
        oauthToken = null;
    }
    return chain -> {
        Request request = chain.request();
        if (isNotNullOrEmpty(oauthToken)) {
            Request authReq = chain.request().newBuilder().addHeader("Authorization", "Bearer " + oauthToken).build();
            return chain.proceed(authReq);
        }
        return chain.proceed(request);
    };
}
Also used : Response(okhttp3.Response) KubernetesClientFactory(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesClientFactory) Authenticator(okhttp3.Authenticator) URL(java.net.URL) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) DefaultOpenShiftClient(io.fabric8.openshift.client.DefaultOpenShiftClient) Singleton(javax.inject.Singleton) Inject(javax.inject.Inject) Utils(io.fabric8.kubernetes.client.utils.Utils) EventListener(okhttp3.EventListener) Response(okhttp3.Response) Named(javax.inject.Named) KubernetesClientConfigFactory(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesClientConfigFactory) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) Interceptor(okhttp3.Interceptor) OpenShiftOAuthInterceptor(io.fabric8.openshift.client.internal.OpenShiftOAuthInterceptor) Request(okhttp3.Request) URLUtils(io.fabric8.kubernetes.client.utils.URLUtils) OpenShiftConfigBuilder(io.fabric8.openshift.client.OpenShiftConfigBuilder) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) Credentials(okhttp3.Credentials) Nullable(org.eclipse.che.commons.annotation.Nullable) Consumer(java.util.function.Consumer) Config(io.fabric8.kubernetes.client.Config) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) OpenShiftConfig(io.fabric8.openshift.client.OpenShiftConfig) OkHttpClient(okhttp3.OkHttpClient) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) ImpersonatorInterceptor(io.fabric8.kubernetes.client.utils.ImpersonatorInterceptor) Utils.isNotNullOrEmpty(io.fabric8.kubernetes.client.utils.Utils.isNotNullOrEmpty) OkHttpClient(okhttp3.OkHttpClient) OpenShiftConfigBuilder(io.fabric8.openshift.client.OpenShiftConfigBuilder) Request(okhttp3.Request) URL(java.net.URL) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Aggregations

OkHttpClient (okhttp3.OkHttpClient)1944 Request (okhttp3.Request)1024 Response (okhttp3.Response)880 IOException (java.io.IOException)567 Test (org.junit.Test)365 Call (okhttp3.Call)290 RequestBody (okhttp3.RequestBody)222 Test (org.junit.jupiter.api.Test)145 Retrofit (retrofit2.Retrofit)138 File (java.io.File)132 HttpUrl (okhttp3.HttpUrl)131 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)128 Callback (okhttp3.Callback)117 JSONObject (org.json.JSONObject)110 ArrayList (java.util.ArrayList)106 ResponseBody (okhttp3.ResponseBody)105 Gson (com.google.gson.Gson)98 MediaType (okhttp3.MediaType)98 List (java.util.List)92 Map (java.util.Map)85