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:eionet.webq.converter.MultipartFileToUserFileConverterTest.java

private MultipartFile createMultipartFile(String contentType, byte[] content) {
    return new MockMultipartFile("xmlFileUpload", originalFilename, contentType, content);
}

From source file:org.openmrs.module.conceptmanagementapps.api.ConceptManagementAppsServiceTest.java

@Test
public void uploadSpreadsheet_shouldPassWithoutErrors() throws Exception {
    conceptManagementAppsService = (ConceptManagementAppsService) Context
            .getService(ConceptManagementAppsService.class);
    final String fileName = "test.csv";
    String line = "\"map type\",\"source name\",\"source code\",\"concept Id\",\"concept uuid\",\"preferred name\",\"description\",\"class\",\"datatype\",\"all existing mappings\"\n";
    line += "\"same-as\",\"\",12345,225,\"432AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"MEDICAL EXAMINATION, ROUTINE\",\"Routine examination, without signs of problems.\",\"Procedure\",\"Boolean\",\"SAME-AS AMPATH \n SAME-AS SNOMED MVP\n SAME-AS PIH \n SAME-AS AMPATH \n NARROWER-THAN SNOMED NP\"\n";
    line += "\"same-as\",\"SNOMED CT\",12345,225,\"432AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"MEDICAL EXAMINATION, ROUTINE\",\"Routine examination, without signs of problems.\",\"Procedure\",\"Boolean\",\"SAME-AS AMPATH \n SAME-AS SNOMED MVP\n SAME-AS PIH \n SAME-AS AMPATH \n NARROWER-THAN SNOMED NP\"\n";
    line += "\"same-as\",\"SNOMED CT\",12345,225,\"1148AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"TOTAL MATERNAL TO CHILD TRANSMISSION PROPHYLAXIS\",\"Describes the use of drugs to prevent the maternal to child transmission of HIV during pregnancy.\",\"Procedure\",\"Coded\",\"SAME-AS AMPATH \n NARROWER-THAN SNOMED NP \n SAME-AS SNOMED MVP\"\n";
    final byte[] content = line.getBytes();
    MockMultipartFile mockMultipartFile = new MockMultipartFile("content", fileName, "text/plain", content);
    conceptManagementAppsService.uploadSpreadsheet(mockMultipartFile);

}

From source file:com.dominion.salud.nomenclator.negocio.service.tools.BuzonSucesosServiceTest.java

@Ignore
@Test//  w  w w.  j a  va 2 s. com
public void upload() {
    logger.info("INIT [" + getClass().getName() + ".upload()]");

    try {
        System.setProperty("nomenclator.temp",
                "/home/jcgonzalez/Documentos/PROYECTOS/Nomenclator/Bases de Datos/Version 5 - 2015.07.06/xml/temp/");
        File file = new File(
                "/home/jcgonzalez/Documentos/PROYECTOS/Nomenclator/Bases de Datos/Version 5 - 2015.07.06/xml/AEMPS.01082016.zip");
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
                IOUtils.toByteArray(input));

        buzonSucesosService.upload(multipartFile);
        Assert.assertTrue(true);
    } catch (Exception e) {
        Assert.fail(e.toString());
    }

    logger.info("END [" + getClass().getName() + ".upload()]");
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_9.ObsController1_9Test.java

@Test
public void shouldUploadFileAndFetchComplexObs() throws Exception {
    ConceptComplex conceptComplex = newConceptComplex();

    InputStream in = getClass().getClassLoader().getResourceAsStream("customTestDataset.xml");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copy(in, out);/*from  ww  w  . j  ava2 s .  c  o  m*/

    String json = "{\"concept\":\"" + conceptComplex.getUuid()
            + "\", \"person\":\"5946f880-b197-400b-9caa-a3c661d23041\","
            + "\"obsDatetime\":\"2015-09-07T00:00:00.000+0530\"}";

    MockMultipartHttpServletRequest request = newUploadRequest(getURI());
    request.addFile(new MockMultipartFile("file", "customTestDataset.xml", null, out.toByteArray()));
    request.addParameter("json", json);

    SimpleObject response = deserialize(handle(request));

    MockHttpServletResponse rawResponse = handle(
            newGetRequest(getURI() + "/" + response.get("uuid") + "/value"));

    assertThat(out.toByteArray(), is(equalTo(rawResponse.getContentAsByteArray())));
}

From source file:alpha.portal.webapp.controller.CardFileUploadControllerTest.java

/**
 * Test zero file.//from  w  w w.j  a v  a  2 s  .  c o m
 */
@Test
public void testZeroFile() {
    final String caseId = "550e4713-e22b-11d4-a716-446655440000";
    final String cardId = "440e4816-e01b-74d4-a716-449955440092";
    final String fileName = "doesnotcompute.file";
    final String mimeType = "text/plain";
    final byte[] content = "".getBytes();

    final MockHttpServletRequest request = this.newGet("/cardfileupload");
    request.setRemoteUser("admin");
    request.addParameter("case", caseId);
    request.addParameter("card", cardId);
    final FileUpload fileUpload = this.ctrl.showForm(request);
    fileUpload.setFile(content);

    final MockMultipartHttpServletRequest upload = new MockMultipartHttpServletRequest();
    upload.setRemoteUser("user");
    final MockMultipartFile file = new MockMultipartFile("file", fileName, mimeType, content);
    upload.addFile(file);
    upload.addParameter("case", caseId);
    upload.addParameter("card", cardId);

    final BindingResult errors = new DataBinder(fileUpload).getBindingResult();
    String result = "";
    try {
        result = this.ctrl.onSubmit(fileUpload, errors, upload);
    } catch (final IOException e) {
        Assert.fail("Should not fail on fail upload");
    }
    Assert.assertTrue(errors.hasErrors());
    final List<ObjectError> errorList = errors.getAllErrors();
    Assert.assertEquals(1, errorList.size());
    Assert.assertEquals("errors.required", errorList.get(0).getCode());
    Assert.assertNull(upload.getSession().getAttribute("successMessages"));

    Assert.assertEquals("redirect:/cardfileupload?card=" + cardId + "&case=" + caseId, result);
}

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

@Test
public void itShouldReturnNotFoundForCreatingAProcessInNonExistentProjectID() throws Exception {
    final String processLabelToTest = "newProcessLabelToTest";
    MockMultipartFile processFileToTest = new MockMultipartFile("processFile", "example-spa.bpmn",
            MediaType.MULTIPART_FORM_DATA_VALUE, Files.toByteArray(getFilePath("example-spa.bpmn").toFile()));
    mockMvc.perform(fileUpload("/projects/" + NON_EXISTENT_PROJECT_ID_TO_TEST + "/processes")
            .file(processFileToTest).param("processLabel", processLabelToTest).param("format", "BPMN2"))
            .andExpect(status().isNotFound());
}

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

@Test
public void should_return_error_when_uploading_with_error_onsave() throws Exception {
    expectedException.expect(ServerImportException.class);
    expectedException.expectMessage(is("Error while uploading asset in myfile.inv [null]"));

    Page page = aPage().build();//from w ww  . ja  v a  2  s .co m
    MockMultipartFile file = new MockMultipartFile("file.js", "myfile.inv", "application/javascript",
            "function(){}".getBytes());
    doThrow(IOException.class).when(repository).updateLastUpdateAndSave(page);

    assetService.upload(file, page, "js");
}

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

@Test
public void should_import_a_page_with_its_dependencies() 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.CONFLICT)
            .withAdded(aWidget().id("addedWidget").name("newWidget"))
            .withOverridden(aWidget().id("overriddenWidget").name("oldWidget")).build();
    when(pathImporter.importFromPath(unzipedPath, pageImporter)).thenReturn(expectedReport);

    mockMvc.perform(fileUpload("/import/page").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("conflict"))
            .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:wepa.service.initservice.InitService.java

public MultipartFile getImage(String imagePath) {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream(imagePath);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {/*from   w w w  .  j av a  2  s . c  o  m*/
        IOUtils.copy(is, outputStream);
    } catch (IOException ioe) {
        System.out.println("Problem while reading from the file: " + ioe.getMessage());
        return null;
    }

    byte[] bytes = outputStream.toByteArray();
    MultipartFile multipartFile = new MockMultipartFile("file", "hippo.jpg", "image/jpeg", bytes);
    return multipartFile;
}

From source file:com.dominion.salud.nomenclator.web.controller.tools.BuzonSucesosControllerTest.java

@Ignore
@Test//w  w  w. ja v a  2  s .c  o m
public void upload() {
    logger.info("INIT [" + getClass().getName() + ".upload()]");

    try {
        System.setProperty("nomenclator.temp",
                "/home/jcgonzalez/Documentos/PROYECTOS/Nomenclator/Bases de Datos/Version 5 - 2015.07.06/xml/temp/");

        File file = new File(
                "/home/jcgonzalez/Documentos/PROYECTOS/Nomenclator/Bases de Datos/Version 5 - 2015.07.06/xml/AEMPS.zip");
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
                IOUtils.toByteArray(input));

        buzonSucesosController.uploadBuzonSucesos(multipartFile);
        Assert.assertTrue(true);
    } catch (Exception e) {
        Assert.fail(e.toString());
    }
    logger.info("END [" + getClass().getName() + ".upload()]");
}