Example usage for org.springframework.mock.web MockMultipartFile MockMultipartFile

List of usage examples for org.springframework.mock.web MockMultipartFile MockMultipartFile

Introduction

In this page you can find the example usage for org.springframework.mock.web MockMultipartFile MockMultipartFile.

Prototype

public MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType,
        InputStream contentStream) throws IOException 

Source Link

Document

Create a new MockMultipartFile with the given content.

Usage

From source file:org.bonitasoft.web.designer.controller.asset.AssetServiceTest.java

@Test
public void should_upload_existing_file() throws Exception {
    Asset existingAsset = anAsset().withId("UIID").withName("asset.js").build();
    Page page = aPage().withId("page-id").withName("my-page").withAsset(existingAsset).build();
    MockMultipartFile file = new MockMultipartFile("asset.js", "asset.js", "application/javascript",
            "function(){}".getBytes());

    Asset asset = assetService.upload(file, page, "js");

    verify(assetRepository).delete(any(Asset.class));
    verify(assetRepository).save("page-id", page.getAssets().iterator().next(), "function(){}".getBytes());
    verify(repository).updateLastUpdateAndSave(page);
    assertThat(asset.getId()).isEqualTo(existingAsset.getId());
}

From source file:business.UploadTests.java

@Test(groups = "upload", dependsOnMethods = "createRequest")
public void uploadFileSuccess() throws IOException {
    UserAuthenticationToken requester = getRequester();
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(requester);

    RequestRepresentation representation = requestController.getRequestById(requester, processInstanceId);
    log.info("Status: " + representation.getStatus());
    int attachmentCount = representation.getAttachments().size();

    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource("test/Utrecht_Oude_Gracht_Hamburgerbrug_(LOC).jpg");
    InputStream input = resource.openStream();
    MultipartFile file = new MockMultipartFile(resource.getFile(), resource.getFile().toString(), "image/jpeg",
            input);//from  w  w  w . j  a  va  2  s .c  o  m

    Integer flowTotalChunks = 1;
    Integer flowChunkNumber = 1;
    String flowIdentifier = "flow";

    representation = requestController.uploadRequestAttachment(requester, processInstanceId, resource.getFile(),
            flowTotalChunks, flowChunkNumber, flowIdentifier, file);

    assertEquals(attachmentCount + 1, representation.getAttachments().size());
    printFiles(representation.getAttachments());

    SecurityContextHolder.clearContext();
}

From source file:org.jtalks.common.web.controller.UserController.java

/**
 * Update user profile info. Check if the user enter valid data and update profile in database.
 * In error case return into the edit profile page and draw the error.
 *
 * @param userDto dto populated by user//from   w w w .ja v a  2 s .  c  om
 * @param result  binding result which contains the validation result
 * @return in case of errors return back to edit profile page, in another case return to user detalis page
 * @throws NotFoundException   - throws if current logged in user was not found
 * @throws java.io.IOException - throws in case of access errors (if the temporary store fails)
 */
@RequestMapping(value = "/user/edit", method = RequestMethod.POST)
public ModelAndView editProfile(@Valid @ModelAttribute(EDITED_USER) EditUserProfileDto userDto,
        BindingResult result) throws NotFoundException, IOException {

    User user = securityService.getCurrentUser();

    if (result.hasErrors()) {
        //we should show current user avatar (if any)
        //if no file was uploaded, or if there were validation errors on avatar field
        if ((userDto.getAvatar().getSize() == 0) || (result.hasFieldErrors("avatar"))) {
            userDto.setAvatar(
                    new MockMultipartFile("avatar", "", ImageFormats.JPG.getContentType(), user.getAvatar()));
        }
        return new ModelAndView(EDIT_PROFILE, EDITED_USER, userDto);
    }

    User editedUser;
    try {
        editedUser = userService.editUserProfile(userDto.getEmail(), userDto.getFirstName(),
                userDto.getLastName(), userDto.getCurrentUserPassword(), userDto.getNewUserPassword(),
                userDto.getAvatar().getBytes());
    } catch (DuplicateEmailException e) {
        result.rejectValue("email", "validation.duplicateemail");
        return new ModelAndView(EDIT_PROFILE);
    } catch (WrongPasswordException e) {
        result.rejectValue("currentUserPassword", "label.incorrectCurrentPassword",
                "Password does not match to the current password");
        return new ModelAndView(EDIT_PROFILE);
    }
    return new ModelAndView(new StringBuilder().append("redirect:/user/")
            .append(editedUser.getEncodedUsername()).append(".html").toString());
}

From source file:com.formkiq.core.service.workflow.WorkflowEditorServiceImplTest.java

/**
 * testEventAddStep02().//from  w  ww . ja  v  a  2s  . co m
 * Add step - MultipartHttpServletRequest
 * @throws IOException IOException
 */
@SuppressWarnings("unchecked")
@Test
public void testEventAddStep02() throws IOException {
    // given
    this.archive.setWorkflow(this.workflow);
    MockMultipartHttpServletRequest req = new MockMultipartHttpServletRequest();
    req.setRequestURI("/home");

    byte[] content = Strings.toByteArray("test");
    req.addFile(new MockMultipartFile("sample.pdf", "sample.pdf", "", content));

    // when
    expect(this.flow.getData()).andReturn(this.archive);

    this.flow.setStates(isA(List.class));
    this.flow.setEventId(1);

    Map<String, WorkflowOutputGenerator> map = ImmutableMap.of("test", this.pdfEditor);
    expect(this.context.getBeansOfType(WorkflowOutputGenerator.class)).andReturn(map);
    expect(this.pdfEditor.getNewWorkflowOutputDocument()).andReturn(new WorkflowOutputPdfForm());
    this.pdfEditor.generate(this.archive, "sample.pdf", content);

    replayAll();
    this.ws.eventIdaddstep(this.flow, req, null);

    // then
    verifyAll();
}

From source file:org.bonitasoft.web.designer.controller.asset.AssetServiceTest.java

@Test(expected = MalformedJsonException.class)
public void should_check_that_json_is_well_formed_while_uploading_a_json_asset() throws Exception {
    MockMultipartFile file = new MockMultipartFile("asset.json", "asset.json", "application/javascript",
            "{ not json }".getBytes());

    assetService.upload(file, aPage().build(), "json");
}

From source file:de.tobiasbruns.content.storage.ContentControllerITCase.java

@Test
public void test11_uploadBinaryFile() throws Exception {
    InputStream testStream = TestUtils.loadFile("requests/testimg.jpeg");

    mockMvc.perform(fileUpload(BASE + "/folder")
            .file(new MockMultipartFile("file", "testimage.jpeg", "image/jpeg", testStream)))
            .andExpect(status().isCreated())//
            .andExpect(header().string("Location", "http://localhost:8080/folder/testimage.jpeg"))
            .andDo(TestUtils.writeDoc("addBinaryContent"));
}

From source file:de.unimannheim.spa.process.rest.ProjectRestControllerTest.java

@Test
public void itShouldReturn500ForCreatingAProcessWithUnsopportedFormat() throws Exception {
    expected.expect(NestedServletException.class);
    final String projectIDForTest = createProjectAndReturnID();
    final String processLabelToTest = "newProcessLabelToTest";
    final String unsupportedFormat = "TXT";
    MockMultipartFile processFileToTest = new MockMultipartFile("processFile", "example-spa.bpmn",
            MediaType.MULTIPART_FORM_DATA_VALUE, Files.toByteArray(getFilePath("example-spa.bpmn").toFile()));
    mockMvc.perform(fileUpload("/projects/" + projectIDForTest + "/processes").file(processFileToTest)
            .param("processLabel", processLabelToTest).param("format", unsupportedFormat))
            .andExpect(status().isInternalServerError());
}

From source file:org.bonitasoft.web.designer.controller.ImportControllerTest.java

@Test
public void should_force_a_page_import() 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.zip", "application/zip", "foo".getBytes());
    ImportReport expectedReport = anImportReportFor(aPage().withId("aPage").withName("thePage"))
            .withUUID("UUIDZipFile").withStatus(ImportReport.Status.IMPORTED)
            .withAdded(aWidget().id("addedWidget").name("newWidget"))
            .withOverridden(aWidget().id("overriddenWidget").name("oldWidget")).build();
    when(pathImporter.forceImportFromPath(unzipedPath, pageImporter)).thenReturn(expectedReport);

    mockMvc.perform(fileUpload("/import/page?force=true").file(file))
            .andExpect(content().contentType(MediaType.TEXT_PLAIN)).andExpect(status().isCreated())
            .andExpect(jsonPath("uuid").value("UUIDZipFile"))
            .andExpect(jsonPath("extractedDirName").doesNotExist())
            .andExpect(jsonPath("element.id").value("aPage")).andExpect(jsonPath("status").value("imported"))
            .andExpect(jsonPath("element.name").value("thePage"))
            .andExpect(jsonPath("dependencies.added.widget[0].id").value("addedWidget"))
            .andExpect(jsonPath("dependencies.added.widget[0].name").value("newWidget"))
            .andExpect(jsonPath("dependencies.overridden.widget[0].id").value("overriddenWidget"))
            .andExpect(jsonPath("dependencies.overridden.widget[0].name").value("oldWidget"));
}

From source file:com.ethercamp.harmony.service.ContractsTests.java

@Test
public void contracts_shouldDetectContractName_whenManyContracts() throws Exception {
    // prepare//  w w  w  .java2s . co m
    final String sourceCode = loadSourceCode("contracts/NameReg.sol");
    final String contractBin = loadContractBin(sourceCode, "NameReg");
    //when(repository.getCode(any())).thenReturn(Hex.decode(contractBin));
    String bin = "606060405260e060020a600035046341c0e1b581146044578063bb34534c146050578063e1fa8e84146086578063e79a198f146044578063f5c573821460a1575b6000565b34600057604e60c0565b005b34600057605d60043560c3565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b34600057604e60043560cb565b005b34600057604e60c0565b005b3460005760ae60043560c3565b60408051918252519081900360200190f35b5b565b60005b919050565b5b50565b5b565b60005b91905056";
    when(repository.getCode(any())).thenReturn(Hex.decode(bin));

    // test
    MockMultipartFile[] files = {
            new MockMultipartFile("contract.sol", "contract.sol", "plain/text",
                    loadSourceCode("contracts/Contract.sol").getBytes()),
            new MockMultipartFile("NameReg.sol", "NameReg.sol", "plain/text",
                    loadSourceCode("contracts/NameReg.sol").getBytes()),
            new MockMultipartFile("std.sol", "std.sol", "plain/text",
                    loadSourceCode("contracts/std.sol").getBytes()) };
    ContractInfoDTO addedContract = contractsService.uploadContract(ADDRESS, files);

    assertThat(addedContract.getName(), is("NameReg"));
}

From source file:org.openmrs.module.radiology.test.RadiologyTestData.java

/**
 * Convenience method constructing a multipart file for the tests
 *//*  ww w .  j  a v  a 2 s  .  c o m*/
public static MockMultipartFile getMockMultipartFileForMockObsWithComplexConcept() {
    final String fileName = "test.jpg";
    final byte[] content = "FFD8FFE000104A46".getBytes();
    return new MockMultipartFile("complexDataFile", fileName, "image/jpeg", content);
}