Search in sources :

Example 21 with ForestResponse

use of com.dtflys.forest.http.ForestResponse in project forest by dromara.

the class TestTimeoutClient method testConnectTimeout.

@Test
public void testConnectTimeout() {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START));
    ForestRequest request = timeoutClient.testConnectTimeout();
    assertThat(request).isNotNull();
    assertThat(request.getConnectTimeout()).isEqualTo(10);
    ForestResponse response = (ForestResponse) request.execute(ForestResponse.class);
    assertThat(response).isNotNull();
    assertThat(response.isTimeout()).isTrue();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) ForestResponse(com.dtflys.forest.http.ForestResponse) ForestRequest(com.dtflys.forest.http.ForestRequest) Test(org.junit.Test) BaseClientTest(com.dtflys.test.http.BaseClientTest)

Example 22 with ForestResponse

use of com.dtflys.forest.http.ForestResponse in project forest by dromara.

the class TestErrorClient method testErrorGet.

@Test
public void testErrorGet() {
    server.enqueue(new MockResponse().setResponseCode(404).setBody(EXPECTED));
    AtomicReference<String> content = new AtomicReference<>(null);
    assertThat(getClient.errorGet((ex, request, response) -> {
        content.set(response.getContent());
        assertThat(response).isNotNull().extracting(ForestResponse::isError, ForestResponse::getStatusCode, ForestResponse::getContent).contains(true, 404, EXPECTED);
        response.setResult("onError=true");
    })).isNotNull().isEqualTo("onError=true");
    assertThat(content.get()).isNotNull().isEqualTo(EXPECTED);
}
Also used : BeforeClass(org.junit.BeforeClass) ForestNetworkException(com.dtflys.forest.exceptions.ForestNetworkException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Test(org.junit.Test) AtomicReference(java.util.concurrent.atomic.AtomicReference) ForestResponse(com.dtflys.forest.http.ForestResponse) BackOffRetryer(com.dtflys.forest.retryer.BackOffRetryer) ForestConfiguration(com.dtflys.forest.config.ForestConfiguration) Rule(org.junit.Rule) GetClient(com.dtflys.test.http.client.GetClient) MockWebServer(okhttp3.mockwebserver.MockWebServer) MockResponse(okhttp3.mockwebserver.MockResponse) HttpBackend(com.dtflys.forest.backend.HttpBackend) MockResponse(okhttp3.mockwebserver.MockResponse) ForestResponse(com.dtflys.forest.http.ForestResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Example 23 with ForestResponse

use of com.dtflys.forest.http.ForestResponse in project forest by dromara.

the class DefaultLogHandler method responseLoggingContent.

/**
 * 请求响应日志打印的内容
 * @param responseLogMessage 请求响应日志字符串
 * @return 请求响应日志字符串
 */
protected String responseLoggingContent(ResponseLogMessage responseLogMessage) {
    ForestResponse response = responseLogMessage.getResponse();
    if (response != null && response.getException() != null) {
        return "Response: [Network Error]: " + response.getException().getMessage();
    }
    int status = responseLogMessage.getStatus();
    if (status >= 0) {
        return "Response: Status = " + responseLogMessage.getStatus() + ", Time = " + responseLogMessage.getTime() + "ms";
    } else {
        return "Response: [Network Error]: Unknown Network Error!";
    }
}
Also used : ForestResponse(com.dtflys.forest.http.ForestResponse)

Example 24 with ForestResponse

use of com.dtflys.forest.http.ForestResponse in project forest by dromara.

the class ResultHandler method getResult.

public Object getResult(ForestRequest request, ForestResponse response, Type resultType, Class resultClass) {
    if (request.isDownloadFile()) {
        return null;
    }
    Object result = response.getResult();
    if (result != null && resultClass.isAssignableFrom(result.getClass())) {
        return result;
    }
    if (isReceivedResponseData(response)) {
        try {
            if (void.class.isAssignableFrom(resultClass)) {
                return null;
            }
            if (ForestResponse.class.isAssignableFrom(resultClass) || ForestRequest.class.isAssignableFrom(resultClass)) {
                if (resultType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) resultType;
                    Class rowClass = (Class) parameterizedType.getRawType();
                    if (ForestResponse.class.isAssignableFrom(rowClass) || ForestRequest.class.isAssignableFrom(resultClass)) {
                        Type realType = parameterizedType.getActualTypeArguments()[0];
                        Class realClass = ReflectUtils.toClass(parameterizedType.getActualTypeArguments()[0]);
                        if (realClass == null) {
                            realClass = String.class;
                        }
                        Object realResult = getResult(request, response, realType, realClass);
                        response.setResult(realResult);
                    }
                } else {
                    Object realResult = getResult(request, response, Object.class, Object.class);
                    response.setResult(realResult);
                }
                return response;
            }
            if (Future.class.isAssignableFrom(resultClass)) {
                if (resultType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) resultType;
                    Class rowClass = (Class) parameterizedType.getRawType();
                    if (Future.class.isAssignableFrom(rowClass)) {
                        Type realType = parameterizedType.getActualTypeArguments()[0];
                        Class realClass = ReflectUtils.toClass(parameterizedType.getActualTypeArguments()[0]);
                        return getResult(request, response, realType, realClass);
                    }
                }
            }
            if (resultClass.isArray()) {
                if (byte[].class.isAssignableFrom(resultClass)) {
                    return response.getByteArray();
                }
            }
            Object attFile = request.getAttachment(DownloadLifeCycle.ATTACHMENT_NAME_FILE);
            if (attFile != null && attFile instanceof File) {
                ForestConverter converter = request.getConfiguration().getConverter(ForestDataType.JSON);
                return converter.convertToJavaObject(attFile, resultClass);
            }
            String responseText = null;
            if (result != null && CharSequence.class.isAssignableFrom(result.getClass())) {
                responseText = result.toString();
            } else if (CharSequence.class.isAssignableFrom(resultClass)) {
                try {
                    responseText = response.readAsString();
                } catch (Throwable th) {
                    request.getLifeCycleHandler().handleError(request, response, th);
                }
            } else {
                try {
                    responseText = response.getContent();
                } catch (Throwable th) {
                    request.getLifeCycleHandler().handleError(request, response, th);
                }
            }
            response.setContent(responseText);
            if (CharSequence.class.isAssignableFrom(resultClass)) {
                return responseText;
            }
            if (InputStream.class.isAssignableFrom(resultClass)) {
                return response.getInputStream();
            }
            ContentType contentType = response.getContentType();
            if (request.getDecoder() != null) {
                if (contentType != null && contentType.canReadAsString()) {
                    return request.getDecoder().convertToJavaObject(responseText, resultType);
                } else {
                    return request.getDecoder().convertToJavaObject(response.getByteArray(), resultType);
                }
            }
            ForestDataType dataType = request.getDataType();
            ForestConverter converter = request.getConfiguration().getConverter(dataType);
            if (contentType != null && contentType.canReadAsString()) {
                return converter.convertToJavaObject(responseText, resultType);
            }
            Charset charset = null;
            String resCharset = response.getCharset();
            if (resCharset != null) {
                charset = Charset.forName(resCharset);
            }
            return converter.convertToJavaObject(response.getByteArray(), resultType, charset);
        } catch (Exception e) {
            throw new ForestHandlerException(e, request, response);
        }
    } else if (ForestResponse.class.isAssignableFrom(resultClass)) {
        return response;
    }
    return null;
}
Also used : ForestResponse(com.dtflys.forest.http.ForestResponse) ContentType(com.dtflys.forest.backend.ContentType) ForestDataType(com.dtflys.forest.utils.ForestDataType) Charset(java.nio.charset.Charset) ForestRequest(com.dtflys.forest.http.ForestRequest) ForestHandlerException(com.dtflys.forest.exceptions.ForestHandlerException) ParameterizedType(java.lang.reflect.ParameterizedType) ContentType(com.dtflys.forest.backend.ContentType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) ForestDataType(com.dtflys.forest.utils.ForestDataType) ForestHandlerException(com.dtflys.forest.exceptions.ForestHandlerException) ForestConverter(com.dtflys.forest.converter.ForestConverter) File(java.io.File)

Example 25 with ForestResponse

use of com.dtflys.forest.http.ForestResponse in project forest by dromara.

the class TestInterceptorChain method testInterceptorChain.

@Test
public void testInterceptorChain() {
    final AtomicInteger count = new AtomicInteger(0);
    final AtomicBoolean inter1Before = new AtomicBoolean(false);
    final AtomicBoolean inter2Before = new AtomicBoolean(false);
    final AtomicBoolean inter3Before = new AtomicBoolean(false);
    final AtomicBoolean inter1Success = new AtomicBoolean(false);
    final AtomicBoolean inter2Success = new AtomicBoolean(false);
    final AtomicBoolean inter1Error = new AtomicBoolean(false);
    final AtomicBoolean inter2Error = new AtomicBoolean(false);
    final AtomicBoolean inter1After = new AtomicBoolean(false);
    final AtomicBoolean inter2After = new AtomicBoolean(false);
    final AtomicBoolean only2After = new AtomicBoolean(false);
    Interceptor interceptor1 = new Interceptor() {

        @Override
        public boolean beforeExecute(ForestRequest request) {
            inter1Before.set(true);
            return true;
        }

        @Override
        public void onSuccess(Object data, ForestRequest request, ForestResponse response) {
            inter1Success.set(true);
            count.incrementAndGet();
        }

        @Override
        public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
            inter1Error.set(true);
        }

        @Override
        public void afterExecute(ForestRequest request, ForestResponse response) {
            inter1After.set(true);
        }
    };
    Interceptor interceptor2 = new Interceptor() {

        @Override
        public boolean beforeExecute(ForestRequest request) {
            inter2Before.set(true);
            return true;
        }

        @Override
        public void onSuccess(Object data, ForestRequest request, ForestResponse response) {
            inter2Success.set(true);
            count.incrementAndGet();
        }

        @Override
        public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
            inter2Error.set(true);
        }

        @Override
        public void afterExecute(ForestRequest request, ForestResponse response) {
            inter2After.set(true);
            only2After.set(true);
        }
    };
    Interceptor interceptor3 = new Interceptor() {

        @Override
        public boolean beforeExecute(ForestRequest request) {
            inter3Before.set(true);
            return false;
        }

        @Override
        public void onSuccess(Object data, ForestRequest request, ForestResponse response) {
        }

        @Override
        public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
        }

        @Override
        public void afterExecute(ForestRequest request, ForestResponse response) {
        }
    };
    InterceptorChain chain = new InterceptorChain();
    chain.addInterceptor(interceptor1).addInterceptor(interceptor2);
    assertEquals(2, chain.getInterceptorSize());
    assertTrue(chain.beforeExecute(null));
    assertTrue(inter1Before.get());
    assertTrue(inter2Before.get());
    chain.addInterceptor(interceptor3);
    assertFalse(inter3Before.get());
    chain.onSuccess(null, null, null);
    assertTrue(inter1Success.get());
    assertTrue(inter2Success.get());
    assertEquals(2, count.get());
    chain.onError(null, null, null);
    assertTrue(inter1Error.get());
    assertTrue(inter2Error.get());
    chain.afterExecute(null, null);
    assertTrue(inter1After.get());
    assertTrue(inter2After.get());
    assertTrue(only2After.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) InterceptorChain(com.dtflys.forest.interceptor.InterceptorChain) ForestResponse(com.dtflys.forest.http.ForestResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) ForestRequest(com.dtflys.forest.http.ForestRequest) Interceptor(com.dtflys.forest.interceptor.Interceptor) Test(org.junit.Test)

Aggregations

ForestResponse (com.dtflys.forest.http.ForestResponse)46 ForestRequest (com.dtflys.forest.http.ForestRequest)38 Test (org.junit.Test)37 MockResponse (okhttp3.mockwebserver.MockResponse)34 BaseClientTest (com.dtflys.test.http.BaseClientTest)31 HttpBackend (com.dtflys.forest.backend.HttpBackend)30 ForestConfiguration (com.dtflys.forest.config.ForestConfiguration)30 AtomicReference (java.util.concurrent.atomic.AtomicReference)30 MockWebServer (okhttp3.mockwebserver.MockWebServer)30 BeforeClass (org.junit.BeforeClass)30 Rule (org.junit.Rule)30 MockServerRequest.mockRequest (com.dtflys.forest.mock.MockServerRequest.mockRequest)29 CountDownLatch (java.util.concurrent.CountDownLatch)29 TimeUnit (java.util.concurrent.TimeUnit)29 AssertionsForClassTypes.assertThat (org.assertj.core.api.AssertionsForClassTypes.assertThat)29 ForestNetworkException (com.dtflys.forest.exceptions.ForestNetworkException)3 ForestRuntimeException (com.dtflys.forest.exceptions.ForestRuntimeException)3 HttpclientForestResponseFactory (com.dtflys.forest.backend.httpclient.response.HttpclientForestResponseFactory)2 ForestRetryException (com.dtflys.forest.exceptions.ForestRetryException)2 Date (java.util.Date)2