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);
}
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);
}
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);
}
});
}
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);
}
});
}
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;
}
Aggregations