Search in sources :

Example 6 with MultiPartRequest

use of org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest in project alfresco-remote-api by Alfresco.

the class RenditionsTest method testCreateRendition.

/**
 * Tests create rendition.
 * <p>POST:</p>
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>/renditions}
 */
@Test
public void testCreateRendition() throws Exception {
    setRequestContext(networkN1.getId(), userOneN1.getId(), null);
    // Create a folder within the site document's library
    String folderName = "folder" + System.currentTimeMillis();
    String folder_Id = addToDocumentLibrary(userOneN1Site, folderName, TYPE_CM_FOLDER, userOneN1.getId());
    // Create multipart request
    String fileName = "quick.pdf";
    File file = getResourceFile(fileName);
    MultiPartBuilder multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    MultiPartRequest reqBody = multiPartBuilder.build();
    // Upload quick.pdf file into 'folder'
    HttpResponse response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    Document document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    String contentNodeId = document.getId();
    // pause briefly
    Thread.sleep(DELAY_IN_MS);
    // Get rendition (not created yet) information for node
    response = getSingle(getNodeRenditionsUrl(contentNodeId), "imgpreview", 200);
    Rendition rendition = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Rendition.class);
    assertNotNull(rendition);
    assertEquals(RenditionStatus.NOT_CREATED, rendition.getStatus());
    // Try to download non-existent rendition (and no placeholder)
    Map<String, String> params = new HashMap<>();
    params.put("placeholder", "false");
    getSingle(getNodeRenditionsUrl(contentNodeId), ("doclib/content"), params, 404);
    // Download placeholder instead
    params = new HashMap<>();
    params.put("placeholder", "true");
    response = getSingle(getNodeRenditionsUrl(contentNodeId), ("doclib/content"), params, 200);
    assertNotNull(response.getResponseAsBytes());
    // Create and get 'imgpreview' rendition
    rendition = createAndGetRendition(contentNodeId, "imgpreview");
    assertNotNull(rendition);
    assertEquals(RenditionStatus.CREATED, rendition.getStatus());
    ContentInfo contentInfo = rendition.getContent();
    assertNotNull(contentInfo);
    assertEquals(MimetypeMap.MIMETYPE_IMAGE_JPEG, contentInfo.getMimeType());
    assertEquals("JPEG Image", contentInfo.getMimeTypeName());
    assertNotNull(contentInfo.getEncoding());
    assertTrue(contentInfo.getSizeInBytes() > 0);
    // Create 'doclib' rendition request
    Rendition renditionRequest = new Rendition().setId("doclib");
    // Test only if OpenOffice is available
    if (isOpenOfficeAvailable()) {
        // Create a node without any content
        String emptyContentNodeId = addToDocumentLibrary(userOneN1Site, "emptyDoc.txt", TYPE_CM_CONTENT, userOneN1.getId());
        post(getNodeRenditionsUrl(emptyContentNodeId), toJsonAsString(renditionRequest), 202);
        // Rendition for binary content
        String content = "The quick brown fox jumps over the lazy dog.";
        file = TempFileProvider.createTempFile(new ByteArrayInputStream(content.getBytes()), getClass().getSimpleName(), ".bin");
        multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData("binaryFileName", file));
        reqBody = multiPartBuilder.build();
        response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
        Document binaryDocument = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
        post(getNodeRenditionsUrl(binaryDocument.getId()), toJsonAsString(renditionRequest), 202);
    }
    // 
    // -ve Tests
    // 
    // The rendition requested already exists
    response = post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(new Rendition().setId("imgpreview")), 409);
    ExpectedErrorResponse errorResponse = RestApiUtil.parseErrorResponse(response.getJsonResponse());
    assertNotNull(errorResponse);
    assertNotNull(errorResponse.getErrorKey());
    assertNotNull(errorResponse.getBriefSummary());
    assertNotNull(errorResponse.getStackTrace());
    assertNotNull(errorResponse.getDescriptionURL());
    assertEquals(409, errorResponse.getStatusCode());
    // nodeId in the path parameter does not represent a file
    post(getNodeRenditionsUrl(folder_Id), toJsonAsString(renditionRequest), 400);
    // nodeId in the path parameter does not exist
    response = post(getNodeRenditionsUrl(UUID.randomUUID().toString()), toJsonAsString(renditionRequest), 404);
    // EntityNotFoundException
    errorResponse = RestApiUtil.parseErrorResponse(response.getJsonResponse());
    assertNotNull(errorResponse);
    assertNotNull(errorResponse.getErrorKey());
    assertNotNull(errorResponse.getBriefSummary());
    assertNotNull(errorResponse.getStackTrace());
    assertNotNull(errorResponse.getDescriptionURL());
    assertEquals(404, errorResponse.getStatusCode());
    // renditionId is not registered
    final String randomRenditionId = "renditionId" + System.currentTimeMillis();
    post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(new Rendition().setId(randomRenditionId)), 404);
    // renditionId is null
    post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(new Rendition().setId(null)), 400);
    // renditionId is empty
    post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(new Rendition().setId("")), 400);
    // -ve test - we do not currently accept multiple create entities
    List<Rendition> multipleRenditionRequest = new ArrayList<>(2);
    multipleRenditionRequest.add(new Rendition().setId("doclib"));
    multipleRenditionRequest.add(new Rendition().setId("imgpreview"));
    post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(multipleRenditionRequest), 400);
    ThumbnailService thumbnailService = applicationContext.getBean("thumbnailService", ThumbnailService.class);
    // Disable thumbnail generation
    thumbnailService.setThumbnailsEnabled(false);
    try {
        // Create multipart request
        String txtFileName = "quick-1.txt";
        File txtFile = getResourceFile(fileName);
        reqBody = MultiPartBuilder.create().setFileData(new FileData(txtFileName, txtFile)).build();
        // Upload quick-1.txt file into 'folder'
        response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
        Document txtDocument = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
        // Thumbnail generation has been disabled
        response = post(getNodeRenditionsUrl(txtDocument.getId()), toJsonAsString(renditionRequest), 501);
        errorResponse = RestApiUtil.parseErrorResponse(response.getJsonResponse());
        assertNotNull(errorResponse);
        assertNotNull(errorResponse.getErrorKey());
        assertNotNull(errorResponse.getBriefSummary());
        assertNotNull(errorResponse.getStackTrace());
        assertNotNull(errorResponse.getDescriptionURL());
        assertEquals(501, errorResponse.getStatusCode());
    } finally {
        thumbnailService.setThumbnailsEnabled(true);
    }
}
Also used : ExpectedErrorResponse(org.alfresco.rest.api.tests.client.PublicApiClient.ExpectedErrorResponse) ThumbnailService(org.alfresco.service.cmr.thumbnail.ThumbnailService) HashMap(java.util.HashMap) Rendition(org.alfresco.rest.api.tests.client.data.Rendition) ArrayList(java.util.ArrayList) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) MultiPartRequest(org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest) RestApiUtil.toJsonAsString(org.alfresco.rest.api.tests.util.RestApiUtil.toJsonAsString) Document(org.alfresco.rest.api.tests.client.data.Document) MultiPartBuilder(org.alfresco.rest.api.tests.util.MultiPartBuilder) ContentInfo(org.alfresco.rest.api.tests.client.data.ContentInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) File(java.io.File) FileData(org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData) Test(org.junit.Test)

Example 7 with MultiPartRequest

use of org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest in project alfresco-remote-api by Alfresco.

the class RenditionsTest method testCreateRenditionOnUpload.

/**
 * Tests create rendition when on upload/create of a file
 *
 * <p>POST:</p>
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>/children}
 */
@Test
public void testCreateRenditionOnUpload() throws Exception {
    String userId = userOneN1.getId();
    setRequestContext(networkN1.getId(), userOneN1.getId(), null);
    // Create a folder within the site document's library
    String folderName = "folder" + System.currentTimeMillis();
    String folder_Id = addToDocumentLibrary(userOneN1Site, folderName, TYPE_CM_FOLDER, userId);
    // Create multipart request - pdf file
    String renditionName = "doclib";
    String fileName = "quick.pdf";
    File file = getResourceFile(fileName);
    MultiPartRequest reqBody = MultiPartBuilder.create().setFileData(new FileData(fileName, file)).setRenditions(Collections.singletonList(renditionName)).build();
    // Upload quick.pdf file into 'folder' - including request to create 'doclib' thumbnail
    HttpResponse response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    Document document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    String contentNodeId = document.getId();
    // wait and check that rendition is created ...
    Rendition rendition = waitAndGetRendition(contentNodeId, renditionName);
    assertNotNull(rendition);
    assertEquals(RenditionStatus.CREATED, rendition.getStatus());
    Map<String, String> params = new HashMap<>();
    params.put("placeholder", "false");
    response = getSingle(getNodeRenditionsUrl(contentNodeId), ("doclib/content"), params, 200);
    assertNotNull(response.getResponseAsBytes());
    if (isOpenOfficeAvailable()) {
        // Create multipart request - Word doc file
        renditionName = "doclib";
        fileName = "farmers_markets_list_2003.doc";
        file = getResourceFile(fileName);
        reqBody = MultiPartBuilder.create().setFileData(new FileData(fileName, file)).setRenditions(Collections.singletonList(renditionName)).build();
        // Upload file into 'folder' - including request to create 'doclib' thumbnail
        response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
        document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
        contentNodeId = document.getId();
        // wait and check that rendition is created ...
        rendition = waitAndGetRendition(contentNodeId, renditionName);
        assertNotNull(rendition);
        assertEquals(RenditionStatus.CREATED, rendition.getStatus());
    }
    /* RA-834: commented-out since not currently applicable for empty file
        Document d1 = new Document();
        d1.setName("d1.txt");
        d1.setNodeType("cm:content");
        ContentInfo ci = new ContentInfo();
        ci.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        d1.setContent(ci);

        // create empty file including request to generate a thumbnail
        renditionName = "doclib";
        response = post(getNodeChildrenUrl(folder_Id), userId, toJsonAsStringNonNull(d1), "?renditions="+renditionName, 201);
        Document documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
        String d1Id = documentResp.getId();

        // wait and check that rendition is created ...
        rendition = waitAndGetRendition(userId, d1Id, renditionName);
        assertNotNull(rendition);
        assertEquals(RenditionStatus.CREATED, rendition.getStatus());
        */
    /*
         * Per RA-1052, the failure of the async request to create a rendition
         * should NOT fail the upload.
         */
    // Currently we do not support multiple rendition requests on create
    reqBody = MultiPartBuilder.create().setFileData(new FileData(fileName, file)).setAutoRename(true).setRenditions(Arrays.asList(new String[] { "doclib,imgpreview" })).build();
    post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 400);
    // Unknown rendition
    reqBody = MultiPartBuilder.create().setFileData(new FileData(fileName, file)).setAutoRename(true).setRenditions(Arrays.asList(new String[] { "unknown" })).build();
    post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    // ThumbnailService is disabled
    ThumbnailService thumbnailService = applicationContext.getBean("thumbnailService", ThumbnailService.class);
    thumbnailService.setThumbnailsEnabled(false);
    try {
        // Create multipart request
        String txtFileName = "quick-1.txt";
        File txtFile = getResourceFile(fileName);
        reqBody = MultiPartBuilder.create().setFileData(new FileData(txtFileName, txtFile)).setRenditions(Arrays.asList(new String[] { "doclib" })).build();
        post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    } finally {
        thumbnailService.setThumbnailsEnabled(true);
    }
}
Also used : ThumbnailService(org.alfresco.service.cmr.thumbnail.ThumbnailService) HashMap(java.util.HashMap) Rendition(org.alfresco.rest.api.tests.client.data.Rendition) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) MultiPartRequest(org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest) RestApiUtil.toJsonAsString(org.alfresco.rest.api.tests.util.RestApiUtil.toJsonAsString) Document(org.alfresco.rest.api.tests.client.data.Document) File(java.io.File) FileData(org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData) Test(org.junit.Test)

Example 8 with MultiPartRequest

use of org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest in project alfresco-remote-api by Alfresco.

the class RenditionsTest method testGetNodeRendition.

/**
 * Tests get node rendition.
 * <p>GET:</p>
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>/renditions/<renditionId>}
 */
@Test
public void testGetNodeRendition() throws Exception {
    setRequestContext(networkN1.getId(), userOneN1.getId(), null);
    // Create a folder within the site document's library
    String folderName = "folder" + System.currentTimeMillis();
    String folder_Id = addToDocumentLibrary(userOneN1Site, folderName, TYPE_CM_FOLDER, userOneN1.getId());
    // Create multipart request
    String fileName = "quick.pdf";
    File file = getResourceFile(fileName);
    MultiPartBuilder multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    MultiPartRequest reqBody = multiPartBuilder.build();
    // Upload quick.pdf file into 'folder'
    HttpResponse response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    Document document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    String contentNodeId = document.getId();
    // pause briefly
    Thread.sleep(DELAY_IN_MS);
    // Get rendition (not created yet) information for node
    response = getSingle(getNodeRenditionsUrl(contentNodeId), "doclib", 200);
    Rendition rendition = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Rendition.class);
    assertNotNull(rendition);
    assertEquals(RenditionStatus.NOT_CREATED, rendition.getStatus());
    ContentInfo contentInfo = rendition.getContent();
    assertNotNull(contentInfo);
    assertEquals(MimetypeMap.MIMETYPE_IMAGE_PNG, contentInfo.getMimeType());
    assertEquals("PNG Image", contentInfo.getMimeTypeName());
    assertNull("Shouldn't have returned the encoding, as the rendition hasn't been created yet.", contentInfo.getEncoding());
    assertNull("Shouldn't have returned the size, as the rendition hasn't been created yet.", contentInfo.getSizeInBytes());
    // Create and get 'doclib' rendition
    rendition = createAndGetRendition(contentNodeId, "doclib");
    assertNotNull(rendition);
    assertEquals(RenditionStatus.CREATED, rendition.getStatus());
    contentInfo = rendition.getContent();
    assertNotNull(contentInfo);
    assertEquals(MimetypeMap.MIMETYPE_IMAGE_PNG, contentInfo.getMimeType());
    assertEquals("PNG Image", contentInfo.getMimeTypeName());
    assertNotNull(contentInfo.getEncoding());
    assertTrue(contentInfo.getSizeInBytes() > 0);
    // nodeId in the path parameter does not represent a file
    getSingle(getNodeRenditionsUrl(folder_Id), "doclib", 400);
    // nodeId in the path parameter does not exist
    getSingle(getNodeRenditionsUrl(UUID.randomUUID().toString()), "doclib", 404);
    // renditionId in the path parameter is not registered/available
    getSingle(getNodeRenditionsUrl(contentNodeId), ("renditionId" + System.currentTimeMillis()), 404);
    // Create a node without any content. Test only if OpenOffice is available
    if (isOpenOfficeAvailable()) {
        String emptyContentNodeId = addToDocumentLibrary(userOneN1Site, "emptyDoc.txt", TYPE_CM_CONTENT, userOneN1.getId());
        getSingle(getNodeRenditionsUrl(emptyContentNodeId), "doclib", 200);
    }
    // Create multipart request
    String jpgFileName = "quick.jpg";
    File jpgFile = getResourceFile(fileName);
    reqBody = MultiPartBuilder.create().setFileData(new FileData(jpgFileName, jpgFile)).build();
    // Upload quick.jpg file into 'folder'
    response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    Document jpgImage = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    String jpgImageNodeId = jpgImage.getId();
    // List all available renditions (includes those that have been created and those that are yet to be created)
    response = getAll(getNodeRenditionsUrl(jpgImageNodeId), getPaging(0, 50), 200);
    List<Rendition> renditions = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), Rendition.class);
    // Check there is no pdf rendition is available for the jpg file
    Rendition pdf = getRendition(renditions, "pdf");
    assertNull(pdf);
    // The renditionId (pdf) is registered but it is not applicable for the node's mimeType
    getSingle(getNodeRenditionsUrl(jpgImageNodeId), "pdf", 404);
}
Also used : MultiPartBuilder(org.alfresco.rest.api.tests.util.MultiPartBuilder) ContentInfo(org.alfresco.rest.api.tests.client.data.ContentInfo) Rendition(org.alfresco.rest.api.tests.client.data.Rendition) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) MultiPartRequest(org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest) RestApiUtil.toJsonAsString(org.alfresco.rest.api.tests.util.RestApiUtil.toJsonAsString) Document(org.alfresco.rest.api.tests.client.data.Document) File(java.io.File) FileData(org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData) Test(org.junit.Test)

Example 9 with MultiPartRequest

use of org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest in project alfresco-remote-api by Alfresco.

the class NodeApiTest method testDownloadFileContent.

/**
 * Tests download of file/content.
 * <p>GET:</p>
 * {@literal <host>:<port>/alfresco/api/-default-/public/alfresco/versions/1/nodes/<nodeId>/content}
 */
@Test
public void testDownloadFileContent() throws Exception {
    setRequestContext(user1);
    // 
    // Test plain text
    // 
    String fileName = "quick-1.txt";
    File file = getResourceFile(fileName);
    MultiPartBuilder multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    MultiPartRequest reqBody = multiPartBuilder.build();
    // Upload text content
    HttpResponse response = post(getNodeChildrenUrl(Nodes.PATH_MY), reqBody.getBody(), null, reqBody.getContentType(), 201);
    Document document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    String contentNodeId = document.getId();
    // Check the upload response
    assertEquals(fileName, document.getName());
    ContentInfo contentInfo = document.getContent();
    assertNotNull(contentInfo);
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    // Download text content - by default with Content-Disposition header
    response = getSingle(NodesEntityResource.class, contentNodeId + "/content", null, 200);
    String textContent = response.getResponse();
    assertEquals("The quick brown fox jumps over the lazy dog", textContent);
    Map<String, String> responseHeaders = response.getHeaders();
    assertNotNull(responseHeaders);
    assertEquals("attachment; filename=\"quick-1.txt\"; filename*=UTF-8''quick-1.txt", responseHeaders.get("Content-Disposition"));
    String cacheControl = responseHeaders.get("Cache-Control");
    assertNotNull(cacheControl);
    assertTrue(cacheControl.contains("must-revalidate"));
    assertTrue(cacheControl.contains("max-age=0"));
    assertNotNull(responseHeaders.get("Expires"));
    String lastModifiedHeader = responseHeaders.get(LAST_MODIFIED_HEADER);
    assertNotNull(lastModifiedHeader);
    Map<String, String> headers = Collections.singletonMap(IF_MODIFIED_SINCE_HEADER, lastModifiedHeader);
    // Test 304 response
    getSingle(getNodeContentUrl(contentNodeId), null, null, headers, 304);
    // Update the content to change the node's modified date
    Document docUpdate = new Document();
    docUpdate.setProperties(Collections.singletonMap("cm:description", (Object) "desc updated!"));
    // Wait a second then update, as the dates will be rounded to
    // ignore millisecond when checking for If-Modified-Since
    Thread.sleep(1000L);
    response = put(URL_NODES, contentNodeId, toJsonAsStringNonNull(docUpdate), null, 200);
    Document updatedDocument = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals(contentNodeId, updatedDocument.getId());
    // The requested "If-Modified-Since" date is older than node's modified date
    response = getSingle(getNodeContentUrl(contentNodeId), null, null, headers, 200);
    responseHeaders = response.getHeaders();
    assertNotNull(responseHeaders);
    assertNotNull(responseHeaders.get("Cache-Control"));
    assertNotNull(responseHeaders.get("Expires"));
    String newLastModifiedHeader = responseHeaders.get(LAST_MODIFIED_HEADER);
    assertNotNull(newLastModifiedHeader);
    assertNotEquals(lastModifiedHeader, newLastModifiedHeader);
    // 
    // Test binary (eg. PDF)
    // 
    fileName = "quick.pdf";
    file = getResourceFile(fileName);
    byte[] originalBytes = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
    multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    reqBody = multiPartBuilder.build();
    // Upload binary content
    response = post(getNodeChildrenUrl(Nodes.PATH_MY), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    contentNodeId = document.getId();
    // Check the upload response
    assertEquals(fileName, document.getName());
    contentInfo = document.getContent();
    assertNotNull(contentInfo);
    assertEquals(MimetypeMap.MIMETYPE_PDF, contentInfo.getMimeType());
    // Download binary content (as bytes) - without Content-Disposition header (attachment=false)
    Map<String, String> params = new LinkedHashMap<>();
    params.put("attachment", "false");
    response = getSingle(NodesEntityResource.class, contentNodeId + "/content", params, 200);
    byte[] bytes = response.getResponseAsBytes();
    assertArrayEquals(originalBytes, bytes);
    responseHeaders = response.getHeaders();
    assertNotNull(responseHeaders);
    assertNull(responseHeaders.get("Content-Disposition"));
    assertNotNull(responseHeaders.get("Cache-Control"));
    assertNotNull(responseHeaders.get("Expires"));
    lastModifiedHeader = responseHeaders.get(LAST_MODIFIED_HEADER);
    assertNotNull(lastModifiedHeader);
    headers = Collections.singletonMap(IF_MODIFIED_SINCE_HEADER, lastModifiedHeader);
    // Test 304 response
    getSingle(getNodeContentUrl(contentNodeId), null, null, headers, 304);
}
Also used : HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) MultiPartRequest(org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest) NodesEntityResource(org.alfresco.rest.api.nodes.NodesEntityResource) Document(org.alfresco.rest.api.tests.client.data.Document) LinkedHashMap(java.util.LinkedHashMap) MultiPartBuilder(org.alfresco.rest.api.tests.util.MultiPartBuilder) ContentInfo(org.alfresco.rest.api.tests.client.data.ContentInfo) JSONObject(org.json.simple.JSONObject) File(java.io.File) FileData(org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData) Test(org.junit.Test) AbstractSingleNetworkSiteTest(org.alfresco.rest.AbstractSingleNetworkSiteTest)

Example 10 with MultiPartRequest

use of org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest in project alfresco-remote-api by Alfresco.

the class NodeApiTest method testUploadToSite.

/**
 * Tests Multipart upload to a Site.
 * <p>POST:</p>
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>/children}
 */
@Test
public void testUploadToSite() throws Exception {
    setRequestContext(user1);
    final String fileName = "quick-1.txt";
    final File file = getResourceFile(fileName);
    String folderA = "folder" + RUNID + "_A";
    String folderA_id = createFolder(tDocLibNodeId, folderA).getId();
    Paging paging = getPaging(0, Integer.MAX_VALUE);
    HttpResponse response = getAll(getNodeChildrenUrl(folderA_id), paging, 200);
    PublicApiClient.ExpectedPaging pagingResult = parsePaging(response.getJsonResponse());
    assertNotNull(paging);
    final int numOfNodes = pagingResult.getCount();
    MultiPartBuilder multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    MultiPartRequest reqBody = multiPartBuilder.build();
    // Try to upload
    response = post(getNodeChildrenUrl(folderA_id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    Document document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    // Check the upload response
    assertEquals(fileName, document.getName());
    ContentInfo contentInfo = document.getContent();
    assertNotNull(contentInfo);
    // As the client didn't set the mimeType, the API must guess it.
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    // Retrieve the uploaded file
    response = getSingle(NodesEntityResource.class, document.getId(), null, 200);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals(fileName, document.getName());
    contentInfo = document.getContent();
    assertNotNull(contentInfo);
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    // Check 'get children' is confirming the upload
    response = getAll(getNodeChildrenUrl(folderA_id), paging, 200);
    pagingResult = parsePaging(response.getJsonResponse());
    assertNotNull(paging);
    assertEquals(numOfNodes + 1, pagingResult.getCount().intValue());
    // Upload the same file again to check the name conflicts handling
    post(getNodeChildrenUrl(folderA_id), reqBody.getBody(), null, reqBody.getContentType(), 409);
    response = getAll(getNodeChildrenUrl(folderA_id), paging, 200);
    pagingResult = parsePaging(response.getJsonResponse());
    assertNotNull(paging);
    assertEquals(numOfNodes + 1, pagingResult.getCount().intValue());
    setRequestContext(user2);
    final String fileName2 = "quick-2.txt";
    final File file2 = getResourceFile(fileName2);
    reqBody = MultiPartBuilder.create().setFileData(new FileData(fileName2, file2)).build();
    // user2 tries to upload a new file into the folderA of user1
    post(getNodeChildrenUrl(folderA_id), reqBody.getBody(), null, reqBody.getContentType(), 403);
    setRequestContext(user1);
    // Test upload with properties
    response = post(getNodeChildrenUrl(folderA_id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    // Check the upload response
    assertEquals(fileName2, document.getName());
    contentInfo = document.getContent();
    assertNotNull(contentInfo);
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    assertNotNull(document.getProperties());
    assertNull(document.getProperties().get("cm:title"));
    assertNull(document.getProperties().get("cm:description"));
    // upload a file with properties. Also, set autoRename=true
    Map<String, String> props = new HashMap<>(2);
    props.put("cm:title", "test title");
    props.put("cm:description", "test description");
    reqBody = MultiPartBuilder.create().setFileData(new FileData(fileName2, file2)).setAutoRename(true).setProperties(props).build();
    response = post(getNodeChildrenUrl(folderA_id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    // Check the upload response
    // "quick-2-1.txt" => fileName2 + autoRename
    assertEquals("quick-2-1.txt", document.getName());
    contentInfo = document.getContent();
    assertNotNull(contentInfo);
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    assertNotNull(document.getProperties());
    assertEquals("test title", document.getProperties().get("cm:title"));
    assertEquals("test description", document.getProperties().get("cm:description"));
    // Test unknown property name
    props = new HashMap<>(1);
    props.put("unknownPrefix" + System.currentTimeMillis() + ":description", "test description");
    reqBody = MultiPartBuilder.create().setFileData(new FileData(fileName2, file2)).setAutoRename(true).setProperties(props).build();
    // Prop prefix is unknown
    post(getNodeChildrenUrl(folderA_id), reqBody.getBody(), null, reqBody.getContentType(), 400);
    // Test relativePath multi-part field.
    // Any folders in the relativePath that do not exist, are created before the content is created.
    multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file)).setRelativePath("X/Y/Z");
    reqBody = multiPartBuilder.build();
    response = post(getNodeChildrenUrl(folderA_id), reqBody.getBody(), "?include=path", reqBody.getContentType(), 201);
    document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
    // Check the upload response
    assertEquals(fileName, document.getName());
    contentInfo = document.getContent();
    assertNotNull(contentInfo);
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    // Check the uploaded file parent folders
    PathInfo pathInfo = document.getPath();
    assertNotNull(pathInfo);
    List<ElementInfo> elementInfos = pathInfo.getElements();
    assertNotNull(elementInfos);
    // /Company Home/Sites/RandomSite<timestamp>/documentLibrary/folder<timestamp>_A/X/Y/Z
    assertEquals(8, elementInfos.size());
    assertEquals(document.getParentId(), elementInfos.get(7).getId());
    assertEquals("Z", elementInfos.get(7).getName());
    assertEquals("Y", elementInfos.get(6).getName());
    assertEquals("X", elementInfos.get(5).getName());
    assertEquals(folderA, elementInfos.get(4).getName());
    // Try to create a folder with the same name as the document within the 'Z' folder.
    reqBody = MultiPartBuilder.copy(multiPartBuilder).setRelativePath("X/Y/Z/" + document.getName()).build();
    post(getNodeChildrenUrl(folderA_id), reqBody.getBody(), null, reqBody.getContentType(), 409);
    // Test the same functionality as "mkdir -p x/y/z" which the folders should be created
    // as needed but no errors thrown if the path or any part of the path already exists.
    // NOTE: white spaces, leading and trailing "/" are ignored.
    reqBody = MultiPartBuilder.copy(multiPartBuilder).setRelativePath("/X/ Y/Z /CoolFolder/").build();
    response = post(getNodeChildrenUrl(folderA_id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    // Check the upload response
    assertEquals(fileName, document.getName());
    contentInfo = document.getContent();
    assertNotNull(contentInfo);
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    // Retrieve the uploaded file parent folder
    response = getSingle(NodesEntityResource.class, document.getParentId(), null, 200);
    Folder coolFolder = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Folder.class);
    assertEquals(document.getParentId(), coolFolder.getId());
    assertEquals("CoolFolder", coolFolder.getName());
    // Try to upload quick-1.txt within coolFolder and set the relativePath to a blank string.
    reqBody = MultiPartBuilder.copy(multiPartBuilder).setRelativePath(// blank
    "  ").build();
    // 409 -> as the blank string is ignored and quick-1.txt already exists in the coolFolder
    post(getNodeChildrenUrl(coolFolder.getId()), reqBody.getBody(), null, reqBody.getContentType(), 409);
    setRequestContext(user2);
    // user2 tries to upload the same file by creating sub-folders in the folderA of user1
    reqBody = MultiPartBuilder.copy(multiPartBuilder).setRelativePath("userTwoFolder1/userTwoFolder2").build();
    post(getNodeChildrenUrl(folderA_id), reqBody.getBody(), null, reqBody.getContentType(), 403);
    // -ve test: integrity error
    setRequestContext(user1);
    reqBody = MultiPartBuilder.create().setFileData(new FileData("invalid:name", file)).build();
    // 422 -> invalid name (includes a ':' in this example)
    post(getNodeChildrenUrl(coolFolder.getId()), reqBody.getBody(), null, reqBody.getContentType(), 422);
}
Also used : ExpectedPaging(org.alfresco.rest.api.tests.client.PublicApiClient.ExpectedPaging) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ElementInfo(org.alfresco.rest.api.tests.client.data.PathInfo.ElementInfo) RestApiUtil.parsePaging(org.alfresco.rest.api.tests.util.RestApiUtil.parsePaging) Paging(org.alfresco.rest.api.tests.client.PublicApiClient.Paging) ExpectedPaging(org.alfresco.rest.api.tests.client.PublicApiClient.ExpectedPaging) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) MultiPartRequest(org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest) NodesEntityResource(org.alfresco.rest.api.nodes.NodesEntityResource) Document(org.alfresco.rest.api.tests.client.data.Document) Folder(org.alfresco.rest.api.tests.client.data.Folder) MultiPartBuilder(org.alfresco.rest.api.tests.util.MultiPartBuilder) ContentInfo(org.alfresco.rest.api.tests.client.data.ContentInfo) PublicApiClient(org.alfresco.rest.api.tests.client.PublicApiClient) PathInfo(org.alfresco.rest.api.tests.client.data.PathInfo) File(java.io.File) FileData(org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData) Test(org.junit.Test) AbstractSingleNetworkSiteTest(org.alfresco.rest.AbstractSingleNetworkSiteTest)

Aggregations

File (java.io.File)13 FileData (org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData)13 MultiPartRequest (org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest)13 Test (org.junit.Test)13 HttpResponse (org.alfresco.rest.api.tests.client.HttpResponse)11 Document (org.alfresco.rest.api.tests.client.data.Document)11 MultiPartBuilder (org.alfresco.rest.api.tests.util.MultiPartBuilder)9 ContentInfo (org.alfresco.rest.api.tests.client.data.ContentInfo)8 HashMap (java.util.HashMap)6 Rendition (org.alfresco.rest.api.tests.client.data.Rendition)6 RestApiUtil.toJsonAsString (org.alfresco.rest.api.tests.util.RestApiUtil.toJsonAsString)6 AbstractSingleNetworkSiteTest (org.alfresco.rest.AbstractSingleNetworkSiteTest)5 NodesEntityResource (org.alfresco.rest.api.nodes.NodesEntityResource)5 ExpectedPaging (org.alfresco.rest.api.tests.client.PublicApiClient.ExpectedPaging)3 Paging (org.alfresco.rest.api.tests.client.PublicApiClient.Paging)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 PrintWriter (java.io.PrintWriter)2 ArrayList (java.util.ArrayList)2 LinkedHashMap (java.util.LinkedHashMap)2 PublicApiClient (org.alfresco.rest.api.tests.client.PublicApiClient)2