Search in sources :

Example 6 with EventListener

use of okhttp3.EventListener in project okhttp by square.

the class DuplexTest method duplexWithRedirect.

/**
 * Duplex calls that have follow-ups are weird. By the time we know there's a follow-up we've
 * already split off another thread to stream the request body. Because we permit at most one
 * exchange at a time we break the request stream out from under that writer.
 */
@Test
public void duplexWithRedirect() throws Exception {
    enableProtocol(Protocol.HTTP_2);
    CountDownLatch duplexResponseSent = new CountDownLatch(1);
    listener = new RecordingEventListener() {

        @Override
        public void responseHeadersEnd(Call call, Response response) {
            try {
                // Wait for the server to send the duplex response before acting on the 301 response
                // and resetting the stream.
                duplexResponseSent.await();
            } catch (InterruptedException e) {
                throw new AssertionError();
            }
            super.responseHeadersEnd(call, response);
        }
    };
    client = client.newBuilder().eventListener(listener).build();
    MockDuplexResponseBody mockDuplexResponseBody = enqueueResponseWithBody(new MockResponse().clearHeaders().setResponseCode(HttpURLConnection.HTTP_MOVED_PERM).addHeader("Location: /b"), new MockDuplexResponseBody().sendResponse("/a has moved!\n", duplexResponseSent).requestIOException().exhaustResponse());
    server.enqueue(new MockResponse().setBody("this is /b"));
    Call call = client.newCall(new Request.Builder().url(server.url("/")).post(new AsyncRequestBody()).build());
    try (Response response = call.execute()) {
        BufferedSource responseBody = response.body().source();
        assertThat(responseBody.readUtf8Line()).isEqualTo("this is /b");
    }
    BufferedSink requestBody = ((AsyncRequestBody) call.request().body()).takeSink();
    try {
        requestBody.writeUtf8("request body\n");
        requestBody.flush();
        fail();
    } catch (IOException expected) {
        assertThat(expected.getMessage()).isEqualTo("stream was reset: CANCEL");
    }
    mockDuplexResponseBody.awaitSuccess();
    assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "ProxySelectStart", "ProxySelectEnd", "DnsStart", "DnsEnd", "ConnectStart", "SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "RequestBodyStart", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd", "RequestFailed");
}
Also used : MockResponse(mockwebserver3.MockResponse) AsyncRequestBody(okhttp3.internal.duplex.AsyncRequestBody) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) MockResponse(mockwebserver3.MockResponse) MockDuplexResponseBody(mockwebserver3.internal.duplex.MockDuplexResponseBody) BufferedSource(okio.BufferedSource) Test(org.junit.jupiter.api.Test)

Example 7 with EventListener

use of okhttp3.EventListener in project okhttp by square.

the class ClientAuthTest method invalidClientAuthEvents.

@Test
public void invalidClientAuthEvents() throws Throwable {
    server.enqueue(new MockResponse().setBody("abc"));
    clientCert = new HeldCertificate.Builder().signedBy(clientIntermediateCa).serialNumber(4L).commonName("Jethro Willis").addSubjectAlternativeName("jethrowillis.com").validityInterval(1, 2).build();
    OkHttpClient client = buildClient(clientCert, clientIntermediateCa.certificate());
    RecordingEventListener listener = new RecordingEventListener();
    client = client.newBuilder().eventListener(listener).build();
    SSLSocketFactory socketFactory = buildServerSslSocketFactory();
    server.useHttps(socketFactory, false);
    server.requireClientAuth();
    Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
    try {
        call.execute();
        fail();
    } catch (IOException expected) {
    }
    // Observed Events are variable
    // JDK 14
    // CallStart, ProxySelectStart, ProxySelectEnd, DnsStart, DnsEnd, ConnectStart, SecureConnectStart,
    // SecureConnectEnd, ConnectEnd, ConnectionAcquired, RequestHeadersStart, RequestHeadersEnd,
    // ResponseFailed, ConnectionReleased, CallFailed
    // JDK 8
    // CallStart, ProxySelectStart, ProxySelectEnd, DnsStart, DnsEnd, ConnectStart, SecureConnectStart,
    // ConnectFailed, CallFailed
    // Gradle - JDK 11
    // CallStart, ProxySelectStart, ProxySelectEnd, DnsStart, DnsEnd, ConnectStart, SecureConnectStart,
    // SecureConnectEnd, ConnectFailed, CallFailed
    List<String> recordedEventTypes = listener.recordedEventTypes();
    assertThat(recordedEventTypes).startsWith("CallStart", "ProxySelectStart", "ProxySelectEnd", "DnsStart", "DnsEnd", "ConnectStart", "SecureConnectStart");
    assertThat(recordedEventTypes).endsWith("CallFailed");
}
Also used : MockResponse(mockwebserver3.MockResponse) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) HeldCertificate(okhttp3.tls.HeldCertificate) Request(okhttp3.Request) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) RecordingEventListener(okhttp3.RecordingEventListener) Test(org.junit.jupiter.api.Test)

Example 8 with EventListener

use of okhttp3.EventListener in project nzbhydra2 by theotherp.

the class WebHooks method onSearchEvent.

@Async
@EventListener
public void onSearchEvent(SearchEvent searchEvent) throws IOException {
    String searchHook = System.getProperty("nzbhydra.hooks.search");
    if (!Strings.isNullOrEmpty(searchHook)) {
        if (searchEvent.getSearchRequest().getSource() == SearchSource.INTERNAL) {
            try {
                OkHttpClient client = requestFactory.getOkHttpClientBuilder(URI.create(searchHook)).build();
                String content = objectMapper.writeValueAsString(searchEvent.getSearchRequest());
                Response response = client.newCall(new Builder().url(searchHook).method("PUT", RequestBody.create(MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_VALUE), content)).build()).execute();
                response.close();
                logger.debug("Called search web hook with response {}", response);
            } catch (IOException e) {
                logger.error("Unable to execute webhook to {} on search event", searchHook);
            }
        }
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Builder(okhttp3.Request.Builder) IOException(java.io.IOException) Async(org.springframework.scheduling.annotation.Async) EventListener(org.springframework.context.event.EventListener)

Aggregations

IOException (java.io.IOException)6 OkHttpClient (okhttp3.OkHttpClient)6 Request (okhttp3.Request)4 Response (okhttp3.Response)4 Test (org.junit.jupiter.api.Test)4 MockResponse (mockwebserver3.MockResponse)3 Call (okhttp3.Call)3 Builder (okhttp3.Request.Builder)2 EventListener (org.springframework.context.event.EventListener)2 Async (org.springframework.scheduling.annotation.Async)2 Request (com.android.volley.Request)1 StringRequest (com.android.volley.toolbox.StringRequest)1 FailsafeExecutor (dev.failsafe.FailsafeExecutor)1 EventListener (dev.failsafe.event.EventListener)1 ExecutionCompletedEvent (dev.failsafe.event.ExecutionCompletedEvent)1 FailsafeCall (dev.failsafe.okhttp.FailsafeCall)1 Testing (dev.failsafe.testing.Testing)1 Collections (java.util.Collections)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1