List of usage examples for org.springframework.mock.web MockMultipartFile MockMultipartFile
public MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream) throws IOException
From source file:org.bonitasoft.web.designer.controller.PageResourceTest.java
@Test public void should_not_upload_an_asset_when_upload_send_an_error() throws Exception { //We construct a mockfile (the first arg is the name of the property expected in the controller MockMultipartFile file = new MockMultipartFile("file", "myfile.js", "application/javascript", "foo".getBytes()); Page page = mockPageOfId("my-page"); doThrow(IllegalArgumentException.class).when(pageAssetService).upload(file, page, "js"); mockMvc.perform(fileUpload("/rest/pages/my-page/assets/js").file(file)).andExpect(status().isBadRequest()); verify(pageAssetService).upload(file, page, "js"); }
From source file:com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java
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?"); }//from www . jav a 2s . co m String uri; if (isNotBlank(basePath)) { uri = mergeAndRemoveDoubleSlash(basePath, path); } else { uri = path; } 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 (!queryParams.isEmpty()) { new ParamApplier(queryParams) { @Override protected void applyParam(String paramName, String[] paramValues) { // Spring MVC cannot distinguish query from params afaik. request.param(paramName, paramValues); } }.applyParams(); } 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()); } request.cookie(servletCookie); } } 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, uri, path, pathParams); return performRequest(request); }
From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java
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?"); }/*from w w w.j a v a2s . c o m*/ 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); }
From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java
private void createTaxonAttributes(MockMultipartHttpServletRequest request, TaxonGroup taxonGroup) throws ParseException, IOException { String name;// w w w .j a va 2 s. c o m IndicatorSpeciesAttribute taxonAttr; Preference testDataDirPref = prefDAO.getPreferenceByKey(TEST_DATA_IMAGE_DIR); for (Attribute attr : taxonGroup.getAttributes()) { if (attr.isTag()) { name = String.format(AttributeParser.ATTRIBUTE_NAME_TEMPLATE, AttributeParser.DEFAULT_PREFIX, attr.getId()); taxonAttr = new IndicatorSpeciesAttribute(); taxonAttr.setAttribute(attr); if (AttributeType.IMAGE.equals(attr.getType()) || AttributeType.FILE.equals(attr.getType())) { byte[] data; String contentType; String filename; if (AttributeType.IMAGE.equals(attr.getType())) { data = getRandomImage(testDataDirPref, 640, 480); data = data == null ? createImage(640, 480, attr.getDescription()) : data; contentType = "image/png"; filename = String.format("%s.png", attr.getName()); } else { data = generateDataFile(); contentType = "text/plain"; filename = String.format("%s.txt", attr.getName()); } String attrFileKey = String.format(AttributeParser.ATTRIBUTE_FILE_NAME_TEMPLATE, AttributeParser.DEFAULT_PREFIX, attr.getId()); MockMultipartFile mockFileFile = new MockMultipartFile(attrFileKey, filename, contentType, data); request.addFile(mockFileFile); taxonAttr.setStringValue(filename); } else { setValueForTaxonAttribute(taxonAttr); } request.addParameter(name, taxonAttr.getStringValue()); } } }
From source file:com.netflix.genie.web.controllers.JobRestControllerIntegrationTests.java
private String submitJob(final int documentationId, final JobRequest jobRequest, final List<MockMultipartFile> attachments) throws Exception { final MvcResult result; if (attachments != null) { final RestDocumentationResultHandler createResultHandler = MockMvcRestDocumentation.document( "{class-name}/" + documentationId + "/submitJobWithAttachments/", Preprocessors.preprocessRequest(Preprocessors.prettyPrint()), Preprocessors.preprocessResponse(Preprocessors.prettyPrint()), HeaderDocumentation.requestHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE) .description(MediaType.MULTIPART_FORM_DATA_VALUE)), // Request headers RequestDocumentation.requestParts( RequestDocumentation.partWithName("request").description( "The job request JSON. Content type must be application/json for part"), RequestDocumentation.partWithName("attachment").description( "An attachment file. There can be multiple. Type should be octet-stream")), // Request parts Snippets.LOCATION_HEADER // Response Headers );//ww w. j a v a 2 s .c om final MockMultipartFile json = new MockMultipartFile("request", "", MediaType.APPLICATION_JSON_VALUE, this.objectMapper.writeValueAsBytes(jobRequest)); final MockMultipartHttpServletRequestBuilder builder = RestDocumentationRequestBuilders .fileUpload(JOBS_API).file(json); for (final MockMultipartFile attachment : attachments) { builder.file(attachment); } builder.contentType(MediaType.MULTIPART_FORM_DATA); result = this.mvc.perform(builder).andExpect(MockMvcResultMatchers.status().isAccepted()) .andExpect(MockMvcResultMatchers.header().string(HttpHeaders.LOCATION, Matchers.notNullValue())) .andDo(createResultHandler).andReturn(); } else { // Use regular POST final RestDocumentationResultHandler createResultHandler = MockMvcRestDocumentation.document( "{class-name}/" + documentationId + "/submitJobWithoutAttachments/", Preprocessors.preprocessRequest(Preprocessors.prettyPrint()), Preprocessors.preprocessResponse(Preprocessors.prettyPrint()), Snippets.CONTENT_TYPE_HEADER, // Request headers Snippets.getJobRequestRequestPayload(), // Request Fields Snippets.LOCATION_HEADER // Response Headers ); result = this.mvc .perform(MockMvcRequestBuilders.post(JOBS_API).contentType(MediaType.APPLICATION_JSON) .content(this.objectMapper.writeValueAsBytes(jobRequest))) .andExpect(MockMvcResultMatchers.status().isAccepted()) .andExpect(MockMvcResultMatchers.header().string(HttpHeaders.LOCATION, Matchers.notNullValue())) .andDo(createResultHandler).andReturn(); } return this.getIdFromLocation(result.getResponse().getHeader(HttpHeaders.LOCATION)); }
From source file:org.bonitasoft.web.designer.controller.WidgetResourceTest.java
@Test public void should_upload_a_local_asset() throws Exception { //We construct a mockfile (the first arg is the name of the property expected in the controller MockMultipartFile file = new MockMultipartFile("file", "myfile.js", "application/javascript", "foo".getBytes()); Widget widget = aWidget().id("my-widget").custom().build(); Asset expectedAsset = anAsset().withId("assetId").active().withName("myfile.js").withOrder(2) .withType(AssetType.JAVASCRIPT).build(); when(widgetRepository.get("my-widget")).thenReturn(widget); when(widgetAssetService.upload(file, widget, "js")).thenReturn(expectedAsset); mockMvc.perform(fileUpload("/rest/widgets/my-widget/assets/js").file(file)).andExpect(status().isCreated()) .andExpect(jsonPath("$.id").value("assetId")).andExpect(jsonPath("$.name").value("myfile.js")) .andExpect(jsonPath("$.type").value("js")).andExpect(jsonPath("$.order").value(2)); verify(widgetAssetService).upload(file, widget, "js"); }
From source file:fragment.web.AbstractConnectorControllerTest.java
@Test public void testUploadServiceInstanceLogo() throws Exception { Configuration configuration = configurationService .locateConfigurationByName(Names.com_citrix_cpbm_portal_settings_images_uploadPath); configuration.setValue("src\\test\\resources"); configurationService.update(configuration); ServiceInstance serviceInstance = serviceInstanceDao.find(1L); Assert.assertEquals(null, serviceInstance.getImagePath()); MultipartFile logo = new MockMultipartFile("ServiceInstanceLogo.jpeg", "ServiceInstanceLogo.jpeg", "byte", "ServiceInstance".getBytes()); ServiceInstanceLogoForm form = new ServiceInstanceLogoForm(serviceInstance); form.setLogo(logo);//w w w. j ava 2s . c om BindingResult result = validate(form); HttpServletRequest request = new MockHttpServletRequest(); map = new ModelMap(); String resultString = controller.uploadServiceInstanceLogo(form, result, request, map); Assert.assertNotNull(resultString); Assert.assertEquals("success", resultString); serviceInstance = serviceInstanceDao.find(1L); Assert.assertEquals(FilenameUtils.separatorsToSystem("serviceInstance\\1\\ServiceInstanceLogo.jpeg"), serviceInstance.getImagePath()); }
From source file:org.bonitasoft.web.designer.controller.WidgetResourceTest.java
@Test public void should_not_upload_an_asset() throws Exception { //We construct a mockfile (the first arg is the name of the property expected in the controller MockMultipartFile file = new MockMultipartFile("file", "myfile.js", "application/javascript", "foo".getBytes()); Widget widget = aWidget().id("my-widget").custom().build(); when(widgetRepository.get("my-widget")).thenReturn(widget); doThrow(IllegalArgumentException.class).when(widgetAssetService).upload(file, widget, "js"); mockMvc.perform(fileUpload("/rest/widgets/my-widget/assets/js").file(file)) .andExpect(status().isBadRequest()); verify(widgetAssetService).upload(file, widget, "js"); }