Search in sources :

Example 1 with MultiValueMap

use of cn.taketoday.core.MultiValueMap in project today-infrastructure by TAKETODAY.

the class DefaultWebClientBuilder method build.

@Override
public WebClient build() {
    ClientHttpConnector connectorToUse = (this.connector != null ? this.connector : initConnector());
    ExchangeFunction exchange = (this.exchangeFunction == null ? ExchangeFunctions.create(connectorToUse, initExchangeStrategies()) : this.exchangeFunction);
    ExchangeFunction filteredExchange = (this.filters != null ? this.filters.stream().reduce(ExchangeFilterFunction::andThen).map(filter -> filter.apply(exchange)).orElse(exchange) : exchange);
    HttpHeaders defaultHeaders = copyDefaultHeaders();
    MultiValueMap<String, String> defaultCookies = copyDefaultCookies();
    return new DefaultWebClient(filteredExchange, initUriBuilderFactory(), defaultHeaders, defaultCookies, this.defaultRequest, new DefaultWebClientBuilder(this));
}
Also used : ClientHttpConnector(cn.taketoday.http.client.reactive.ClientHttpConnector) ClientCodecConfigurer(cn.taketoday.http.codec.ClientCodecConfigurer) LinkedMultiValueMap(cn.taketoday.core.LinkedMultiValueMap) Arrays(java.util.Arrays) Assert(cn.taketoday.lang.Assert) CollectionUtils(cn.taketoday.util.CollectionUtils) JettyClientHttpConnector(cn.taketoday.http.client.reactive.JettyClientHttpConnector) ClassUtils(cn.taketoday.util.ClassUtils) UriBuilderFactory(cn.taketoday.web.util.UriBuilderFactory) ArrayList(java.util.ArrayList) ReactorClientHttpConnector(cn.taketoday.http.client.reactive.ReactorClientHttpConnector) LinkedHashMap(java.util.LinkedHashMap) Consumer(java.util.function.Consumer) List(java.util.List) HttpHeaders(cn.taketoday.http.HttpHeaders) Nullable(cn.taketoday.lang.Nullable) Map(java.util.Map) HttpComponentsClientHttpConnector(cn.taketoday.http.client.reactive.HttpComponentsClientHttpConnector) MultiValueMap(cn.taketoday.core.MultiValueMap) DefaultUriBuilderFactory(cn.taketoday.web.util.DefaultUriBuilderFactory) JdkClientHttpConnector(cn.taketoday.http.client.reactive.JdkClientHttpConnector) HttpHeaders(cn.taketoday.http.HttpHeaders) ClientHttpConnector(cn.taketoday.http.client.reactive.ClientHttpConnector) JettyClientHttpConnector(cn.taketoday.http.client.reactive.JettyClientHttpConnector) ReactorClientHttpConnector(cn.taketoday.http.client.reactive.ReactorClientHttpConnector) HttpComponentsClientHttpConnector(cn.taketoday.http.client.reactive.HttpComponentsClientHttpConnector) JdkClientHttpConnector(cn.taketoday.http.client.reactive.JdkClientHttpConnector)

Example 2 with MultiValueMap

use of cn.taketoday.core.MultiValueMap in project today-infrastructure by TAKETODAY.

the class BodyInsertersTests method fromFormDataWith.

@Test
public void fromFormDataWith() {
    BodyInserter<MultiValueMap<String, String>, ClientHttpRequest> inserter = BodyInserters.fromFormData("name 1", "value 1").with("name 2", "value 2+1").with("name 2", "value 2+2").with("name 3", null);
    MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("https://example.com"));
    Mono<Void> result = inserter.insert(request, this.context);
    StepVerifier.create(result).expectComplete().verify();
    StepVerifier.create(request.getBody()).consumeNextWith(dataBuffer -> {
        byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
        dataBuffer.read(resultBytes);
        DataBufferUtils.release(dataBuffer);
        assertThat(resultBytes).isEqualTo("name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3".getBytes(StandardCharsets.UTF_8));
    }).expectComplete().verify();
}
Also used : MockClientHttpRequest(cn.taketoday.web.testfixture.http.client.reactive.MockClientHttpRequest) MockClientHttpRequest(cn.taketoday.web.testfixture.http.client.reactive.MockClientHttpRequest) ClientHttpRequest(cn.taketoday.http.client.reactive.ClientHttpRequest) LinkedMultiValueMap(cn.taketoday.core.LinkedMultiValueMap) MultiValueMap(cn.taketoday.core.MultiValueMap) Test(org.junit.jupiter.api.Test)

Example 3 with MultiValueMap

use of cn.taketoday.core.MultiValueMap in project today-infrastructure by TAKETODAY.

the class TodayStrategies method loadStrategies.

private static MultiValueMap<String, String> loadStrategies(ClassLoader classLoader) {
    MultiValueMap<String, String> strategies = strategiesCache.get(classLoader);
    if (strategies != null) {
        return strategies;
    }
    synchronized (strategiesCache) {
        strategies = strategiesCache.get(classLoader);
        if (strategies == null) {
            log.debug("Detecting strategies location '{}'", STRATEGIES_LOCATION);
            strategies = MultiValueMap.fromLinkedHashMap();
            try {
                Enumeration<URL> urls = classLoader.getResources(STRATEGIES_LOCATION);
                while (urls.hasMoreElements()) {
                    URL url = urls.nextElement();
                    Properties properties = new Properties();
                    try (InputStream inputStream = url.openStream()) {
                        properties.load(inputStream);
                    }
                    log.debug("Reading strategies file '{}'", url);
                    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                        Object key = entry.getKey();
                        Object value = entry.getValue();
                        if (key != null && value != null) {
                            String strategyKey = key.toString();
                            // split as string list
                            List<String> strategyValues = StringUtils.splitAsList(value.toString());
                            for (String strategyValue : strategyValues) {
                                // trim whitespace
                                strategyValue = strategyValue.trim();
                                if (StringUtils.isNotEmpty(strategyValue)) {
                                    strategies.add(strategyKey, strategyValue);
                                }
                            }
                        }
                    }
                }
                strategiesCache.put(classLoader, strategies);
            } catch (IOException ex) {
                throw new IllegalArgumentException("Unable to load strategies from location [" + STRATEGIES_LOCATION + "]", ex);
            }
        }
    }
    return strategies;
}
Also used : InputStream(java.io.InputStream) IOException(java.io.IOException) Properties(java.util.Properties) ConcurrentReferenceHashMap(cn.taketoday.util.ConcurrentReferenceHashMap) Map(java.util.Map) MultiValueMap(cn.taketoday.core.MultiValueMap) URL(java.net.URL)

Example 4 with MultiValueMap

use of cn.taketoday.core.MultiValueMap 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 5 with MultiValueMap

use of cn.taketoday.core.MultiValueMap in project today-infrastructure by TAKETODAY.

the class MultipartHttpMessageWriterTests method singleSubscriberWithResource.

// SPR-16402
@Test
public void singleSubscriberWithResource() throws IOException {
    Sinks.Many<Resource> sink = Sinks.many().unicast().onBackpressureBuffer();
    Resource logo = new ClassPathResource("/cn/taketoday/http/converter/logo.jpg");
    sink.tryEmitNext(logo);
    MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
    bodyBuilder.asyncPart("logo", sink.asFlux(), Resource.class);
    Mono<MultiValueMap<String, HttpEntity<?>>> result = Mono.just(bodyBuilder.build());
    Map<String, Object> hints = Collections.emptyMap();
    this.writer.write(result, null, MediaType.MULTIPART_FORM_DATA, this.response, hints).block();
    MultiValueMap<String, Part> requestParts = parse(this.response, hints);
    assertThat(requestParts.size()).isEqualTo(1);
    Part part = requestParts.getFirst("logo");
    assertThat(part.name()).isEqualTo("logo");
    assertThat(part instanceof FilePart).isTrue();
    assertThat(((FilePart) part).filename()).isEqualTo("logo.jpg");
    assertThat(part.headers().getContentType()).isEqualTo(MediaType.IMAGE_JPEG);
    assertThat(part.headers().getContentLength()).isEqualTo(logo.getFile().length());
}
Also used : Sinks(reactor.core.publisher.Sinks) Resource(cn.taketoday.core.io.Resource) ClassPathResource(cn.taketoday.core.io.ClassPathResource) ClassPathResource(cn.taketoday.core.io.ClassPathResource) MultipartBodyBuilder(cn.taketoday.http.client.MultipartBodyBuilder) MultiValueMap(cn.taketoday.core.MultiValueMap) Test(org.junit.jupiter.api.Test)

Aggregations

MultiValueMap (cn.taketoday.core.MultiValueMap)46 Test (org.junit.jupiter.api.Test)27 Map (java.util.Map)17 List (java.util.List)13 LinkedMultiValueMap (cn.taketoday.core.LinkedMultiValueMap)12 ResolvableMethodParameter (cn.taketoday.web.handler.method.ResolvableMethodParameter)10 Nullable (cn.taketoday.lang.Nullable)9 DataBuffer (cn.taketoday.core.io.buffer.DataBuffer)8 HttpHeaders (cn.taketoday.http.HttpHeaders)8 MultipartBodyBuilder (cn.taketoday.http.client.MultipartBodyBuilder)8 MethodParameter (cn.taketoday.core.MethodParameter)7 Resource (cn.taketoday.core.io.Resource)6 MatrixParam (cn.taketoday.web.annotation.MatrixParam)5 ArrayList (java.util.ArrayList)5 BeanMetadata (cn.taketoday.beans.BeanMetadata)4 PropertyValue (cn.taketoday.beans.PropertyValue)4 PropertyValues (cn.taketoday.beans.PropertyValues)4 DefaultMultiValueMap (cn.taketoday.core.DefaultMultiValueMap)4 ResolvableType (cn.taketoday.core.ResolvableType)4 TypeDescriptor (cn.taketoday.core.TypeDescriptor)4