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:fragment.web.TenantsControllerTest.java

@Test
public void testeditTenantLogo() throws Exception {

    Configuration configuration = configurationService
            .locateConfigurationByName(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    configuration.setValue("src\\test\\resources");
    configurationService.update(configuration);

    Tenant tenant = tenantService.getTenantByParam("id", "1", false);
    TenantLogoForm tenantLogoForm = new TenantLogoForm();

    MultipartFile logo = new MockMultipartFile("poli.jpg", "poli.jpg", "bytes", "poli.jpg".getBytes());
    MultipartFile favicon = new MockMultipartFile("poli.ico", "poli.ico", "bytes", "poli.ico".getBytes());

    tenantLogoForm.setFavicon(favicon);//  www  . ja  va 2s .c  o  m
    tenantLogoForm.setLogo(logo);
    BindingResult result = validate(tenantLogoForm);
    String actualResult = controller.editTenantLogo(tenant.getUuid(), tenantLogoForm, result, map, null);
    Assert.assertEquals("redirect:/portal/home", actualResult);

}

From source file:fragment.web.TenantsControllerTest.java

@Test
public void testeditTenantLogoInvalidFiles() throws Exception {

    Configuration configuration = configurationService
            .locateConfigurationByName(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    configuration.setValue("src\\test\\resources");
    configurationService.update(configuration);

    Tenant tenant = tenantService.getTenantByParam("id", "1", false);
    TenantLogoForm tenantLogoForm = new TenantLogoForm();

    MultipartFile logo = new MockMultipartFile("poli.txt", "poli.txt", "bytes", "poli.txt".getBytes());
    MultipartFile favicon = new MockMultipartFile("poli.ico", "poli.ico", "bytes", "poli.ico".getBytes());

    tenantLogoForm.setFavicon(favicon);/*from   w  w  w.  j  av a2 s.c o  m*/
    tenantLogoForm.setLogo(logo);
    BindingResult result = validate(tenantLogoForm);
    String actualResult = controller.editTenantLogo(tenant.getUuid(), tenantLogoForm, result, map, null);
    Assert.assertEquals("tenants.editcurrentlogo", actualResult);
}

From source file:fragment.web.TenantsControllerTest.java

@Test
public void testeditTenantLogoInvalidUploadPath() throws Exception {

    Configuration configuration = configurationService
            .locateConfigurationByName(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    configuration.setValue("");
    configurationService.update(configuration);

    Tenant tenant = tenantService.getTenantByParam("id", "1", false);
    TenantLogoForm tenantLogoForm = new TenantLogoForm();

    MultipartFile logo = new MockMultipartFile("poli.txt", "poli.txt", "bytes", "poli.txt".getBytes());
    MultipartFile favicon = new MockMultipartFile("poli.ico", "poli.ico", "bytes", "poli.ico".getBytes());

    tenantLogoForm.setFavicon(favicon);//from ww w  . ja v a2 s .co m
    tenantLogoForm.setLogo(logo);
    BindingResult result = validate(tenantLogoForm);
    String actualResult = controller.editTenantLogo(tenant.getUuid(), tenantLogoForm, result, map, null);
    Assert.assertEquals("tenants.editcurrentlogo", actualResult);
}

From source file:fragment.web.AbstractProductsControllerTest.java

@Test
public void testEditProductLogo() throws Exception {

    Product product = productDAO.find(1L);
    ProductLogoForm form = new ProductLogoForm(product);
    MultipartFile logo = new MockMultipartFile("Product.jpeg", "Product.jpeg", "bytes",
            "ProductLogo".getBytes());
    form.setLogo(logo);/*from  ww w .j  a v a 2 s  . c o  m*/
    BindingResult result = validate(form);
    Assert.assertNotNull(result);
    String resultString = productsController.editProductLogo("1", map);
    Assert.assertNotNull(resultString);
}

From source file:fragment.web.AbstractProductsControllerTest.java

@Test
public void testEditProductsLogo() throws Exception {

    Product product = productService.locateProduct("1", false);
    Assert.assertNull(product.getImagePath());
    ProductLogoForm form = new ProductLogoForm(product);
    MultipartFile logo = new MockMultipartFile("Product.jpeg", "Product.jpeg", "bytes",
            "ProductLogo".getBytes());
    form.setLogo(logo);/*from  www  . j  a  v  a  2  s.  c  o  m*/
    BindingResult result = validate(form);
    Assert.assertNotNull(result);
    File currentDirectory = new File(new File(".").getAbsolutePath());
    String currentDirectoryPath = "";
    Configuration rootdir = configurationService
            .locateConfigurationByName(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    try {
        currentDirectoryPath = currentDirectory.getCanonicalPath();
    } catch (IOException e1) {
        e1.printStackTrace();
        Assert.fail();
    }
    rootdir.setValue(currentDirectoryPath);
    configurationService.update(rootdir);
    Assert.assertNull(product.getImagePath());
    productsController.editProductLogo(form, result, request, map);
    product = productService.locateProduct("1", false);
    Assert.assertNotNull(product.getImagePath());
    String productsAbsoluteDir = FilenameUtils.concat(currentDirectoryPath, "products");
    Assert.assertEquals(product.getImagePath().replace("/", "\\"), "products\\1\\Product.jpeg");
    File dir = new File(productsAbsoluteDir);
    try {
        org.apache.commons.io.FileUtils.deleteDirectory(dir);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.cloudifysource.rest.UploadRepoTest.java

public static MultipartFile createNewMultiFile(final File file) throws IOException {
    byte[] content = FileUtils.readFileToByteArray(file);
    final MockMultipartFile mockMultipartFile = new MockMultipartFile(CloudifyConstants.UPLOAD_FILE_PARAM_NAME,
            file.getName(), "text/plain", content);
    return mockMultipartFile;
}

From source file:org.dspace.app.rest.WorkspaceItemRestRepositoryIT.java

@Test
/**/* w w  w . j  a  va  2  s. c  o m*/
 * Test the creation of workspaceitems POSTing to the resource collection endpoint a bibtex file
 *
 * @throws Exception
 */
public void createMultipleWorkspaceItemFromFileTest() throws Exception {
    context.turnOffAuthorisationSystem();

    //** GIVEN **
    //1. A community-collection structure with one parent community with sub-community and two collections.
    parentCommunity = CommunityBuilder.createCommunity(context).withName("Parent Community").build();
    Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity).withName("Sub Community")
            .build();
    Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
    Collection col2 = CollectionBuilder.createCollection(context, child1).withName("Collection 2").build();

    String authToken = getAuthToken(admin.getEmail(), password);

    InputStream bibtex = getClass().getResourceAsStream("bibtex-test.bib");
    final MockMultipartFile bibtexFile = new MockMultipartFile("file", "bibtex-test.bib",
            "application/x-bibtex", bibtex);

    // bulk create workspaceitems in the default collection (col1)
    getClient(authToken).perform(fileUpload("/api/submission/workspaceitems").file(bibtexFile))
            // bulk create should return 200, 201 (created) is better for single resource
            .andExpect(status().isOk())
            .andExpect(
                    jsonPath("$._embedded.workspaceitems[0].sections.traditionalpageone['dc.title'][0].value",
                            is("My Article")))
            .andExpect(jsonPath("$._embedded.workspaceitems[0]._embedded.collection.id",
                    is(col1.getID().toString())))
            .andExpect(
                    jsonPath("$._embedded.workspaceitems[1].sections.traditionalpageone['dc.title'][0].value",
                            is("My Article 2")))
            .andExpect(jsonPath("$._embedded.workspaceitems[1]._embedded.collection.id",
                    is(col1.getID().toString())))
            .andExpect(
                    jsonPath("$._embedded.workspaceitems[2].sections.traditionalpageone['dc.title'][0].value",
                            is("My Article 3")))
            .andExpect(jsonPath("$._embedded.workspaceitems[2]._embedded.collection.id",
                    is(col1.getID().toString())))
            .andExpect(jsonPath("$._embedded.workspaceitems[*]._embedded.upload").doesNotExist());

    // bulk create workspaceitems explicitly in the col2
    getClient(authToken)
            .perform(fileUpload("/api/submission/workspaceitems").file(bibtexFile).param("collection",
                    col2.getID().toString()))
            .andExpect(status().isOk())
            .andExpect(
                    jsonPath("$._embedded.workspaceitems[0].sections.traditionalpageone['dc.title'][0].value",
                            is("My Article")))
            .andExpect(jsonPath("$._embedded.workspaceitems[0]._embedded.collection.id",
                    is(col2.getID().toString())))
            .andExpect(
                    jsonPath("$._embedded.workspaceitems[1].sections.traditionalpageone['dc.title'][0].value",
                            is("My Article 2")))
            .andExpect(jsonPath("$._embedded.workspaceitems[1]._embedded.collection.id",
                    is(col2.getID().toString())))
            .andExpect(
                    jsonPath("$._embedded.workspaceitems[2].sections.traditionalpageone['dc.title'][0].value",
                            is("My Article 3")))
            .andExpect(jsonPath("$._embedded.workspaceitems[2]._embedded.collection.id",
                    is(col2.getID().toString())))
            .andExpect(jsonPath("$._embedded.workspaceitems[*]._embedded.upload").doesNotExist());

    bibtex.close();
}

From source file:org.dspace.app.rest.WorkspaceItemRestRepositoryIT.java

@Test
/**/*from w  w  w  .jav  a2s.c om*/
 * Test the creation of a workspaceitem POSTing to the resource collection endpoint a PDF file. As a single item
 * will be created we expect to have the pdf file stored as a bitstream
 *
 * @throws Exception
 */
public void createWorkspaceItemFromPDFFileTest() throws Exception {
    context.turnOffAuthorisationSystem();

    //** GIVEN **
    //1. A community-collection structure with one parent community with sub-community and two collections.
    parentCommunity = CommunityBuilder.createCommunity(context).withName("Parent Community").build();
    Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity).withName("Sub Community")
            .build();
    Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();

    String authToken = getAuthToken(admin.getEmail(), password);

    InputStream pdf = getClass().getResourceAsStream("simple-article.pdf");
    final MockMultipartFile pdfFile = new MockMultipartFile("file", "/local/path/myfile.pdf", "application/pdf",
            pdf);

    // bulk create a workspaceitem
    getClient(authToken).perform(fileUpload("/api/submission/workspaceitems").file(pdfFile))
            // bulk create should return 200, 201 (created) is better for single resource
            .andExpect(status().isOk())
            //FIXME it will be nice to setup a mock grobid server for end to end testing
            // no metadata for now
            //              .andExpect(jsonPath("$._embedded.workspaceitems[0]._embedded.traditionalpageone['dc.title'][0].value",
            //              is("This is a simple test file")))
            // we can just check that the pdf is stored in the item
            .andExpect(jsonPath(
                    "$._embedded.workspaceitems[0].sections.upload.files[0].metadata['dc.title'][0].value",
                    is("myfile.pdf")))
            .andExpect(jsonPath(
                    "$._embedded.workspaceitems[0].sections.upload.files[0].metadata['dc.source'][0].value",
                    is("/local/path/myfile.pdf")));

    pdf.close();
}

From source file:org.dspace.app.rest.WorkspaceItemRestRepositoryIT.java

@Test
/**//from  www . java 2s.  com
 * Test the upload of files in the upload over section
 *
 * @throws Exception
 */
public void uploadTest() throws Exception {
    context.turnOffAuthorisationSystem();

    //** GIVEN **
    //1. A community-collection structure with one parent community with sub-community and two collections.
    parentCommunity = CommunityBuilder.createCommunity(context).withName("Parent Community").build();
    Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity).withName("Sub Community")
            .build();
    Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();

    String authToken = getAuthToken(admin.getEmail(), password);

    WorkspaceItem witem = WorkspaceItemBuilder.createWorkspaceItem(context, col1)
            .withTitle("Test WorkspaceItem").withIssueDate("2017-10-17").build();

    InputStream pdf = getClass().getResourceAsStream("simple-article.pdf");
    final MockMultipartFile pdfFile = new MockMultipartFile("file", "/local/path/simple-article.pdf",
            "application/pdf", pdf);

    // upload the file in our workspaceitem
    getClient(authToken).perform(fileUpload("/api/submission/workspaceitems/" + witem.getID()).file(pdfFile))
            .andExpect(status().isCreated())
            .andExpect(jsonPath("$.sections.upload.files[0].metadata['dc.title'][0].value",
                    is("simple-article.pdf")))
            .andExpect(jsonPath("$.sections.upload.files[0].metadata['dc.source'][0].value",
                    is("/local/path/simple-article.pdf")));

    // check the file metadata
    getClient().perform(get("/api/submission/workspaceitems/" + witem.getID())).andExpect(status().isOk())
            .andExpect(jsonPath("$.sections.upload.files[0].metadata['dc.title'][0].value",
                    is("simple-article.pdf")))
            .andExpect(jsonPath("$.sections.upload.files[0].metadata['dc.source'][0].value",
                    is("/local/path/simple-article.pdf")));
}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java

@Test
@Description("Tests the upload of an artifact binary. The upload is executed and the content checked in the repository for completeness.")
public void uploadArtifact() throws Exception {
    final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();

    // create test file
    final byte random[] = randomBytes(5 * 1024);
    final String md5sum = HashGeneratorUtils.generateMD5(random);
    final String sha1sum = HashGeneratorUtils.generateSHA1(random);
    final MockMultipartFile file = new MockMultipartFile("file", "origFilename", null, random);

    // upload/* ww w.ja v  a  2 s  .  c  om*/
    final MvcResult mvcResult = mvc
            .perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
                    .accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.hashes.md5", equalTo(md5sum)))
            .andExpect(jsonPath("$.hashes.sha1", equalTo(sha1sum)))
            .andExpect(jsonPath("$.size", equalTo(random.length)))
            .andExpect(jsonPath("$.providedFilename", equalTo("origFilename"))).andReturn();

    // check rest of response compared to DB
    final MgmtArtifact artResult = ResourceUtility
            .convertArtifactResponse(mvcResult.getResponse().getContentAsString());
    final Long artId = softwareModuleManagement.get(sm.getId()).get().getArtifacts().get(0).getId();
    assertThat(artResult.getArtifactId()).as("Wrong artifact id").isEqualTo(artId);
    assertThat(JsonPath.compile("$._links.self.href").read(mvcResult.getResponse().getContentAsString())
            .toString()).as("Link contains no self url").isEqualTo(
                    "http://localhost/rest/v1/softwaremodules/" + sm.getId() + "/artifacts/" + artId);
    assertThat(JsonPath.compile("$._links.download.href").read(mvcResult.getResponse().getContentAsString())
            .toString()).as("response contains no download url ")
                    .isEqualTo("http://localhost/rest/v1/softwaremodules/" + sm.getId() + "/artifacts/" + artId
                            + "/download");

    assertArtifact(sm, random);
}