Search in sources :

Example 31 with Dispatcher

use of mockwebserver3.Dispatcher 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 32 with Dispatcher

use of mockwebserver3.Dispatcher in project retrofit by square.

the class Crawler method main.

public static void main(String... args) throws Exception {
    Dispatcher dispatcher = new Dispatcher(Executors.newFixedThreadPool(20));
    dispatcher.setMaxRequests(20);
    dispatcher.setMaxRequestsPerHost(1);
    OkHttpClient okHttpClient = new OkHttpClient.Builder().dispatcher(dispatcher).connectionPool(new ConnectionPool(100, 30, TimeUnit.SECONDS)).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(HttpUrl.parse("https://example.com/")).addConverterFactory(PageAdapter.FACTORY).client(okHttpClient).build();
    PageService pageService = retrofit.create(PageService.class);
    Crawler crawler = new Crawler(pageService);
    crawler.crawlPage(HttpUrl.parse(args[0]));
}
Also used : ConnectionPool(okhttp3.ConnectionPool) Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) Dispatcher(okhttp3.Dispatcher)

Example 33 with Dispatcher

use of mockwebserver3.Dispatcher in project apollo-android by apollographql.

the class CacheHeadersTest method testDefaultHeadersReceived.

@Test
@SuppressWarnings("CheckReturnValue")
public void testDefaultHeadersReceived() throws Exception {
    final AtomicBoolean hasHeader = new AtomicBoolean();
    final NormalizedCache normalizedCache = new NormalizedCache() {

        @Nullable
        @Override
        public Record loadRecord(@NonNull String key, @NonNull CacheHeaders cacheHeaders) {
            hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE));
            return null;
        }

        @Nonnull
        @Override
        public Set<String> merge(@NonNull Record record, @NonNull CacheHeaders cacheHeaders) {
            hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE));
            return emptySet();
        }

        @Override
        public void clearAll() {
        }

        @Override
        public boolean remove(@Nonnull CacheKey cacheKey) {
            return false;
        }

        @Nonnull
        @Override
        protected Set<String> performMerge(@Nonnull Record apolloRecord, @Nonnull CacheHeaders cacheHeaders) {
            return emptySet();
        }
    };
    final NormalizedCacheFactory<NormalizedCache> cacheFactory = new NormalizedCacheFactory<NormalizedCache>() {

        @Override
        public NormalizedCache create(RecordFieldJsonAdapter recordFieldAdapter) {
            return normalizedCache;
        }
    };
    CacheHeaders cacheHeaders = CacheHeaders.builder().addHeader(ApolloCacheHeaders.DO_NOT_STORE, "true").build();
    ApolloClient apolloClient = ApolloClient.builder().normalizedCache(cacheFactory, new IdFieldCacheKeyResolver()).serverUrl(server.url("/")).okHttpClient(new OkHttpClient.Builder().dispatcher(new Dispatcher(Utils.immediateExecutorService())).build()).dispatcher(Utils.immediateExecutor()).defaultCacheHeaders(cacheHeaders).build();
    server.enqueue(mockResponse("HeroAndFriendsNameResponse.json"));
    Rx2Apollo.from(apolloClient.query(new HeroAndFriendsNamesQuery(Input.fromNullable(Episode.NEWHOPE))).cacheHeaders(cacheHeaders)).test();
    assertThat(hasHeader.get()).isTrue();
}
Also used : Nonnull(javax.annotation.Nonnull) Dispatcher(okhttp3.Dispatcher) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RecordFieldJsonAdapter(com.apollographql.apollo.cache.normalized.RecordFieldJsonAdapter) ApolloCacheHeaders(com.apollographql.apollo.cache.ApolloCacheHeaders) CacheHeaders(com.apollographql.apollo.cache.CacheHeaders) HeroAndFriendsNamesQuery(com.apollographql.apollo.integration.normalizer.HeroAndFriendsNamesQuery) NormalizedCache(com.apollographql.apollo.cache.normalized.NormalizedCache) NonNull(android.support.annotation.NonNull) NormalizedCacheFactory(com.apollographql.apollo.cache.normalized.NormalizedCacheFactory) Record(com.apollographql.apollo.cache.normalized.Record) CacheKey(com.apollographql.apollo.cache.normalized.CacheKey) Test(org.junit.Test)

Example 34 with Dispatcher

use of mockwebserver3.Dispatcher in project apollo-android by apollographql.

the class HttpCacheTest method setUp.

@Before
public void setUp() {
    CustomTypeAdapter<Date> dateCustomTypeAdapter = new CustomTypeAdapter<Date>() {

        @Override
        public Date decode(CustomTypeValue value) {
            try {
                return DATE_FORMAT.parse(value.value.toString());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public CustomTypeValue encode(Date value) {
            return new CustomTypeValue.GraphQLString(DATE_FORMAT.format(value));
        }
    };
    cacheStore = new MockHttpCacheStore();
    cacheStore.delegate = new DiskLruHttpCacheStore(inMemoryFileSystem, new File("/cache/"), Integer.MAX_VALUE);
    HttpCache cache = new ApolloHttpCache(cacheStore, null);
    okHttpClient = new OkHttpClient.Builder().addInterceptor(new TrackingInterceptor()).addInterceptor(cache.interceptor()).dispatcher(new Dispatcher(Utils.immediateExecutorService())).readTimeout(2, TimeUnit.SECONDS).writeTimeout(2, TimeUnit.SECONDS).build();
    apolloClient = ApolloClient.builder().serverUrl(server.url("/")).okHttpClient(okHttpClient).dispatcher(Utils.immediateExecutor()).addCustomTypeAdapter(CustomType.DATE, dateCustomTypeAdapter).httpCache(cache).build();
}
Also used : ApolloHttpCache(com.apollographql.apollo.cache.http.ApolloHttpCache) OkHttpClient(okhttp3.OkHttpClient) ApolloHttpCache(com.apollographql.apollo.cache.http.ApolloHttpCache) HttpCache(com.apollographql.apollo.api.cache.http.HttpCache) Dispatcher(okhttp3.Dispatcher) Date(java.util.Date) CustomTypeAdapter(com.apollographql.apollo.response.CustomTypeAdapter) CustomTypeValue(com.apollographql.apollo.response.CustomTypeValue) DiskLruHttpCacheStore(com.apollographql.apollo.cache.http.DiskLruHttpCacheStore) ParseException(java.text.ParseException) File(java.io.File) Before(org.junit.Before)

Example 35 with Dispatcher

use of mockwebserver3.Dispatcher in project apollo-android by apollographql.

the class ApolloCancelCallTest method cancelCallAfterEnqueueNoCallback.

@Test
public void cancelCallAfterEnqueueNoCallback() throws Exception {
    OkHttpClient okHttpClient = new OkHttpClient.Builder().dispatcher(new Dispatcher(Utils.immediateExecutorService())).build();
    apolloClient = ApolloClient.builder().serverUrl(server.url("/")).okHttpClient(okHttpClient).httpCache(new ApolloHttpCache(cacheStore, null)).build();
    server.enqueue(mockResponse("EpisodeHeroNameResponse.json"));
    final ApolloCall<EpisodeHeroNameQuery.Data> call = apolloClient.query(new EpisodeHeroNameQuery(Input.fromNullable(Episode.EMPIRE)));
    final TestObserver<Response<EpisodeHeroNameQuery.Data>> test = Rx2Apollo.from(call).test();
    call.cancel();
    test.awaitDone(1, TimeUnit.SECONDS).assertNoErrors().assertNoValues().assertNotComplete();
}
Also used : Response(com.apollographql.apollo.api.Response) MockResponse(okhttp3.mockwebserver.MockResponse) ApolloHttpCache(com.apollographql.apollo.cache.http.ApolloHttpCache) OkHttpClient(okhttp3.OkHttpClient) EpisodeHeroNameQuery(com.apollographql.apollo.integration.normalizer.EpisodeHeroNameQuery) Dispatcher(okhttp3.Dispatcher) Test(org.junit.Test)

Aggregations

Dispatcher (okhttp3.Dispatcher)43 OkHttpClient (okhttp3.OkHttpClient)28 Before (org.junit.Before)14 LruNormalizedCacheFactory (com.apollographql.apollo.cache.normalized.lru.LruNormalizedCacheFactory)10 IOException (java.io.IOException)9 Interceptor (okhttp3.Interceptor)7 Test (org.junit.Test)7 Call (okhttp3.Call)6 RecordedRequest (mockwebserver3.RecordedRequest)5 ApolloHttpCache (com.apollographql.apollo.cache.http.ApolloHttpCache)3 CustomTypeValue (com.apollographql.apollo.response.CustomTypeValue)3 ParseException (java.text.ParseException)3 MockResponse (mockwebserver3.MockResponse)3 ConnectionPool (okhttp3.ConnectionPool)3 Request (okhttp3.Request)3 Response (okhttp3.Response)3 Buffer (okio.Buffer)3 NonNull (android.support.annotation.NonNull)2 IdFieldCacheKeyResolver (com.apollographql.apollo.IdFieldCacheKeyResolver)2 Response (com.apollographql.apollo.api.Response)2