Search in sources :

Example 1 with ContentType

use of com.dtflys.forest.backend.ContentType in project forest by dromara.

the class HttpclientLogBodyMessage method getBodyString.

@Override
public String getBodyString() {
    if (entity == null) {
        return null;
    }
    Header contentTypeHeader = entity.getContentType();
    ContentType contentType = new ContentType(contentTypeHeader.getValue());
    if (contentType.isMultipart()) {
        Class[] paramTypes = new Class[0];
        Object[] args = new Object[0];
        List<FormBodyPart> parts = null;
        try {
            Method getMultipartMethod = entity.getClass().getDeclaredMethod("getMultipart", paramTypes);
            getMultipartMethod.setAccessible(true);
            Object multipart = getMultipartMethod.invoke(entity, args);
            if (multipart != null) {
                Method getBodyPartsMethod = multipart.getClass().getDeclaredMethod("getBodyParts", paramTypes);
                getBodyPartsMethod.setAccessible(true);
                parts = (List<FormBodyPart>) getBodyPartsMethod.invoke(multipart, args);
            }
        } catch (NoSuchMethodException e) {
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        }
        Long contentLength = null;
        try {
            contentLength = entity.getContentLength();
        } catch (Throwable th) {
        }
        if (parts == null) {
            String result = "[" + entity.getContentType().getValue();
            if (contentLength != null) {
                result += "; length=" + contentLength;
            }
            return result + "]";
        } else {
            StringBuilder builder = new StringBuilder();
            builder.append("[").append(entity.getContentType().getValue());
            if (contentLength != null) {
                builder.append("; length=").append(contentLength);
            }
            builder.append("] parts:");
            for (FormBodyPart part : parts) {
                ContentBody partBody = part.getBody();
                MinimalField disposition = part.getHeader().getField("Content-Disposition");
                builder.append("\n             -- [").append(disposition.getBody());
                if (partBody instanceof StringBody) {
                    Reader reader = ((StringBody) partBody).getReader();
                    BufferedReader bufferedReader = new BufferedReader(reader);
                    String value = null;
                    try {
                        value = getLogContentFormBufferedReader(bufferedReader);
                    } catch (IOException e) {
                    }
                    builder.append("; content-type=\"").append(((StringBody) partBody).getContentType()).append("\"");
                    builder.append("; value=\"").append(value).append("\"]");
                } else {
                    Long length = null;
                    length = partBody.getContentLength();
                    if (length != null) {
                        builder.append("; length=").append(length);
                    }
                    if (partBody instanceof HttpclientMultipartFileBody) {
                        builder.append("; content-type=\"").append(((HttpclientMultipartFileBody) partBody).getContentType()).append("\"");
                    }
                    builder.append("]");
                }
            }
            return builder.toString();
        }
    } else if (contentType.isBinary()) {
        return "[Binary length=" + entity.getContentLength() + "]";
    }
    return getLogContentForStringBody(entity);
}
Also used : ContentType(com.dtflys.forest.backend.ContentType) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) Method(java.lang.reflect.Method) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) HttpclientMultipartFileBody(com.dtflys.forest.backend.httpclient.body.HttpclientMultipartFileBody) FormBodyPart(org.apache.http.entity.mime.FormBodyPart) Header(org.apache.http.Header) ContentBody(org.apache.http.entity.mime.content.ContentBody) StringBody(org.apache.http.entity.mime.content.StringBody) MinimalField(org.apache.http.entity.mime.MinimalField) BufferedReader(java.io.BufferedReader)

Example 2 with ContentType

use of com.dtflys.forest.backend.ContentType in project forest by dromara.

the class OkHttp3LogBodyMessage method getBodyString.

@Override
public String getBodyString() {
    if (requestBody == null) {
        return null;
    }
    MediaType mediaType = requestBody.contentType();
    if (mediaType == null) {
        return getLogContentForStringBody(this.requestBody);
    }
    ContentType contentType = new ContentType(mediaType.toString());
    if (contentType.isMultipart()) {
        MultipartBody multipartBody = (MultipartBody) requestBody;
        String boundary = multipartBody.boundary();
        Long contentLength = null;
        try {
            contentLength = multipartBody.contentLength();
        } catch (IOException e) {
        }
        StringBuilder builder = new StringBuilder();
        builder.append("[").append("boundary=").append(boundary);
        if (contentLength != null) {
            builder.append("; length=").append(contentLength);
        }
        builder.append("] parts:");
        List<MultipartBody.Part> parts = multipartBody.parts();
        for (MultipartBody.Part part : parts) {
            RequestBody partBody = part.body();
            List<String> disposition = part.headers().values("Content-Disposition");
            builder.append("\n             -- [").append(disposition.get(0));
            MediaType partMediaType = partBody.contentType();
            if (partMediaType == null) {
                builder.append("; content-type=\"").append(partBody.contentType()).append("\"");
                builder.append("; value=\"").append(getLogContentForStringBody(partBody)).append("\"]");
            } else {
                Long length = null;
                try {
                    length = partBody.contentLength();
                } catch (IOException e) {
                }
                if (length != null) {
                    builder.append("; length=").append(length);
                }
                builder.append("; content-type=\"").append(partBody.contentType()).append("\"");
                builder.append("]");
            }
        }
        return builder.toString();
    } else if (contentType.isBinary()) {
        try {
            return "[Binary length=" + requestBody.contentLength() + "]";
        } catch (IOException e) {
            throw new ForestRuntimeException(e);
        }
    }
    return getLogContentForStringBody(this.requestBody);
}
Also used : ContentType(com.dtflys.forest.backend.ContentType) ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) IOException(java.io.IOException) MultipartBody(okhttp3.MultipartBody) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 3 with ContentType

use of com.dtflys.forest.backend.ContentType in project forest by dromara.

the class TestUploadClient method testMixtureImageUploadWithJSONBodyParamsAndWithoutContentType.

@Test
public void testMixtureImageUploadWithJSONBodyParamsAndWithoutContentType() throws InterruptedException, FileUploadException {
    server.enqueue(new MockResponse().setBody(EXPECTED));
    String path = Objects.requireNonNull(this.getClass().getResource("/test-img.jpg")).getPath();
    if (path.startsWith("/") && isWindows()) {
        path = path.substring(1);
    }
    File file = new File(path);
    Map<String, Object> map = new HashMap<>();
    map.put("a", 1);
    map.put("b", 2);
    ForestRequest request = uploadClient.imageUploadWithJSONBodyParamsAndWithoutContentType("img1.jpg", file, map);
    assertNotNull(request);
    List<ForestMultipart> multipartList = request.getMultiparts();
    assertEquals(1, multipartList.size());
    ForestMultipart multipart = multipartList.get(0);
    // assertTrue(Map.class.isAssignableFrom(request.getMethod().getReturnClass()));
    assertTrue(multipart instanceof FileMultipart);
    assertEquals("file", multipart.getName());
    assertEquals("img1.jpg", multipart.getOriginalFileName());
    Map result = (Map) request.execute();
    assertNotNull(result);
    MockServerRequest.mockRequest(server).assertMultipart("file", multiparts -> {
        assertEquals(1, multiparts.size());
        FileItem fileItem = multiparts.get(0);
        assertEquals("img1.jpg", fileItem.getName());
        assertEquals("image/jpeg", fileItem.getContentType());
    }).assertMultipart("params", params -> {
        assertEquals(1, params.size());
        FileItem item = params.get(0);
        ContentType contentType = new ContentType(item.getContentType());
        assertEquals("application/json", contentType.toStringWithoutParameters());
        try {
            assertEquals(JSON.toJSONString(map), IOUtils.toString(item.getInputStream(), "UTF-8"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : BeforeClass(org.junit.BeforeClass) URL(java.net.URL) ContentType(com.dtflys.forest.backend.ContentType) ForestRequest(com.dtflys.forest.http.ForestRequest) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Assert.assertThat(org.junit.Assert.assertThat) ForestConfiguration(com.dtflys.forest.config.ForestConfiguration) InputStreamMultipart(com.dtflys.forest.multipart.InputStreamMultipart) Map(java.util.Map) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) MockWebServer(okhttp3.mockwebserver.MockWebServer) LinkedList(java.util.LinkedList) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) Assert.assertNotNull(org.junit.Assert.assertNotNull) FileItem(org.apache.commons.fileupload.FileItem) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileMultipart(com.dtflys.forest.multipart.FileMultipart) ByteArrayMultipart(com.dtflys.forest.multipart.ByteArrayMultipart) File(java.io.File) Objects(java.util.Objects) UploadClient(com.dtflys.test.http.client.UploadClient) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) JSON(com.alibaba.fastjson.JSON) Rule(org.junit.Rule) MockServerRequest(com.dtflys.forest.mock.MockServerRequest) StringUtils(com.dtflys.forest.utils.StringUtils) FilePathMultipart(com.dtflys.forest.multipart.FilePathMultipart) FileUploadException(org.apache.commons.fileupload.FileUploadException) MockResponse(okhttp3.mockwebserver.MockResponse) HttpBackend(com.dtflys.forest.backend.HttpBackend) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) MockResponse(okhttp3.mockwebserver.MockResponse) FileMultipart(com.dtflys.forest.multipart.FileMultipart) ContentType(com.dtflys.forest.backend.ContentType) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) ForestRequest(com.dtflys.forest.http.ForestRequest) IOException(java.io.IOException) FileItem(org.apache.commons.fileupload.FileItem) File(java.io.File) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Test(org.junit.Test)

Example 4 with ContentType

use of com.dtflys.forest.backend.ContentType in project forest by dromara.

the class TestUploadClient method testMixtureUploadImageWithBodyParams.

@Test
public void testMixtureUploadImageWithBodyParams() throws InterruptedException, FileUploadException {
    server.enqueue(new MockResponse().setBody(EXPECTED));
    String path = Objects.requireNonNull(this.getClass().getResource("/test-img.jpg")).getPath();
    if (path.startsWith("/") && isWindows()) {
        path = path.substring(1);
    }
    File file = new File(path);
    ForestRequest request = uploadClient.imageUploadWithBodyParams("img1.jpg", file, "1", "2");
    assertNotNull(request);
    List<ForestMultipart> multipartList = request.getMultiparts();
    assertEquals(1, multipartList.size());
    ForestMultipart multipart = multipartList.get(0);
    // assertTrue(Map.class.isAssignableFrom(request.getMethod().getReturnClass()));
    assertTrue(multipart instanceof FileMultipart);
    assertEquals("file", multipart.getName());
    assertEquals("img1.jpg", multipart.getOriginalFileName());
    Map result = (Map) request.execute();
    assertNotNull(result);
    MockServerRequest.mockRequest(server).assertMultipart("file", multiparts -> {
        assertEquals(1, multiparts.size());
        FileItem fileItem = multiparts.get(0);
        assertEquals("img1.jpg", fileItem.getName());
        assertEquals("image/jpeg", fileItem.getContentType());
    }).assertMultipart("a", params -> {
        assertEquals(1, params.size());
        FileItem item = params.get(0);
        ContentType contentType = new ContentType(item.getContentType());
        assertEquals("text/plain", contentType.toStringWithoutParameters());
        try {
            assertEquals("1", IOUtils.toString(item.getInputStream()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }).assertMultipart("b", params -> {
        assertEquals(1, params.size());
        FileItem item = params.get(0);
        ContentType contentType = new ContentType(item.getContentType());
        assertEquals("text/plain", contentType.toStringWithoutParameters());
        try {
            assertEquals("2", IOUtils.toString(item.getInputStream()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : BeforeClass(org.junit.BeforeClass) URL(java.net.URL) ContentType(com.dtflys.forest.backend.ContentType) ForestRequest(com.dtflys.forest.http.ForestRequest) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Assert.assertThat(org.junit.Assert.assertThat) ForestConfiguration(com.dtflys.forest.config.ForestConfiguration) InputStreamMultipart(com.dtflys.forest.multipart.InputStreamMultipart) Map(java.util.Map) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) MockWebServer(okhttp3.mockwebserver.MockWebServer) LinkedList(java.util.LinkedList) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) Assert.assertNotNull(org.junit.Assert.assertNotNull) FileItem(org.apache.commons.fileupload.FileItem) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileMultipart(com.dtflys.forest.multipart.FileMultipart) ByteArrayMultipart(com.dtflys.forest.multipart.ByteArrayMultipart) File(java.io.File) Objects(java.util.Objects) UploadClient(com.dtflys.test.http.client.UploadClient) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) JSON(com.alibaba.fastjson.JSON) Rule(org.junit.Rule) MockServerRequest(com.dtflys.forest.mock.MockServerRequest) StringUtils(com.dtflys.forest.utils.StringUtils) FilePathMultipart(com.dtflys.forest.multipart.FilePathMultipart) FileUploadException(org.apache.commons.fileupload.FileUploadException) MockResponse(okhttp3.mockwebserver.MockResponse) HttpBackend(com.dtflys.forest.backend.HttpBackend) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) MockResponse(okhttp3.mockwebserver.MockResponse) FileMultipart(com.dtflys.forest.multipart.FileMultipart) ContentType(com.dtflys.forest.backend.ContentType) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) ForestRequest(com.dtflys.forest.http.ForestRequest) IOException(java.io.IOException) FileItem(org.apache.commons.fileupload.FileItem) File(java.io.File) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Test(org.junit.Test)

Example 5 with ContentType

use of com.dtflys.forest.backend.ContentType 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)

Aggregations

ContentType (com.dtflys.forest.backend.ContentType)11 IOException (java.io.IOException)6 ForestRequest (com.dtflys.forest.http.ForestRequest)5 ForestMultipart (com.dtflys.forest.multipart.ForestMultipart)5 File (java.io.File)5 Map (java.util.Map)5 JSON (com.alibaba.fastjson.JSON)4 HttpBackend (com.dtflys.forest.backend.HttpBackend)4 ForestConfiguration (com.dtflys.forest.config.ForestConfiguration)4 MockServerRequest (com.dtflys.forest.mock.MockServerRequest)4 ByteArrayMultipart (com.dtflys.forest.multipart.ByteArrayMultipart)4 FileMultipart (com.dtflys.forest.multipart.FileMultipart)4 FilePathMultipart (com.dtflys.forest.multipart.FilePathMultipart)4 InputStreamMultipart (com.dtflys.forest.multipart.InputStreamMultipart)4 StringUtils (com.dtflys.forest.utils.StringUtils)4 UploadClient (com.dtflys.test.http.client.UploadClient)4 FileInputStream (java.io.FileInputStream)4 InputStream (java.io.InputStream)4 URL (java.net.URL)4 HashMap (java.util.HashMap)4