Search in sources :

Example 11 with Credentials

use of okhttp3.Credentials in project autorest-clientruntime-for-java by Azure.

the class CredentialsTests method basicCredentialsTest.

@Test
public void basicCredentialsTest() throws Exception {
    BasicAuthenticationCredentials credentials = new BasicAuthenticationCredentials("user", "pass");
    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
    credentials.applyCredentialsFilter(clientBuilder);
    clientBuilder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            String header = chain.request().header("Authorization");
            Assert.assertEquals("Basic dXNlcjpwYXNz", header);
            return new Response.Builder().request(chain.request()).code(200).protocol(Protocol.HTTP_1_1).build();
        }
    });
    ServiceClient serviceClient = new ServiceClient("http://localhost", clientBuilder, new Retrofit.Builder()) {
    };
    Response response = serviceClient.httpClient().newCall(new Request.Builder().url("http://localhost").build()).execute();
    Assert.assertEquals(200, response.code());
}
Also used : OkHttpClient(okhttp3.OkHttpClient) BasicAuthenticationCredentials(com.microsoft.rest.credentials.BasicAuthenticationCredentials) IOException(java.io.IOException) Response(okhttp3.Response) Retrofit(retrofit2.Retrofit) Interceptor(okhttp3.Interceptor) Test(org.junit.Test)

Example 12 with Credentials

use of okhttp3.Credentials in project photon-model by vmware.

the class AzureSdkClients method buildRestClient.

/**
 * Build Azure RestClient with specified executor service and credentials using
 * {@link RestClient.Builder}.
 */
private static RestClient buildRestClient(ApplicationTokenCredentials credentials, ExecutorService executorService) {
    final Retrofit.Builder retrofitBuilder;
    {
        retrofitBuilder = new Retrofit.Builder();
        if (executorService != null) {
            RxJavaCallAdapterFactory rxWithExecutorCallFactory = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.from(executorService));
            retrofitBuilder.addCallAdapterFactory(rxWithExecutorCallFactory);
        }
    }
    final RestClient.Builder restClientBuilder = new RestClient.Builder(new OkHttpClient.Builder(), retrofitBuilder);
    restClientBuilder.withBaseUrl(AzureUtils.getAzureBaseUri());
    restClientBuilder.withCredentials(credentials);
    restClientBuilder.withSerializerAdapter(new AzureJacksonAdapter());
    restClientBuilder.withLogLevel(getRestClientLogLevel());
    restClientBuilder.withInterceptor(new ResourceManagerThrottlingInterceptor());
    if (executorService != null) {
        restClientBuilder.withCallbackExecutor(executorService);
    }
    restClientBuilder.withResponseBuilderFactory(new Factory());
    return restClientBuilder.build();
}
Also used : Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) RxJavaCallAdapterFactory(retrofit2.adapter.rxjava.RxJavaCallAdapterFactory) CacheBuilder(com.google.common.cache.CacheBuilder) AzureJacksonAdapter(com.microsoft.azure.serializer.AzureJacksonAdapter) RestClient(com.microsoft.rest.RestClient) Factory(com.microsoft.rest.ServiceResponseBuilder.Factory) RxJavaCallAdapterFactory(retrofit2.adapter.rxjava.RxJavaCallAdapterFactory) ResourceManagerThrottlingInterceptor(com.microsoft.azure.management.resources.fluentcore.utils.ResourceManagerThrottlingInterceptor)

Example 13 with Credentials

use of okhttp3.Credentials in project dhis2-android-sdk by dhis2.

the class BasicAuthenticator method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    String authorizationHeader = chain.request().header(AUTHORIZATION);
    if (authorizationHeader != null) {
        // authorization header has already been set
        return chain.proceed(chain.request());
    }
    List<AuthenticatedUserModel> authenticatedUsers = authenticatedUserStore.query();
    if (authenticatedUsers.isEmpty()) {
        // have any users authenticated
        return chain.proceed(chain.request());
    }
    // retrieve first user and pass in his / her credentials
    Request request = chain.request().newBuilder().addHeader(AUTHORIZATION, String.format(Locale.US, BASIC_CREDENTIALS, authenticatedUsers.get(0).credentials())).build();
    return chain.proceed(request);
}
Also used : AuthenticatedUserModel(org.hisp.dhis.android.core.user.AuthenticatedUserModel) Request(okhttp3.Request)

Example 14 with Credentials

use of okhttp3.Credentials in project FredBoat by Frederikam.

the class Launcher method hasValidMALLogin.

// ################################################################################
// ##                     Login / credential tests
// ################################################################################
private boolean hasValidMALLogin() {
    String malUser = configProvider.getCredentials().getMalUser();
    String malPassWord = configProvider.getCredentials().getMalPassword();
    if (malUser.isEmpty() || malPassWord.isEmpty()) {
        log.info("MAL credentials not found. MAL related commands will not be available.");
        return false;
    }
    Http.SimpleRequest request = BotController.Companion.getHTTP().get("https://myanimelist.net/api/account/verify_credentials.xml").auth(Credentials.basic(malUser, malPassWord));
    try (Response response = request.execute()) {
        if (response.isSuccessful()) {
            log.info("MAL login successful");
            return true;
        } else {
            // noinspection ConstantConditions
            log.warn("MAL login failed with {}\n{}", response.toString(), response.body().string());
        }
    } catch (IOException e) {
        log.warn("MAL login failed, it seems to be down.", e);
    }
    return false;
}
Also used : Response(okhttp3.Response) Http(fredboat.util.rest.Http) IOException(java.io.IOException)

Example 15 with Credentials

use of okhttp3.Credentials in project FredBoat by Frederikam.

the class Launcher method hasValidImgurCredentials.

private boolean hasValidImgurCredentials() {
    String imgurClientId = configProvider.getCredentials().getImgurClientId();
    if (imgurClientId.isEmpty()) {
        log.info("Imgur credentials not found. Commands relying on Imgur will not work properly.");
        return false;
    }
    Http.SimpleRequest request = BotController.Companion.getHTTP().get("https://api.imgur.com/3/credits").auth("Client-ID " + imgurClientId);
    try (Response response = request.execute()) {
        // noinspection ConstantConditions
        String content = response.body().string();
        if (response.isSuccessful()) {
            JSONObject data = new JSONObject(content).getJSONObject("data");
            // https://api.imgur.com/#limits
            // at the time of the introduction of this code imgur offers daily 12500 and hourly 500 GET requests for open source software
            // hitting the daily limit 5 times in a month will blacklist the app for the rest of the month
            // we use 3 requests per hour (and per restart of the bot), so there should be no problems with imgur's rate limit
            int hourlyLimit = data.getInt("UserLimit");
            int hourlyLeft = data.getInt("UserRemaining");
            long seconds = data.getLong("UserReset") - (System.currentTimeMillis() / 1000);
            String timeTillReset = String.format("%d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60));
            int dailyLimit = data.getInt("ClientLimit");
            int dailyLeft = data.getInt("ClientRemaining");
            log.info("Imgur credentials are valid. " + hourlyLeft + "/" + hourlyLimit + " requests remaining this hour, resetting in " + timeTillReset + ", " + dailyLeft + "/" + dailyLimit + " requests remaining today.");
            return true;
        } else {
            log.warn("Imgur login failed with {}\n{}", response.toString(), content);
        }
    } catch (IOException e) {
        log.warn("Imgur login failed, it seems to be down.", e);
    }
    return false;
}
Also used : Response(okhttp3.Response) JSONObject(org.json.JSONObject) Http(fredboat.util.rest.Http) IOException(java.io.IOException)

Aggregations

Request (okhttp3.Request)39 Response (okhttp3.Response)29 OkHttpClient (okhttp3.OkHttpClient)22 IOException (java.io.IOException)20 Test (org.junit.Test)16 HttpUrl (okhttp3.HttpUrl)10 RequestBody (okhttp3.RequestBody)9 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)9 ResponseBody (okhttp3.ResponseBody)8 NonNull (androidx.annotation.NonNull)7 MockResponse (okhttp3.mockwebserver.MockResponse)7 BasicAuthenticator (com.burgstaller.okhttp.basic.BasicAuthenticator)6 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)6 Credentials (com.burgstaller.okhttp.digest.Credentials)6 DigestAuthenticator (com.burgstaller.okhttp.digest.DigestAuthenticator)6 Observable (rx.Observable)6 AuthenticationCacheInterceptor (com.burgstaller.okhttp.AuthenticationCacheInterceptor)5 CachingAuthenticatorDecorator (com.burgstaller.okhttp.CachingAuthenticatorDecorator)5 PokemonGo (com.pokegoapi.api.PokemonGo)5 PtcCredentialProvider (com.pokegoapi.auth.PtcCredentialProvider)5