Search in sources :

Example 1 with HttpEntity

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);
}
Also used : HttpHeaders(cn.taketoday.http.HttpHeaders) Dynamic(jakarta.servlet.ServletRegistration.Dynamic) HttpEntity(cn.taketoday.http.HttpEntity) LinkedMultiValueMap(cn.taketoday.core.LinkedMultiValueMap) HttpServlet(jakarta.servlet.http.HttpServlet) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) ByteArrayResource(cn.taketoday.core.io.ByteArrayResource) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletException(jakarta.servlet.ServletException) MultipartConfigElement(jakarta.servlet.MultipartConfigElement) RestTemplate(cn.taketoday.web.client.RestTemplate) ServletContext(jakarta.servlet.ServletContext) File(java.io.File) LinkedMultiValueMap(cn.taketoday.core.LinkedMultiValueMap) MultiValueMap(cn.taketoday.core.MultiValueMap) Test(org.junit.jupiter.api.Test)

Example 2 with HttpEntity

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));
}
Also used : Arrays(java.util.Arrays) Assert(cn.taketoday.lang.Assert) ResolvableTypeProvider(cn.taketoday.core.ResolvableTypeProvider) DataBufferFactory(cn.taketoday.core.io.buffer.DataBufferFactory) Resource(cn.taketoday.core.io.Resource) FormHttpMessageWriter(cn.taketoday.http.codec.FormHttpMessageWriter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CodecException(cn.taketoday.core.codec.CodecException) LogFormatUtils(cn.taketoday.util.LogFormatUtils) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) HttpHeaders(cn.taketoday.http.HttpHeaders) ReactiveHttpOutputMessage(cn.taketoday.http.ReactiveHttpOutputMessage) DataBufferUtils(cn.taketoday.core.io.buffer.DataBufferUtils) PooledDataBuffer(cn.taketoday.core.io.buffer.PooledDataBuffer) Hints(cn.taketoday.core.codec.Hints) Map(java.util.Map) CharSequenceEncoder(cn.taketoday.core.codec.CharSequenceEncoder) DataBuffer(cn.taketoday.core.io.buffer.DataBuffer) MultiValueMap(cn.taketoday.core.MultiValueMap) EncoderHttpMessageWriter(cn.taketoday.http.codec.EncoderHttpMessageWriter) Publisher(org.reactivestreams.Publisher) ResolvableType(cn.taketoday.core.ResolvableType) HttpMessageWriter(cn.taketoday.http.codec.HttpMessageWriter) Mono(reactor.core.publisher.Mono) ResourceHttpMessageWriter(cn.taketoday.http.codec.ResourceHttpMessageWriter) Flux(reactor.core.publisher.Flux) List(java.util.List) Nullable(cn.taketoday.lang.Nullable) Optional(java.util.Optional) HttpEntity(cn.taketoday.http.HttpEntity) MediaType(cn.taketoday.http.MediaType) Collections(java.util.Collections) HttpHeaders(cn.taketoday.http.HttpHeaders) HttpEntity(cn.taketoday.http.HttpEntity) FormHttpMessageWriter(cn.taketoday.http.codec.FormHttpMessageWriter) EncoderHttpMessageWriter(cn.taketoday.http.codec.EncoderHttpMessageWriter) HttpMessageWriter(cn.taketoday.http.codec.HttpMessageWriter) ResourceHttpMessageWriter(cn.taketoday.http.codec.ResourceHttpMessageWriter) Resource(cn.taketoday.core.io.Resource) Publisher(org.reactivestreams.Publisher) MediaType(cn.taketoday.http.MediaType) CodecException(cn.taketoday.core.codec.CodecException) ResolvableType(cn.taketoday.core.ResolvableType) ResolvableTypeProvider(cn.taketoday.core.ResolvableTypeProvider) PooledDataBuffer(cn.taketoday.core.io.buffer.PooledDataBuffer) DataBuffer(cn.taketoday.core.io.buffer.DataBuffer)

Example 3 with HttpEntity

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");
}
Also used : HttpHeaders(cn.taketoday.http.HttpHeaders) HttpEntity(cn.taketoday.http.HttpEntity) MockHttpOutputMessage(cn.taketoday.http.MockHttpOutputMessage) Resource(cn.taketoday.core.io.Resource) ClassPathResource(cn.taketoday.core.io.ClassPathResource) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) ClassPathResource(cn.taketoday.core.io.ClassPathResource) FileItemFactory(org.apache.tomcat.util.http.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) LinkedHashMap(java.util.LinkedHashMap) FileItem(org.apache.tomcat.util.http.fileupload.FileItem) MediaType(cn.taketoday.http.MediaType) RequestContext(org.apache.tomcat.util.http.fileupload.RequestContext) FileUpload(org.apache.tomcat.util.http.fileupload.FileUpload) Test(org.junit.jupiter.api.Test)

Example 4 with HttpEntity

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();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) MediaType.parseMediaType(cn.taketoday.http.MediaType.parseMediaType) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) HttpMessageConverter(cn.taketoday.http.converter.HttpMessageConverter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) PUT(cn.taketoday.http.HttpMethod.PUT) DELETE(cn.taketoday.http.HttpMethod.DELETE) HttpHeaders(cn.taketoday.http.HttpHeaders) GenericHttpMessageConverter(cn.taketoday.http.converter.GenericHttpMessageConverter) ByteArrayInputStream(java.io.ByteArrayInputStream) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) MockWebServer(okhttp3.mockwebserver.MockWebServer) DefaultUriBuilderFactory(cn.taketoday.web.util.DefaultUriBuilderFactory) ClientHttpRequestInitializer(cn.taketoday.http.client.ClientHttpRequestInitializer) URI(java.net.URI) PATCH(cn.taketoday.http.HttpMethod.PATCH) EnumSet(java.util.EnumSet) BDDMockito.willThrow(org.mockito.BDDMockito.willThrow) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) OPTIONS(cn.taketoday.http.HttpMethod.OPTIONS) Set(java.util.Set) ResponseEntity(cn.taketoday.http.ResponseEntity) ClientHttpResponse(cn.taketoday.http.client.ClientHttpResponse) StreamUtils(cn.taketoday.util.StreamUtils) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) List(java.util.List) POST(cn.taketoday.http.HttpMethod.POST) GET(cn.taketoday.http.HttpMethod.GET) Entry(java.util.Map.Entry) HttpStatus(cn.taketoday.http.HttpStatus) MockResponse(okhttp3.mockwebserver.MockResponse) ClientHttpRequestInterceptor(cn.taketoday.http.client.ClientHttpRequestInterceptor) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HashMap(java.util.HashMap) HttpMethod(cn.taketoday.http.HttpMethod) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) TypeReference(cn.taketoday.core.TypeReference) ClientHttpRequestFactory(cn.taketoday.http.client.ClientHttpRequestFactory) ClientHttpRequest(cn.taketoday.http.client.ClientHttpRequest) IOException(java.io.IOException) SimpleClientHttpRequestFactory(cn.taketoday.http.client.SimpleClientHttpRequestFactory) HttpInputMessage(cn.taketoday.http.HttpInputMessage) Mockito.verify(org.mockito.Mockito.verify) HEAD(cn.taketoday.http.HttpMethod.HEAD) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) HttpEntity(cn.taketoday.http.HttpEntity) MediaType(cn.taketoday.http.MediaType) Collections(java.util.Collections) HttpHeaders(cn.taketoday.http.HttpHeaders) HttpEntity(cn.taketoday.http.HttpEntity) ClientHttpRequestInterceptor(cn.taketoday.http.client.ClientHttpRequestInterceptor) Test(org.junit.jupiter.api.Test)

Example 5 with HttpEntity

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();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) MediaType.parseMediaType(cn.taketoday.http.MediaType.parseMediaType) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) HttpMessageConverter(cn.taketoday.http.converter.HttpMessageConverter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) PUT(cn.taketoday.http.HttpMethod.PUT) DELETE(cn.taketoday.http.HttpMethod.DELETE) HttpHeaders(cn.taketoday.http.HttpHeaders) GenericHttpMessageConverter(cn.taketoday.http.converter.GenericHttpMessageConverter) ByteArrayInputStream(java.io.ByteArrayInputStream) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) MockWebServer(okhttp3.mockwebserver.MockWebServer) DefaultUriBuilderFactory(cn.taketoday.web.util.DefaultUriBuilderFactory) ClientHttpRequestInitializer(cn.taketoday.http.client.ClientHttpRequestInitializer) URI(java.net.URI) PATCH(cn.taketoday.http.HttpMethod.PATCH) EnumSet(java.util.EnumSet) BDDMockito.willThrow(org.mockito.BDDMockito.willThrow) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) OPTIONS(cn.taketoday.http.HttpMethod.OPTIONS) Set(java.util.Set) ResponseEntity(cn.taketoday.http.ResponseEntity) ClientHttpResponse(cn.taketoday.http.client.ClientHttpResponse) StreamUtils(cn.taketoday.util.StreamUtils) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) List(java.util.List) POST(cn.taketoday.http.HttpMethod.POST) GET(cn.taketoday.http.HttpMethod.GET) Entry(java.util.Map.Entry) HttpStatus(cn.taketoday.http.HttpStatus) MockResponse(okhttp3.mockwebserver.MockResponse) ClientHttpRequestInterceptor(cn.taketoday.http.client.ClientHttpRequestInterceptor) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HashMap(java.util.HashMap) HttpMethod(cn.taketoday.http.HttpMethod) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) TypeReference(cn.taketoday.core.TypeReference) ClientHttpRequestFactory(cn.taketoday.http.client.ClientHttpRequestFactory) ClientHttpRequest(cn.taketoday.http.client.ClientHttpRequest) IOException(java.io.IOException) SimpleClientHttpRequestFactory(cn.taketoday.http.client.SimpleClientHttpRequestFactory) HttpInputMessage(cn.taketoday.http.HttpInputMessage) Mockito.verify(org.mockito.Mockito.verify) HEAD(cn.taketoday.http.HttpMethod.HEAD) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) HttpEntity(cn.taketoday.http.HttpEntity) MediaType(cn.taketoday.http.MediaType) Collections(java.util.Collections) HttpHeaders(cn.taketoday.http.HttpHeaders) HttpEntity(cn.taketoday.http.HttpEntity) MediaType.parseMediaType(cn.taketoday.http.MediaType.parseMediaType) MediaType(cn.taketoday.http.MediaType) ClientHttpRequestInterceptor(cn.taketoday.http.client.ClientHttpRequestInterceptor) Test(org.junit.jupiter.api.Test)

Aggregations

HttpEntity (cn.taketoday.http.HttpEntity)34 Test (org.junit.jupiter.api.Test)32 HttpHeaders (cn.taketoday.http.HttpHeaders)26 List (java.util.List)13 MediaType (cn.taketoday.http.MediaType)12 HttpMessageConverter (cn.taketoday.http.converter.HttpMessageConverter)12 TypeReference (cn.taketoday.core.TypeReference)10 URI (java.net.URI)10 Resource (cn.taketoday.core.io.Resource)8 HttpInputMessage (cn.taketoday.http.HttpInputMessage)8 SimpleClientHttpRequestFactory (cn.taketoday.http.client.SimpleClientHttpRequestFactory)8 GenericHttpMessageConverter (cn.taketoday.http.converter.GenericHttpMessageConverter)8 ByteArrayInputStream (java.io.ByteArrayInputStream)8 ArrayList (java.util.ArrayList)8 Arrays (java.util.Arrays)8 Collections (java.util.Collections)8 Map (java.util.Map)8 ClassPathResource (cn.taketoday.core.io.ClassPathResource)6 HttpMethod (cn.taketoday.http.HttpMethod)6 DELETE (cn.taketoday.http.HttpMethod.DELETE)6