Search in sources :

Example 1 with FilePart

use of org.springframework.http.codec.multipart.FilePart in project spring-framework by spring-projects.

the class BodyExtractorsTests method toParts.

@Test
public void toParts() {
    BodyExtractor<Flux<Part>, ServerHttpRequest> extractor = BodyExtractors.toParts();
    String bodyContents = "-----------------------------9051914041544843365972754266\r\n" + "Content-Disposition: form-data; name=\"text\"\r\n" + "\r\n" + "text default\r\n" + "-----------------------------9051914041544843365972754266\r\n" + "Content-Disposition: form-data; name=\"file1\"; filename=\"a.txt\"\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "Content of a.txt.\r\n" + "\r\n" + "-----------------------------9051914041544843365972754266\r\n" + "Content-Disposition: form-data; name=\"file2\"; filename=\"a.html\"\r\n" + "Content-Type: text/html\r\n" + "\r\n" + "<!DOCTYPE html><title>Content of a.html.</title>\r\n" + "\r\n" + "-----------------------------9051914041544843365972754266--\r\n";
    byte[] bytes = bodyContents.getBytes(StandardCharsets.UTF_8);
    DefaultDataBuffer dataBuffer = DefaultDataBufferFactory.sharedInstance.wrap(ByteBuffer.wrap(bytes));
    Flux<DataBuffer> body = Flux.just(dataBuffer);
    MockServerHttpRequest request = MockServerHttpRequest.post("/").header("Content-Type", "multipart/form-data; boundary=---------------------------9051914041544843365972754266").body(body);
    Flux<Part> result = extractor.extract(request, this.context);
    StepVerifier.create(result).consumeNextWith(part -> {
        assertThat(part.name()).isEqualTo("text");
        boolean condition = part instanceof FormFieldPart;
        assertThat(condition).isTrue();
        FormFieldPart formFieldPart = (FormFieldPart) part;
        assertThat(formFieldPart.value()).isEqualTo("text default");
    }).consumeNextWith(part -> {
        assertThat(part.name()).isEqualTo("file1");
        boolean condition = part instanceof FilePart;
        assertThat(condition).isTrue();
        FilePart filePart = (FilePart) part;
        assertThat(filePart.filename()).isEqualTo("a.txt");
        assertThat(filePart.headers().getContentType()).isEqualTo(MediaType.TEXT_PLAIN);
    }).consumeNextWith(part -> {
        assertThat(part.name()).isEqualTo("file2");
        boolean condition = part instanceof FilePart;
        assertThat(condition).isTrue();
        FilePart filePart = (FilePart) part;
        assertThat(filePart.filename()).isEqualTo("a.html");
        assertThat(filePart.headers().getContentType()).isEqualTo(MediaType.TEXT_HTML);
    }).expectComplete().verify();
}
Also used : DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) BeforeEach(org.junit.jupiter.api.BeforeEach) TestPublisher(reactor.test.publisher.TestPublisher) FilePart(org.springframework.http.codec.multipart.FilePart) FormFieldPart(org.springframework.http.codec.multipart.FormFieldPart) JsonView(com.fasterxml.jackson.annotation.JsonView) StepVerifier(reactor.test.StepVerifier) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) FormHttpMessageReader(org.springframework.http.codec.FormHttpMessageReader) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) HashMap(java.util.HashMap) JSON_VIEW_HINT(org.springframework.http.codec.json.Jackson2CodecSupport.JSON_VIEW_HINT) ByteBuffer(java.nio.ByteBuffer) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Part(org.springframework.http.codec.multipart.Part) Map(java.util.Map) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Jaxb2XmlDecoder(org.springframework.http.codec.xml.Jaxb2XmlDecoder) NettyDataBuffer(org.springframework.core.io.buffer.NettyDataBuffer) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) Jackson2JsonDecoder(org.springframework.http.codec.json.Jackson2JsonDecoder) DefaultPartHttpMessageReader(org.springframework.http.codec.multipart.DefaultPartHttpMessageReader) MockClientHttpResponse(org.springframework.web.testfixture.http.client.reactive.MockClientHttpResponse) StringDecoder(org.springframework.core.codec.StringDecoder) MediaType(org.springframework.http.MediaType) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) ByteBufferDecoder(org.springframework.core.codec.ByteBufferDecoder) DataBuffer(org.springframework.core.io.buffer.DataBuffer) StandardCharsets(java.nio.charset.StandardCharsets) DecoderHttpMessageReader(org.springframework.http.codec.DecoderHttpMessageReader) Test(org.junit.jupiter.api.Test) Flux(reactor.core.publisher.Flux) HttpStatus(org.springframework.http.HttpStatus) MockServerHttpRequest(org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest) List(java.util.List) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) MultipartHttpMessageReader(org.springframework.http.codec.multipart.MultipartHttpMessageReader) Optional(java.util.Optional) Collections(java.util.Collections) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) MockServerHttpRequest(org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest) Flux(reactor.core.publisher.Flux) FilePart(org.springframework.http.codec.multipart.FilePart) MockServerHttpRequest(org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest) FilePart(org.springframework.http.codec.multipart.FilePart) FormFieldPart(org.springframework.http.codec.multipart.FormFieldPart) Part(org.springframework.http.codec.multipart.Part) FormFieldPart(org.springframework.http.codec.multipart.FormFieldPart) DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) NettyDataBuffer(org.springframework.core.io.buffer.NettyDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Test(org.junit.jupiter.api.Test)

Example 2 with FilePart

use of org.springframework.http.codec.multipart.FilePart in project spring-framework by spring-projects.

the class MockMvcHttpConnector method initRequestBuilder.

private MockHttpServletRequestBuilder initRequestBuilder(HttpMethod httpMethod, URI uri, MockClientHttpRequest httpRequest, @Nullable byte[] bytes) {
    String contentType = httpRequest.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
    if (!StringUtils.startsWithIgnoreCase(contentType, "multipart/")) {
        MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.request(httpMethod, uri);
        if (!ObjectUtils.isEmpty(bytes)) {
            requestBuilder.content(bytes);
        }
        return requestBuilder;
    }
    // Parse the multipart request in order to adapt to Servlet Part's
    MockMultipartHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.multipart(uri);
    Assert.notNull(bytes, "No multipart content");
    ReactiveHttpInputMessage inputMessage = MockServerHttpRequest.post(uri.toString()).headers(httpRequest.getHeaders()).body(Mono.just(DefaultDataBufferFactory.sharedInstance.wrap(bytes)));
    MULTIPART_READER.read(ResolvableType.forClass(Part.class), inputMessage, Collections.emptyMap()).flatMap(part -> DataBufferUtils.join(part.content()).doOnNext(buffer -> {
        byte[] partBytes = new byte[buffer.readableByteCount()];
        buffer.read(partBytes);
        DataBufferUtils.release(buffer);
        // Adapt to jakarta.servlet.http.Part...
        MockPart mockPart = (part instanceof FilePart ? new MockPart(part.name(), ((FilePart) part).filename(), partBytes) : new MockPart(part.name(), partBytes));
        mockPart.getHeaders().putAll(part.headers());
        requestBuilder.part(mockPart);
    })).blockLast(TIMEOUT);
    return requestBuilder;
}
Also used : MockMvcRequestBuilders.asyncDispatch(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch) FilePart(org.springframework.http.codec.multipart.FilePart) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ClientHttpResponse(org.springframework.http.client.reactive.ClientHttpResponse) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) MockMvc(org.springframework.test.web.servlet.MockMvc) HttpCookie(org.springframework.http.HttpCookie) MockPart(org.springframework.mock.web.MockPart) RequestBuilder(org.springframework.test.web.servlet.RequestBuilder) Part(org.springframework.http.codec.multipart.Part) MockMvcResultHandlers(org.springframework.test.web.servlet.result.MockMvcResultHandlers) Duration(java.time.Duration) MvcResult(org.springframework.test.web.servlet.MvcResult) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) ClientHttpRequest(org.springframework.http.client.reactive.ClientHttpRequest) Nullable(org.springframework.lang.Nullable) FlashMap(org.springframework.web.servlet.FlashMap) URI(java.net.URI) ResolvableType(org.springframework.core.ResolvableType) ResponseCookie(org.springframework.http.ResponseCookie) MockClientHttpResponse(org.springframework.mock.http.client.reactive.MockClientHttpResponse) DefaultPartHttpMessageReader(org.springframework.http.codec.multipart.DefaultPartHttpMessageReader) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) HttpHeaders(org.springframework.http.HttpHeaders) StringWriter(java.io.StringWriter) ObjectUtils(org.springframework.util.ObjectUtils) HttpMethod(org.springframework.http.HttpMethod) Mono(reactor.core.publisher.Mono) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockMvcRequestBuilders(org.springframework.test.web.servlet.request.MockMvcRequestBuilders) ModelAndView(org.springframework.web.servlet.ModelAndView) List(java.util.List) Cookie(jakarta.servlet.http.Cookie) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) MockServerClientHttpResponse(org.springframework.test.web.reactive.server.MockServerClientHttpResponse) MockMultipartHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder) Collections(java.util.Collections) ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) MockClientHttpRequest(org.springframework.mock.http.client.reactive.MockClientHttpRequest) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) MockMultipartHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder) FilePart(org.springframework.http.codec.multipart.FilePart) MockPart(org.springframework.mock.web.MockPart) Part(org.springframework.http.codec.multipart.Part) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) MockPart(org.springframework.mock.web.MockPart) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) FilePart(org.springframework.http.codec.multipart.FilePart)

Aggregations

Collections (java.util.Collections)2 List (java.util.List)2 DefaultDataBuffer (org.springframework.core.io.buffer.DefaultDataBuffer)2 DefaultDataBufferFactory (org.springframework.core.io.buffer.DefaultDataBufferFactory)2 ReactiveHttpInputMessage (org.springframework.http.ReactiveHttpInputMessage)2 DefaultPartHttpMessageReader (org.springframework.http.codec.multipart.DefaultPartHttpMessageReader)2 FilePart (org.springframework.http.codec.multipart.FilePart)2 Part (org.springframework.http.codec.multipart.Part)2 Mono (reactor.core.publisher.Mono)2 JsonView (com.fasterxml.jackson.annotation.JsonView)1 PooledByteBufAllocator (io.netty.buffer.PooledByteBufAllocator)1 IllegalReferenceCountException (io.netty.util.IllegalReferenceCountException)1 Cookie (jakarta.servlet.http.Cookie)1 StringWriter (java.io.StringWriter)1 URI (java.net.URI)1 ByteBuffer (java.nio.ByteBuffer)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Duration (java.time.Duration)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1