use of cn.taketoday.http.HttpEntity in project today-infrastructure by TAKETODAY.
the class TomcatServletWebServerFactoryTests method nonExistentUploadDirectoryIsCreatedUponMultipartUpload.
@Test
void nonExistentUploadDirectoryIsCreatedUponMultipartUpload() throws IOException, URISyntaxException {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0);
AtomicReference<ServletContext> servletContextReference = new AtomicReference<>();
factory.addInitializers((servletContext) -> {
servletContextReference.set(servletContext);
Dynamic servlet = servletContext.addServlet("upload", new HttpServlet() {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getParts();
}
});
servlet.addMapping("/upload");
servlet.setMultipartConfig(new MultipartConfigElement((String) null));
});
this.webServer = factory.getWebServer();
this.webServer.start();
File temp = (File) servletContextReference.get().getAttribute(ServletContext.TEMPDIR);
FileSystemUtils.deleteRecursively(temp);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = HttpHeaders.create();
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new ByteArrayResource(new byte[1024 * 1024]));
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.postForEntity(getLocalUrl("/upload"), requestEntity, String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
use of cn.taketoday.http.HttpEntity in project today-infrastructure by TAKETODAY.
the class MultipartHttpMessageWriter method encodePart.
@SuppressWarnings("unchecked")
private <T> Flux<DataBuffer> encodePart(byte[] boundary, String name, T value, DataBufferFactory factory) {
MultipartHttpOutputMessage message = new MultipartHttpOutputMessage(factory);
HttpHeaders headers = message.getHeaders();
T body;
ResolvableType resolvableType = null;
if (value instanceof HttpEntity) {
HttpEntity<T> httpEntity = (HttpEntity<T>) value;
headers.putAll(httpEntity.getHeaders());
body = httpEntity.getBody();
Assert.state(body != null, "MultipartHttpMessageWriter only supports HttpEntity with body");
if (httpEntity instanceof ResolvableTypeProvider) {
resolvableType = ((ResolvableTypeProvider) httpEntity).getResolvableType();
}
} else {
body = value;
}
if (resolvableType == null) {
resolvableType = ResolvableType.fromClass(body.getClass());
}
if (!headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
if (body instanceof Resource) {
headers.setContentDispositionFormData(name, ((Resource) body).getName());
} else if (resolvableType.resolve() == Resource.class) {
body = (T) Mono.from((Publisher<?>) body).doOnNext(o -> headers.setContentDispositionFormData(name, ((Resource) o).getName()));
} else {
headers.setContentDispositionFormData(name, null);
}
}
MediaType contentType = headers.getContentType();
final ResolvableType finalBodyType = resolvableType;
Optional<HttpMessageWriter<?>> writer = this.partWriters.stream().filter(partWriter -> partWriter.canWrite(finalBodyType, contentType)).findFirst();
if (writer.isEmpty()) {
return Flux.error(new CodecException("No suitable writer found for part: " + name));
}
Publisher<T> bodyPublisher = body instanceof Publisher ? (Publisher<T>) body : Mono.just(body);
// The writer will call MultipartHttpOutputMessage#write which doesn't actually write
// but only stores the body Flux and returns Mono.empty().
Mono<Void> partContentReady = ((HttpMessageWriter<T>) writer.get()).write(bodyPublisher, resolvableType, contentType, message, DEFAULT_HINTS);
// After partContentReady, we can access the part content from MultipartHttpOutputMessage
// and use it for writing to the actual request body
Flux<DataBuffer> partContent = partContentReady.thenMany(Flux.defer(message::getBody));
return Flux.concat(generateBoundaryLine(boundary, factory), partContent, generateNewLine(factory));
}
use of cn.taketoday.http.HttpEntity in project today-infrastructure by TAKETODAY.
the class FormHttpMessageConverterTests method writeMultipart.
@Test
public void writeMultipart() throws Exception {
MultiValueMap<String, Object> parts = MultiValueMap.fromLinkedHashMap();
parts.add("name 1", "value 1");
parts.add("name 2", "value 2+1");
parts.add("name 2", "value 2+2");
parts.add("name 3", null);
Resource logo = new ClassPathResource("/cn/taketoday/http/converter/logo.jpg");
parts.add("logo", logo);
// SPR-12108
Resource utf8 = new ClassPathResource("/cn/taketoday/http/converter/logo.jpg") {
@Override
public String getName() {
return "Hall\u00F6le.jpg";
}
};
parts.add("utf8", utf8);
Object obj = new Object() {
private String name;
public String getName() {
return name;
}
};
// Source xml = new StreamSource(new StringReader("<root><child/></root>"));
HttpHeaders entityHeaders = HttpHeaders.create();
entityHeaders.setContentType(APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(obj, entityHeaders);
parts.add("xml", entity);
Map<String, String> parameters = new LinkedHashMap<>(2);
parameters.put("charset", StandardCharsets.UTF_8.name());
parameters.put("foo", "bar");
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
this.converter.write(parts, new MediaType("multipart", "form-data", parameters), outputMessage);
// MediaType contentType = outputMessage.getHeaders().getContentType();
// assertThat(contentType.getParameters()).containsKeys("charset", "boundary", "foo"); // gh-21568, gh-25839
// see if Commons FileUpload can read what we wrote
FileItemFactory fileItemFactory = new DiskFileItemFactory();
FileUpload fileUpload = new FileUpload(fileItemFactory);
RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
List<FileItem> items = fileUpload.parseRequest(requestContext);
assertThat(items.size()).isEqualTo(6);
FileItem item = items.get(0);
assertThat(item.isFormField()).isTrue();
assertThat(item.getFieldName()).isEqualTo("name 1");
assertThat(item.getString()).isEqualTo("value 1");
item = items.get(1);
assertThat(item.isFormField()).isTrue();
assertThat(item.getFieldName()).isEqualTo("name 2");
assertThat(item.getString()).isEqualTo("value 2+1");
item = items.get(2);
assertThat(item.isFormField()).isTrue();
assertThat(item.getFieldName()).isEqualTo("name 2");
assertThat(item.getString()).isEqualTo("value 2+2");
item = items.get(3);
assertThat(item.isFormField()).isFalse();
assertThat(item.getFieldName()).isEqualTo("logo");
assertThat(item.getName()).isEqualTo("logo.jpg");
assertThat(item.getContentType()).isEqualTo("image/jpeg");
assertThat(item.getSize()).isEqualTo(logo.getFile().length());
item = items.get(4);
assertThat(item.isFormField()).isFalse();
assertThat(item.getFieldName()).isEqualTo("utf8");
assertThat(item.getName()).isEqualTo("Hall\u00F6le.jpg");
assertThat(item.getContentType()).isEqualTo("image/jpeg");
assertThat(item.getSize()).isEqualTo(logo.getFile().length());
item = items.get(5);
assertThat(item.getFieldName()).isEqualTo("xml");
assertThat(item.getContentType()).isEqualTo("application/json");
}
use of cn.taketoday.http.HttpEntity in project today-infrastructure by TAKETODAY.
the class RestTemplateTests method requestInterceptorCanAddExistingHeaderValueWithoutBody.
@Test
// SPR-15066
void requestInterceptorCanAddExistingHeaderValueWithoutBody() throws Exception {
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
request.getHeaders().add("MyHeader", "MyInterceptorValue");
return execution.execute(request, body);
};
template.setInterceptors(interceptor);
HttpHeaders requestHeaders = HttpHeaders.create();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders entityHeaders = HttpHeaders.create();
entityHeaders.add("MyHeader", "MyEntityValue");
HttpEntity<Void> entity = new HttpEntity<>(null, entityHeaders);
template.exchange("https://example.com", POST, entity, Void.class);
assertThat(requestHeaders.get("MyHeader")).contains("MyEntityValue", "MyInterceptorValue");
verify(response).close();
}
use of cn.taketoday.http.HttpEntity in project today-infrastructure by TAKETODAY.
the class RestTemplateTests method requestInterceptorCanAddExistingHeaderValueWithBody.
@Test
// SPR-15066
void requestInterceptorCanAddExistingHeaderValueWithBody() throws Exception {
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
request.getHeaders().add("MyHeader", "MyInterceptorValue");
return execution.execute(request, body);
};
template.setInterceptors(interceptor);
MediaType contentType = MediaType.TEXT_PLAIN;
given(converter.canWrite(String.class, contentType)).willReturn(true);
HttpHeaders requestHeaders = HttpHeaders.create();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders entityHeaders = HttpHeaders.create();
entityHeaders.setContentType(contentType);
entityHeaders.add("MyHeader", "MyEntityValue");
HttpEntity<String> entity = new HttpEntity<>("Hello World", entityHeaders);
template.exchange("https://example.com", POST, entity, Void.class);
assertThat(requestHeaders.get("MyHeader")).contains("MyEntityValue", "MyInterceptorValue");
verify(response).close();
}
Aggregations