Search in sources :

Example 81 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project autorest-clientruntime-for-java by Azure.

the class RequestIdHeaderInterceptorTests method sameRequestIdForRetry.

@Test
public void sameRequestIdForRetry() throws Exception {
    RestClient restClient = new RestClient.Builder().withBaseUrl("http://localhost").withSerializerAdapter(new AzureJacksonAdapter()).withResponseBuilderFactory(new AzureResponseBuilder.Factory()).withInterceptor(new RequestIdHeaderInterceptor()).withInterceptor(new RetryHandler()).withInterceptor(new Interceptor() {

        private String firstRequestId = null;

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (request.header(REQUEST_ID_HEADER) != null) {
                if (firstRequestId == null) {
                    firstRequestId = request.header(REQUEST_ID_HEADER);
                    return new Response.Builder().code(500).request(request).message("Error").protocol(Protocol.HTTP_1_1).body(ResponseBody.create(MediaType.parse("text/plain"), "azure rocks")).build();
                } else if (request.header(REQUEST_ID_HEADER).equals(firstRequestId)) {
                    return new Response.Builder().code(200).request(request).message("OK").protocol(Protocol.HTTP_1_1).body(ResponseBody.create(MediaType.parse("text/plain"), "azure rocks")).build();
                }
            }
            return new Response.Builder().code(400).request(request).protocol(Protocol.HTTP_1_1).build();
        }
    }).build();
    AzureServiceClient serviceClient = new AzureServiceClient(restClient) {
    };
    Response response = serviceClient.restClient().httpClient().newCall(new Request.Builder().get().url("http://localhost").build()).execute();
    Assert.assertEquals(200, response.code());
}
Also used : AzureJacksonAdapter(com.microsoft.azure.serializer.AzureJacksonAdapter) RestClient(com.microsoft.rest.RestClient) Request(okhttp3.Request) RequestIdHeaderInterceptor(com.microsoft.rest.interceptors.RequestIdHeaderInterceptor) Response(okhttp3.Response) RetryHandler(com.microsoft.rest.retry.RetryHandler) Interceptor(okhttp3.Interceptor) RequestIdHeaderInterceptor(com.microsoft.rest.interceptors.RequestIdHeaderInterceptor) Test(org.junit.Test)

Example 82 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project autorest-clientruntime-for-java by Azure.

the class ConnectionPoolTests method canUseOkHttpThreadPool.

// Simulates a server with response latency of 1 second. A connection pool
// size 2 should only send 2 requests per second.
@Test
public void canUseOkHttpThreadPool() throws Exception {
    RestClient restClient = new RestClient.Builder().withBaseUrl("https://microsoft.com").withSerializerAdapter(new JacksonAdapter()).withResponseBuilderFactory(new Factory()).withDispatcher(new Dispatcher(Executors.newFixedThreadPool(2))).useHttpClientThreadPool(true).withInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new IOException(e);
            }
            return new Response.Builder().request(chain.request()).code(200).message("OK").protocol(Protocol.HTTP_1_1).body(ResponseBody.create(MediaType.parse("text/plain"), "azure rocks")).build();
        }
    }).build();
    final Service service = restClient.retrofit().create(Service.class);
    final CountDownLatch latch = new CountDownLatch(1);
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Observable.range(1, 4).flatMap(new Func1<Integer, Observable<?>>() {

        @Override
        public Observable<?> call(Integer integer) {
            return service.getAsync().subscribeOn(Schedulers.io());
        }
    }).doOnCompleted(new Action0() {

        @Override
        public void call() {
            latch.countDown();
        }
    }).subscribe();
    latch.await();
    stopWatch.stop();
    Assert.assertTrue(stopWatch.getTime() > 2000);
}
Also used : Action0(rx.functions.Action0) JacksonAdapter(com.microsoft.rest.serializer.JacksonAdapter) Factory(com.microsoft.rest.ServiceResponseBuilder.Factory) IOException(java.io.IOException) Dispatcher(okhttp3.Dispatcher) CountDownLatch(java.util.concurrent.CountDownLatch) Observable(rx.Observable) StopWatch(org.apache.commons.lang3.time.StopWatch) Interceptor(okhttp3.Interceptor) Test(org.junit.Test)

Example 83 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project autorest-clientruntime-for-java by Azure.

the class ConnectionPoolTests method canUseRxThreadPool.

// Simulates a server with response latency of 1 second. A connection pool
// size 2 should only send requests on Rx scheduler.
@Test
public void canUseRxThreadPool() throws Exception {
    RestClient restClient = new RestClient.Builder().withBaseUrl("https://microsoft.com").withSerializerAdapter(new JacksonAdapter()).withResponseBuilderFactory(new Factory()).withDispatcher(new Dispatcher(Executors.newFixedThreadPool(2))).useHttpClientThreadPool(false).withInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new IOException(e);
            }
            return new Response.Builder().request(chain.request()).code(200).message("OK").protocol(Protocol.HTTP_1_1).body(ResponseBody.create(MediaType.parse("text/plain"), "azure rocks")).build();
        }
    }).build();
    final Service service = restClient.retrofit().create(Service.class);
    final CountDownLatch latch = new CountDownLatch(1);
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    // Rx Scheduler with no concurrency control
    Observable.range(1, 6).flatMap(new Func1<Integer, Observable<?>>() {

        @Override
        public Observable<?> call(Integer integer) {
            return service.getAsync().subscribeOn(Schedulers.io());
        }
    }).doOnCompleted(new Action0() {

        @Override
        public void call() {
            latch.countDown();
        }
    }).subscribe();
    latch.await();
    stopWatch.stop();
    Assert.assertTrue(stopWatch.getTime() < 2000);
    final CountDownLatch latch2 = new CountDownLatch(1);
    stopWatch.reset();
    stopWatch.start();
    // Rx Scheduler with concurrency control
    Observable.range(1, 4).flatMap(new Func1<Integer, Observable<?>>() {

        @Override
        public Observable<?> call(Integer integer) {
            return service.getAsync().subscribeOn(Schedulers.io());
        }
    }, 2).doOnCompleted(new Action0() {

        @Override
        public void call() {
            latch2.countDown();
        }
    }).subscribe();
    latch2.await();
    stopWatch.stop();
    Assert.assertTrue(stopWatch.getTime() > 2000);
}
Also used : Action0(rx.functions.Action0) JacksonAdapter(com.microsoft.rest.serializer.JacksonAdapter) Factory(com.microsoft.rest.ServiceResponseBuilder.Factory) IOException(java.io.IOException) Dispatcher(okhttp3.Dispatcher) CountDownLatch(java.util.concurrent.CountDownLatch) Observable(rx.Observable) StopWatch(org.apache.commons.lang3.time.StopWatch) Interceptor(okhttp3.Interceptor) Test(org.junit.Test)

Example 84 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project azure-sdk-for-java by Azure.

the class MockIntegrationTestBase method setupTest.

protected void setupTest(final String testName) throws Exception {
    if (currentTestName == null) {
        currentTestName = testName;
    } else {
        throw new Exception("Setting up another test in middle of a test");
    }
    SdkContext.setResourceNamerFactory(new TestResourceNamerFactory(this));
    SdkContext.setDelayProvider(new TestDelayProvider());
    SdkContext.setRxScheduler(Schedulers.trampoline());
    int retries = 10;
    while (retries > 0) {
        retries--;
        try {
            wireMock = new WireMock(HOST, wireMockRule.port());
            wireMock.resetMappings();
            break;
        } catch (Exception ex) {
            Thread.sleep(3000);
        }
    }
    if (IS_MOCKED) {
        File recordFile = getRecordFile();
        ObjectMapper mapper = new ObjectMapper();
        testRecord = mapper.readValue(recordFile, TestRecord.class);
        System.out.println("Total records " + testRecord.networkCallRecords.size());
    } else {
        testRecord = new TestRecord();
    }
    this.interceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            if (IS_MOCKED) {
                return registerRecordedResponse(chain);
            }
            return recordRequestAndResponse(chain);
        }
    };
}
Also used : IOException(java.io.IOException) IOException(java.io.IOException) Response(okhttp3.Response) File(java.io.File) Interceptor(okhttp3.Interceptor) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) WireMock(com.github.tomakehurst.wiremock.client.WireMock)

Example 85 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project MVPArms by JessYanCoding.

the class WEApplication method getGlobeConfigModule.

/**
     * app的全局配置信息封装进module(使用Dagger注入到需要配置信息的地方)
     * GlobeHttpHandler是在NetworkInterceptor中拦截数据
     * 如果想将请求参数加密,则必须在Interceptor中对参数进行处理,GlobeConfigModule.addInterceptor可以添加Interceptor
     * @return
     */
@Override
protected GlobeConfigModule getGlobeConfigModule() {
    return GlobeConfigModule.buidler().baseurl(Api.APP_DOMAIN).globeHttpHandler(new // 这里可以提供一个全局处理http响应结果的处理类,
    GlobeHttpHandler() {

        // 这里可以比客户端提前一步拿到服务器返回的结果,可以做一些操作,比如token超时,重新获取
        @Override
        public Response onHttpResultResponse(String httpResult, Interceptor.Chain chain, Response response) {
            //重新请求token,并重新执行请求
            try {
                if (!TextUtils.isEmpty(httpResult)) {
                    JSONArray array = new JSONArray(httpResult);
                    JSONObject object = (JSONObject) array.get(0);
                    String login = object.getString("login");
                    String avatar_url = object.getString("avatar_url");
                    Timber.tag(TAG).w("result ------>" + login + "    ||   avatar_url------>" + avatar_url);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return response;
            }
            //如果不需要返回新的结果,则直接把response参数返回出去
            return response;
        }

        // 这里可以在请求服务器之前可以拿到request,做一些操作比如给request统一添加token或者header
        @Override
        public Request onHttpRequestBefore(Interceptor.Chain chain, Request request) {
            //                .build();
            return request;
        }
    }).responseErroListener(new ResponseErroListener() {

        //     用来提供处理所有错误的监听
        //     rxjava必要要使用ErrorHandleSubscriber(默认实现Subscriber的onError方法),此监听才生效
        @Override
        public void handleResponseError(Context context, Exception e) {
            Timber.tag(TAG).w("------------>" + e.getMessage());
            UiUtils.SnackbarText("net error");
        }
    }).build();
}
Also used : Context(android.content.Context) JSONArray(org.json.JSONArray) Request(okhttp3.Request) JSONException(org.json.JSONException) ResponseErroListener(me.jessyan.rxerrorhandler.handler.listener.ResponseErroListener) JSONException(org.json.JSONException) Response(okhttp3.Response) JSONObject(org.json.JSONObject) Interceptor(okhttp3.Interceptor)

Aggregations

Interceptor (okhttp3.Interceptor)138 Request (okhttp3.Request)61 OkHttpClient (okhttp3.OkHttpClient)54 Response (okhttp3.Response)51 IOException (java.io.IOException)45 Test (org.junit.Test)29 Retrofit (retrofit2.Retrofit)27 File (java.io.File)15 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)13 Cache (okhttp3.Cache)9 HttpUrl (okhttp3.HttpUrl)8 Interceptor (com.pushtorefresh.storio3.Interceptor)7 Dispatcher (okhttp3.Dispatcher)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 X509TrustManager (javax.net.ssl.X509TrustManager)6 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)5 Provides (dagger.Provides)5 Singleton (javax.inject.Singleton)5 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)5 OAuth (com.arm.mbed.cloud.sdk.internal.devicedirectory.auth.OAuth)4