Search in sources :

Example 16 with Callback

use of okhttp3.Callback in project retrofit by square.

the class RetrofitTest method callbackExecutorUsedForFailure.

@Test
public void callbackExecutorUsedForFailure() throws InterruptedException {
    Executor executor = spy(new Executor() {

        @Override
        public void execute(Runnable command) {
            command.run();
        }
    });
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).callbackExecutor(executor).build();
    CallMethod service = retrofit.create(CallMethod.class);
    Call<ResponseBody> call = service.getResponseBody();
    server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
    final CountDownLatch latch = new CountDownLatch(1);
    call.enqueue(new Callback<ResponseBody>() {

        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            throw new AssertionError();
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            latch.countDown();
        }
    });
    assertTrue(latch.await(2, TimeUnit.SECONDS));
    verify(executor).execute(any(Runnable.class));
    verifyNoMoreInteractions(executor);
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) CountDownLatch(java.util.concurrent.CountDownLatch) ResponseBody(okhttp3.ResponseBody) Executor(java.util.concurrent.Executor) Test(org.junit.Test)

Example 17 with Callback

use of okhttp3.Callback in project retrofit by square.

the class Crawler method crawlPage.

public void crawlPage(HttpUrl url) {
    // Skip hosts that we've visited many times.
    AtomicInteger hostnameCount = new AtomicInteger();
    AtomicInteger previous = hostnames.putIfAbsent(url.host(), hostnameCount);
    if (previous != null)
        hostnameCount = previous;
    if (hostnameCount.incrementAndGet() > 100)
        return;
    // Asynchronously visit URL.
    pageService.get(url).enqueue(new Callback<Page>() {

        @Override
        public void onResponse(Call<Page> call, Response<Page> response) {
            if (!response.isSuccessful()) {
                System.out.println(call.request().url() + ": failed: " + response.code());
                return;
            }
            // Print this page's URL and title.
            Page page = response.body();
            HttpUrl base = response.raw().request().url();
            System.out.println(base + ": " + page.title);
            // Enqueue its links for visiting.
            for (String link : page.links) {
                HttpUrl linkUrl = base.resolve(link);
                if (linkUrl != null && !fetchedUrls.add(linkUrl)) {
                    crawlPage(linkUrl);
                }
            }
        }

        @Override
        public void onFailure(Call<Page> call, Throwable t) {
            System.out.println(call.request().url() + ": failed: " + t);
        }
    });
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpUrl(okhttp3.HttpUrl)

Example 18 with Callback

use of okhttp3.Callback in project okhttp by square.

the class CallTest method exceptionThrownByOnResponseIsRedactedAndLogged.

@Test
public void exceptionThrownByOnResponseIsRedactedAndLogged() throws Exception {
    server.enqueue(new MockResponse());
    Request request = new Request.Builder().url(server.url("/secret")).build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            fail();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            throw new IOException("a");
        }
    });
    assertEquals("INFO: Callback failure for call to " + server.url("/") + "...", logHandler.take());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) Test(org.junit.Test)

Example 19 with Callback

use of okhttp3.Callback in project okhttp by square.

the class CallTest method canceledAfterResponseIsDeliveredBreaksStreamButSignalsOnce.

/**
   * There's a race condition where the cancel may apply after the stream has already been
   * processed.
   */
@Test
public void canceledAfterResponseIsDeliveredBreaksStreamButSignalsOnce() throws Exception {
    server.enqueue(new MockResponse().setBody("A"));
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> bodyRef = new AtomicReference<>();
    final AtomicBoolean failureRef = new AtomicBoolean();
    Request request = new Request.Builder().url(server.url("/a")).build();
    final Call call = client.newCall(request);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            failureRef.set(true);
            latch.countDown();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            call.cancel();
            try {
                bodyRef.set(response.body().string());
            } catch (IOException e) {
                // It is ok if this broke the stream.
                bodyRef.set("A");
                // We expect to not loop into onFailure in this case.
                throw e;
            } finally {
                latch.countDown();
            }
        }
    });
    latch.await();
    assertEquals("A", bodyRef.get());
    assertFalse(failureRef.get());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) MockResponse(okhttp3.mockwebserver.MockResponse) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test)

Example 20 with Callback

use of okhttp3.Callback in project okhttp by square.

the class CallTest method legalToExecuteTwiceCloning_Async.

@Test
public void legalToExecuteTwiceCloning_Async() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));
    server.enqueue(new MockResponse().setBody("def"));
    Request request = new Request.Builder().url(server.url("/")).build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    Call cloned = call.clone();
    cloned.enqueue(callback);
    RecordedResponse firstResponse = callback.await(request.url()).assertSuccessful();
    RecordedResponse secondResponse = callback.await(request.url()).assertSuccessful();
    Set<String> bodies = new LinkedHashSet<>();
    bodies.add(firstResponse.getBody());
    bodies.add(secondResponse.getBody());
    assertTrue(bodies.contains("abc"));
    assertTrue(bodies.contains("def"));
}
Also used : LinkedHashSet(java.util.LinkedHashSet) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Aggregations

ResponseBody (okhttp3.ResponseBody)178 DateTimeRfc1123 (com.microsoft.rest.DateTimeRfc1123)166 DateTime (org.joda.time.DateTime)166 ServiceCall (com.microsoft.rest.ServiceCall)140 IOException (java.io.IOException)68 Test (org.junit.Test)60 MockResponse (okhttp3.mockwebserver.MockResponse)58 List (java.util.List)54 PagedList (com.microsoft.azure.PagedList)52 ServiceResponseWithHeaders (com.microsoft.rest.ServiceResponseWithHeaders)52 Call (okhttp3.Call)49 Request (okhttp3.Request)49 Response (okhttp3.Response)48 Callback (okhttp3.Callback)41 RequestBody (okhttp3.RequestBody)28 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)27 CountDownLatch (java.util.concurrent.CountDownLatch)16 OkHttpClient (okhttp3.OkHttpClient)15 Call (retrofit2.Call)15 Callback (retrofit2.Callback)14