Search in sources :

Example 36 with Dispatcher

use of okhttp3.Dispatcher in project okhttp by square.

the class WebSocketHttpTest method readTimeoutAppliesWithinFrames.

/**
 * There's no read timeout when reading the first byte of a new frame. But as soon as we start
 * reading a frame we enable the read timeout. In this test we have the server returning the first
 * byte of a frame but no more frames.
 */
@Test
public void readTimeoutAppliesWithinFrames() {
    webServer.setDispatcher(new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) {
            return upgradeResponse(request).setBody(// Truncated frame.
            new Buffer().write(ByteString.decodeHex("81"))).removeHeader("Content-Length").setSocketPolicy(SocketPolicy.KEEP_OPEN);
        }
    });
    WebSocket webSocket = newWebSocket();
    clientListener.assertOpen();
    clientListener.assertFailure(SocketTimeoutException.class, "timeout", "Read timed out");
    assertThat(webSocket.close(1000, null)).isFalse();
}
Also used : RecordedRequest(mockwebserver3.RecordedRequest) Buffer(okio.Buffer) MockResponse(mockwebserver3.MockResponse) Dispatcher(mockwebserver3.Dispatcher) WebSocket(okhttp3.WebSocket) Test(org.junit.jupiter.api.Test)

Example 37 with Dispatcher

use of okhttp3.Dispatcher in project flink by apache.

the class FlinkDistribution method startFlinkCluster.

public void startFlinkCluster() throws IOException {
    LOG.info("Starting Flink cluster.");
    AutoClosableProcess.create(bin.resolve("start-cluster.sh").toAbsolutePath().toString()).setEnv(env -> env.remove("FLINK_LOG_DIR")).runBlocking();
    final OkHttpClient client = new OkHttpClient();
    final Request request = new Request.Builder().get().url("http://localhost:8081/taskmanagers").build();
    Exception reportedException = null;
    for (int retryAttempt = 0; retryAttempt < 30; retryAttempt++) {
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                final String json = response.body().string();
                final JsonNode taskManagerList = OBJECT_MAPPER.readTree(json).get("taskmanagers");
                if (taskManagerList != null && taskManagerList.size() > 0) {
                    LOG.info("Dispatcher REST endpoint is up.");
                    return;
                }
            }
        } catch (IOException ioe) {
            reportedException = ExceptionUtils.firstOrSuppressed(ioe, reportedException);
        }
        LOG.info("Waiting for dispatcher REST endpoint to come up...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            reportedException = ExceptionUtils.firstOrSuppressed(e, reportedException);
        }
    }
    throw new AssertionError("Dispatcher REST endpoint did not start in time.", reportedException);
}
Also used : LoggerFactory(org.slf4j.LoggerFactory) ExceptionUtils(org.apache.flink.util.ExceptionUtils) CompletableFuture(java.util.concurrent.CompletableFuture) JsonNode(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode) Function(java.util.function.Function) UnmodifiableConfiguration(org.apache.flink.configuration.UnmodifiableConfiguration) TestUtils(org.apache.flink.tests.util.TestUtils) ArrayList(java.util.ArrayList) AutoClosableProcess(org.apache.flink.tests.util.AutoClosableProcess) Matcher(java.util.regex.Matcher) ObjectMapper(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper) Level(org.slf4j.event.Level) Duration(java.time.Duration) Response(okhttp3.Response) Path(java.nio.file.Path) Request(okhttp3.Request) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Files(java.nio.file.Files) Collection(java.util.Collection) Configuration(org.apache.flink.configuration.Configuration) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) List(java.util.List) JobID(org.apache.flink.api.common.JobID) OkHttpClient(okhttp3.OkHttpClient) Stream(java.util.stream.Stream) GlobalConfiguration(org.apache.flink.configuration.GlobalConfiguration) Optional(java.util.Optional) BufferedReader(java.io.BufferedReader) Pattern(java.util.regex.Pattern) FileUtils(org.apache.flink.tests.util.util.FileUtils) FilenameUtils(org.apache.commons.io.FilenameUtils) Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) JsonNode(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 38 with Dispatcher

use of okhttp3.Dispatcher in project pinpoint by naver.

the class OkHttpClient_3_0_0_to_3_3_x_IT method enqueue.

@Test
public void enqueue() throws Exception {
    Request request = new Request.Builder().url(webServer.getCallHttpUrl()).build();
    OkHttpClient client = new OkHttpClient();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Response> responseRef = new AtomicReference<>(null);
    client.newCall(request).enqueue(new Callback() {

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

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            responseRef.set(response);
            latch.countDown();
        }
    });
    latch.await(3, TimeUnit.SECONDS);
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.awaitTrace(event(ASYNC.getName(), "Asynchronous Invocation"), 20, 3000);
    verifier.printCache();
    Method realCallEnqueueMethod = Class.forName("okhttp3.RealCall").getDeclaredMethod("enqueue", Class.forName("okhttp3.Callback"));
    verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), realCallEnqueueMethod));
    Method dispatcherEnqueueMethod = Class.forName("okhttp3.Dispatcher").getDeclaredMethod("enqueue", Class.forName("okhttp3.RealCall$AsyncCall"));
    verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), dispatcherEnqueueMethod));
    verifier.verifyTrace(event(ASYNC.getName(), "Asynchronous Invocation"));
    Method executeMethod = Class.forName("okhttp3.RealCall$AsyncCall").getDeclaredMethod("execute");
    verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), executeMethod));
    Method sendRequestMethod = Class.forName("okhttp3.internal.http.HttpEngine").getDeclaredMethod("sendRequest");
    verifier.verifyTrace(event(OK_HTTP_CLIENT.getName(), sendRequestMethod, null, null, webServer.getHostAndPort(), annotation("http.url", request.url().toString())));
    String hostAndPort = HostAndPort.toHostAndPortString(request.url().host(), request.url().port());
    Method connectMethod = Class.forName("okhttp3.internal.http.HttpEngine").getDeclaredMethod("connect");
    verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), connectMethod, annotation("http.internal.display", hostAndPort)));
    Response response = responseRef.get();
    Method readResponseMethod = Class.forName("okhttp3.internal.http.HttpEngine").getDeclaredMethod("readResponse");
    verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), readResponseMethod, annotation("http.status.code", response.code())));
    verifier.verifyTraceCount(0);
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) Method(java.lang.reflect.Method) CountDownLatch(java.util.concurrent.CountDownLatch) PluginTestVerifier(com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier) Response(okhttp3.Response) Callback(okhttp3.Callback) Test(org.junit.Test)

Example 39 with Dispatcher

use of okhttp3.Dispatcher in project pinpoint by naver.

the class OkHttpClient_3_4_0_BaseIT method enqueue.

@Test
public void enqueue() throws Exception {
    Request request = new Request.Builder().url(webServer.getCallHttpUrl()).build();
    OkHttpClient client = new OkHttpClient();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Response> responseRef = new AtomicReference<>(null);
    client.newCall(request).enqueue(new Callback() {

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

        @Override
        public void onResponse(Call call, Response response) {
            responseRef.set(response);
            latch.countDown();
        }
    });
    latch.await(3, TimeUnit.SECONDS);
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.awaitTrace(event(ASYNC.getName(), "Asynchronous Invocation"), 20, 3000);
    verifier.printCache();
    Method realCallEnqueueMethod = Class.forName("okhttp3.RealCall").getDeclaredMethod("enqueue", Class.forName("okhttp3.Callback"));
    verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), realCallEnqueueMethod));
    Method dispatcherEnqueueMethod = Class.forName("okhttp3.Dispatcher").getDeclaredMethod("enqueue", Class.forName("okhttp3.RealCall$AsyncCall"));
    verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), dispatcherEnqueueMethod));
    verifier.verifyTrace(event(ASYNC.getName(), "Asynchronous Invocation"));
    Method executeMethod = Class.forName("okhttp3.RealCall$AsyncCall").getDeclaredMethod("execute");
    verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), executeMethod));
    Response response = responseRef.get();
    Method interceptMethod = Class.forName("okhttp3.internal.http.BridgeInterceptor").getDeclaredMethod("intercept", Class.forName("okhttp3.Interceptor$Chain"));
    verifier.verifyTrace(event(OK_HTTP_CLIENT.getName(), interceptMethod, null, null, webServer.getHostAndPort(), annotation("http.url", request.url().toString()), annotation("http.status.code", response.code())));
    String hostAndPort = HostAndPort.toHostAndPortString(request.url().host(), request.url().port());
    Method connectMethod = getConnectMethod(Class.forName("okhttp3.internal.connection.RealConnection"));
    verifier.verifyTrace(event(OK_HTTP_CLIENT_INTERNAL.getName(), connectMethod, annotation("http.internal.display", hostAndPort)));
    verifier.verifyTraceCount(0);
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) Method(java.lang.reflect.Method) CountDownLatch(java.util.concurrent.CountDownLatch) PluginTestVerifier(com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier) Response(okhttp3.Response) Callback(okhttp3.Callback) Test(org.junit.Test)

Example 40 with Dispatcher

use of okhttp3.Dispatcher in project MVPArms by JessYanCoding.

the class ClientModule method provideClient.

/**
 * 提供 {@link OkHttpClient}
 *
 * @param application     {@link Application}
 * @param configuration   {@link OkhttpConfiguration}
 * @param builder         {@link OkHttpClient.Builder}
 * @param intercept       {@link Interceptor}
 * @param interceptors    {@link List<Interceptor>}
 * @param handler         {@link GlobalHttpHandler}
 * @param executorService {@link ExecutorService}
 * @return {@link OkHttpClient}
 */
@Singleton
@Provides
static OkHttpClient provideClient(Application application, @Nullable OkhttpConfiguration configuration, OkHttpClient.Builder builder, Interceptor intercept, @Nullable List<Interceptor> interceptors, @Nullable GlobalHttpHandler handler, ExecutorService executorService) {
    builder.connectTimeout(TIME_OUT, TimeUnit.SECONDS).readTimeout(TIME_OUT, TimeUnit.SECONDS).addNetworkInterceptor(intercept);
    if (handler != null) {
        builder.addInterceptor(chain -> chain.proceed(handler.onHttpRequestBefore(chain, chain.request())));
    }
    // 如果外部提供了 Interceptor 的集合则遍历添加
    if (interceptors != null) {
        for (Interceptor interceptor : interceptors) {
            builder.addInterceptor(interceptor);
        }
    }
    // 为 OkHttp 设置默认的线程池
    builder.dispatcher(new Dispatcher(executorService));
    if (configuration != null) {
        configuration.configOkhttp(application, builder);
    }
    return builder.build();
}
Also used : Dispatcher(okhttp3.Dispatcher) RequestInterceptor(com.jess.arms.http.log.RequestInterceptor) Interceptor(okhttp3.Interceptor) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Aggregations

Dispatcher (okhttp3.Dispatcher)42 OkHttpClient (okhttp3.OkHttpClient)34 MockResponse (okhttp3.mockwebserver.MockResponse)28 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)26 Dispatcher (okhttp3.mockwebserver.Dispatcher)25 IOException (java.io.IOException)19 Before (org.junit.Before)18 MockWebServer (okhttp3.mockwebserver.MockWebServer)16 Test (org.junit.Test)15 Call (okhttp3.Call)11 LruNormalizedCacheFactory (com.apollographql.apollo.cache.normalized.lru.LruNormalizedCacheFactory)10 ArrayList (java.util.ArrayList)8 Request (okhttp3.Request)8 Response (okhttp3.Response)8 Interceptor (okhttp3.Interceptor)7 ResponseBody (okhttp3.ResponseBody)7 Gson (com.google.gson.Gson)5 CloudantClient (com.cloudant.client.api.CloudantClient)4 RefineTest (com.google.refine.RefineTest)4 DataExtensionConfig (com.google.refine.model.recon.ReconciledDataExtensionJob.DataExtensionConfig)4