use of org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder in project rest-assured by rest-assured.
the class MockMvcRequestSenderImpl method sendRequest.
private MockMvcResponse sendRequest(HttpMethod method, String path, Object[] pathParams) {
notNull(path, "Path");
if (requestBody != null && !multiParts.isEmpty()) {
throw new IllegalStateException("You cannot specify a request body and a multi-part body in the same request. Perhaps you want to change the body to a multi part?");
}
String baseUri;
if (isNotBlank(basePath)) {
baseUri = mergeAndRemoveDoubleSlash(basePath, path);
} else {
baseUri = path;
}
final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri);
if (!queryParams.isEmpty()) {
new ParamApplier(queryParams) {
@Override
protected void applyParam(String paramName, String[] paramValues) {
uriComponentsBuilder.queryParam(paramName, paramValues);
}
}.applyParams();
}
String uri = uriComponentsBuilder.build().toUriString();
final MockHttpServletRequestBuilder request;
if (multiParts.isEmpty()) {
request = MockMvcRequestBuilders.request(method, uri, pathParams);
} else if (method != POST) {
throw new IllegalArgumentException("Currently multi-part file data uploading only works for " + POST);
} else {
request = MockMvcRequestBuilders.fileUpload(uri, pathParams);
}
String requestContentType = findContentType();
if (!params.isEmpty()) {
new ParamApplier(params) {
@Override
protected void applyParam(String paramName, String[] paramValues) {
request.param(paramName, paramValues);
}
}.applyParams();
if (StringUtils.isBlank(requestContentType) && method == POST && !isInMultiPartMode(request)) {
setContentTypeToApplicationFormUrlEncoded(request);
}
}
if (!formParams.isEmpty()) {
if (method == GET) {
throw new IllegalArgumentException("Cannot use form parameters in a GET request");
}
new ParamApplier(formParams) {
@Override
protected void applyParam(String paramName, String[] paramValues) {
request.param(paramName, paramValues);
}
}.applyParams();
boolean isInMultiPartMode = isInMultiPartMode(request);
if (StringUtils.isBlank(requestContentType) && !isInMultiPartMode) {
setContentTypeToApplicationFormUrlEncoded(request);
}
}
if (!attributes.isEmpty()) {
new ParamApplier(attributes) {
@Override
protected void applyParam(String paramName, String[] paramValues) {
request.requestAttr(paramName, paramValues[0]);
}
}.applyParams();
}
if (RestDocsClassPathChecker.isSpringRestDocsInClasspath() && config.getMockMvcConfig().shouldAutomaticallyApplySpringRestDocsMockMvcSupport()) {
request.requestAttr(ATTRIBUTE_NAME_URL_TEMPLATE, PathSupport.getPath(uri));
}
if (StringUtils.isNotBlank(requestContentType)) {
request.contentType(MediaType.parseMediaType(requestContentType));
}
if (headers.exist()) {
for (Header header : headers) {
request.header(header.getName(), header.getValue());
}
}
if (cookies.exist()) {
for (Cookie cookie : cookies) {
javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());
if (cookie.hasComment()) {
servletCookie.setComment(cookie.getComment());
}
if (cookie.hasDomain()) {
servletCookie.setDomain(cookie.getDomain());
}
if (cookie.hasMaxAge()) {
servletCookie.setMaxAge(cookie.getMaxAge());
}
if (cookie.hasPath()) {
servletCookie.setPath(cookie.getPath());
}
if (cookie.hasVersion()) {
servletCookie.setVersion(cookie.getVersion());
}
servletCookie.setSecure(cookie.isSecured());
request.cookie(servletCookie);
}
}
if (!sessionAttributes.isEmpty()) {
request.sessionAttrs(sessionAttributes);
}
if (!multiParts.isEmpty()) {
MockMultipartHttpServletRequestBuilder multiPartRequest = (MockMultipartHttpServletRequestBuilder) request;
for (MockMvcMultiPart multiPart : multiParts) {
MockMultipartFile multipartFile;
String fileName = multiPart.getFileName();
String controlName = multiPart.getControlName();
String mimeType = multiPart.getMimeType();
if (multiPart.isByteArray()) {
multipartFile = new MockMultipartFile(controlName, fileName, mimeType, (byte[]) multiPart.getContent());
} else if (multiPart.isFile() || multiPart.isInputStream()) {
InputStream inputStream;
if (multiPart.isFile()) {
try {
inputStream = new FileInputStream((File) multiPart.getContent());
} catch (FileNotFoundException e) {
return SafeExceptionRethrower.safeRethrow(e);
}
} else {
inputStream = (InputStream) multiPart.getContent();
}
try {
multipartFile = new MockMultipartFile(controlName, fileName, mimeType, inputStream);
} catch (IOException e) {
return SafeExceptionRethrower.safeRethrow(e);
}
} else {
// String
multipartFile = new MockMultipartFile(controlName, fileName, mimeType, ((String) multiPart.getContent()).getBytes());
}
multiPartRequest.file(multipartFile);
}
}
if (requestBody != null) {
if (requestBody instanceof byte[]) {
request.content((byte[]) requestBody);
} else if (requestBody instanceof File) {
byte[] bytes = toByteArray((File) requestBody);
request.content(bytes);
} else {
request.content(requestBody.toString());
}
}
logRequestIfApplicable(method, baseUri, path, pathParams);
return performRequest(request);
}
use of org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder in project spring-security by spring-projects.
the class RequestCacheConfigurerTests method postWhenRequestIsMultipartThenPostAuthenticationRedirectsToRoot.
// SEC-7060
@Test
public void postWhenRequestIsMultipartThenPostAuthenticationRedirectsToRoot() throws Exception {
this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
MockMultipartFile aFile = new MockMultipartFile("aFile", "A_FILE".getBytes());
MockMultipartHttpServletRequestBuilder request = multipart("/upload").file(aFile);
// @formatter:off
MockHttpSession session = (MockHttpSession) this.mvc.perform(request).andReturn().getRequest().getSession();
// @formatter:on
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("/"));
}
use of org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder 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;
}
use of org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder in project TOSCAna by StuPro-TOSCAna.
the class CsarControllerTest method uploadTest.
@Test
public void uploadTest() throws Exception {
byte[] data = generateRandomByteArray(rnd, 10 * 1024);
byte[] hash = getSHA256Hash(data);
String path = CSAR_BASE_URL + "rnd";
MockMultipartHttpServletRequestBuilder builder = buildMockedMultipartUploadRequest(data, path);
ResultActions resultActions = mvc.perform(builder).andDo(print()).andExpect(status().is2xxSuccessful());
resultActions.andReturn();
assertNotNull(dataRead);
assertEquals(data.length, dataRead.length);
byte[] hashUpload = getSHA256Hash(this.dataRead);
assertHashesEqual(hash, hashUpload);
}
use of org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder in project ArachneCentralAPI by OHDSI.
the class AnalysisControllerTests method testUpdateCodeFile.
@Test
@WithUserDetails(value = ADMIN_EMAIL)
@DatabaseSetups({ @DatabaseSetup("/data/study-with-contributor.xml"), @DatabaseSetup("/data/analysis/analysis-list.xml"), @DatabaseSetup("/data/analysis/code-file-before-deleting.xml") })
@ExpectedDatabases({ @ExpectedDatabase(value = "/data/study-with-contributor.xml", assertionMode = NON_STRICT), @ExpectedDatabase(value = "/data/analysis/code-file-after-updating.xml", assertionMode = NON_STRICT) })
public void testUpdateCodeFile() throws Exception {
String uuid = "68b75ac9-ab29-49a6-8edb-95142456f5fc";
String path = this.getClass().getResource("/test.jpg").getPath();
FileInputStream fileInputStream = new FileInputStream(path);
MockMultipartFile multipartFile = new MockMultipartFile("file", "test_updated.jpg", "image/jpeg", fileInputStream);
MockMultipartHttpServletRequestBuilder builder = fileUpload("/api/v1/analysis-management/analyses/{analysisId}/files/{fileUuid}", ANALYSIS_ID, uuid);
builder.with(request -> {
request.setMethod("PUT");
return request;
});
mvc.perform(builder.file(multipartFile).param("label", "labelUploadedFile").param("file", path).contentType(MULTIPART_FORM_DATA)).andExpect(NO_ERROR_CODE).andExpect(TRUE_RESULT);
}
Aggregations