<commit_before>/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.mvc.method.annotation;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import jakarta.servlet.MultipartConfigElement;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * Test access to parts of a multipart request with {@link RequestPart}.
 *
 * @author <NAME>
 * @author <NAME>
 * @author <NAME>
 */
public class RequestPartIntegrationTests {

	private RestTemplate restTemplate;

	private static Server server;

	private static String baseUrl;


	@BeforeAll
	public static void startServer() throws Exception {
		// Let server pick its own random, available port.
		server = new Server(0);

		ServletContextHandler handler = new ServletContextHandler();
		handler.setContextPath("/");
		ServletHolder standardResolverServlet = new ServletHolder(DispatcherServlet.class);
		standardResolverServlet.setInitParameter("contextConfigLocation", StandardMultipartResolverTestConfig.class.getName());
		standardResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
		standardResolverServlet.getRegistration().setMultipartConfig(new MultipartConfigElement(""));
		handler.addServlet(standardResolverServlet, "/standard-resolver/*");

		server.setHandler(handler);
		server.start();

		Connector[] connectors = server.getConnectors();
		NetworkConnector connector = (NetworkConnector) connectors[0];
		baseUrl = "http://localhost:" + connector.getLocalPort();
	}

	@AfterAll
	public static void stopServer() throws Exception {
		if (server != null) {
			server.stop();
		}
	}

	@BeforeEach
	public void setup() {
		ByteArrayHttpMessageConverter emptyBodyConverter = new ByteArrayHttpMessageConverter();
		emptyBodyConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

		List<HttpMessageConverter<?>> converters = new ArrayList<>(3);
		converters.add(emptyBodyConverter);
		converters.add(new ByteArrayHttpMessageConverter());
		converters.add(new ResourceHttpMessageConverter());
		converters.add(new MappingJackson2HttpMessageConverter());

		AllEncompassingFormHttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter();
		converter.setPartConverters(converters);

		restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
		restTemplate.setMessageConverters(Collections.singletonList(converter));
	}


	@Test
	public void standardMultipartResolver() throws Exception {
		testCreate(baseUrl + "/standard-resolver/test", "Jason");
		testCreate(baseUrl + "/standard-resolver/test", "Arjen");
	}

	@Test  // SPR-13319
	public void standardMultipartResolverWithEncodedFileName() throws Exception {
		byte[] boundary = MimeTypeUtils.generateMultipartBoundary();
		String boundaryText = new String(boundary, "US-ASCII");
		Map<String, String> params = Collections.singletonMap("boundary", boundaryText);

		String content =
				"--" + boundaryText + "\n" +
				"Content-Disposition: form-data; name=\"file\"; filename*=\"utf-8''%C3%A9l%C3%A8ve.txt\"\n" +
				"Content-Type: text/plain\n" +
				"Content-Length: 7\n" +
				"\n" +
				"content\n" +
				"--" + boundaryText + "--";

		RequestEntity<byte[]> requestEntity =
				RequestEntity.post(new URI(baseUrl + "/standard-resolver/spr13319"))
						.contentType(new MediaType(MediaType.MULTIPART_FORM_DATA, params))
						.body(content.getBytes(StandardCharsets.US_ASCII));

		ByteArrayHttpMessageConverter converter = new ByteArrayHttpMessageConverter();
		converter.setSupportedMediaTypes(Collections.singletonList(MediaType.MULTIPART_FORM_DATA));
		this.restTemplate.setMessageConverters(Collections.singletonList(converter));

		ResponseEntity<Void> responseEntity = restTemplate.exchange(requestEntity, Void.class);
		assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);<commit_msg>Fix multipart request test with Jetty server<commit_after>/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.mvc.method.annotation;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import jakarta.servlet.MultipartConfigElement;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * Test access to parts of a multipart request with {@link RequestPart}.
 *
 * @author <NAME>
 * @author <NAME>
 * @author <NAME>
 */
public class RequestPartIntegrationTests {

	private RestTemplate restTemplate;

	private static Server server;

	private static String baseUrl;


	@BeforeAll
	public static void startServer() throws Exception {
		// Let server pick its own random, available port.
		server = new Server(0);

		ServletContextHandler handler = new ServletContextHandler();
		handler.setContextPath("/");
		ServletHolder standardResolverServlet = new ServletHolder(DispatcherServlet.class);
		standardResolverServlet.setInitParameter("contextConfigLocation", StandardMultipartResolverTestConfig.class.getName());
		standardResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
		standardResolverServlet.getRegistration().setMultipartConfig(new MultipartConfigElement(""));
		handler.addServlet(standardResolverServlet, "/standard-resolver/*");

		server.setHandler(handler);
		server.start();

		Connector[] connectors = server.getConnectors();
		NetworkConnector connector = (NetworkConnector) connectors[0];
		baseUrl = "http://localhost:" + connector.getLocalPort();
	}

	@AfterAll
	public static void stopServer() throws Exception {
		if (server != null) {
			server.stop();
		}
	}

	@BeforeEach
	public void setup() {
		ByteArrayHttpMessageConverter emptyBodyConverter = new ByteArrayHttpMessageConverter();
		emptyBodyConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

		List<HttpMessageConverter<?>> converters = new ArrayList<>(3);
		converters.add(emptyBodyConverter);
		converters.add(new ByteArrayHttpMessageConverter());
		converters.add(new ResourceHttpMessageConverter());
		converters.add(new MappingJackson2HttpMessageConverter());

		AllEncompassingFormHttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter();
		converter.setPartConverters(converters);

		restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
		restTemplate.setMessageConverters(Collections.singletonList(converter));
	}


	@Test
	public void standardMultipartResolver() throws Exception {
		testCreate(baseUrl + "/standard-resolver/test", "Jason");
		testCreate(baseUrl + "/standard-resolver/test", "Arjen");
	}

	@Test  // SPR-13319
	public void standardMultipartResolverWithEncodedFileName() throws Exception {
		String boundaryText = MimeTypeUtils.generateMultipartBoundaryString();
		Map<String, String> params = Collections.singletonMap("boundary", boundaryText);

		String content =
				"--" + boundaryText + "\r\n" +
				"Content-Disposition: form-data; name=\"file\"; filename*=\"utf-8''%C3%A9l%C3%A8ve.txt\"\r\n" +
				"Content-Type: text/plain\r\n" +
				"Content-Length: 7\r\n" +
				"\r\n" +
				"content\r\n" +
				"--" + boundaryText + "--";

		RequestEntity<byte[]> requestEntity =
				RequestEntity.post(new URI(baseUrl + "/standard-resolver/spr13319"))
						.contentType(new MediaType(MediaType.MULTIPART_FORM_DATA, params))
						.body(content.getBytes(StandardCharsets.US_ASCII));

		ByteArrayHttpMessageConverter converter = new ByteArrayHttpMessageConverter();
		converter.setSupportedMediaTypes(Collections.singletonList(MediaType.MULTIPART_FORM_DATA));
		this.restTemplate.setMessageConverters(Collections.singletonList(converter));

		ResponseEntity<Void> responseEntity = restTemplate.exchange(requestEntity, Void.class);
		assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
{'fraction_non_alphanumeric': 0.10252285191956124, 'fraction_numerical': 0.004826325411334552, 'mean_word_length': 6.336909871244635, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '686128', 'n_tokens_mistral': 3887, 'n_tokens_neox': 3648, 'n_words': 744}