Search in sources :

Example 21 with Document

use of org.alfresco.rest.api.tests.client.data.Document in project alfresco-remote-api by Alfresco.

the class QueriesNodesApiTest method testLiveSearchNodes_SortPage.

@Test
public void testLiveSearchNodes_SortPage() throws Exception {
    setRequestContext(user1);
    int f1Count = 5;
    List<String> f1NodeIds = new ArrayList<>(f1Count);
    int f2Count = 3;
    List<String> f2NodeIds = new ArrayList<>(f2Count);
    int totalCount = f1Count + f2Count;
    List<String> allIds = new ArrayList<>(totalCount);
    String testTerm = "def456sortpage";
    try {
        // As user 1 ...
        Paging paging = getPaging(0, 100);
        Map<String, String> params = new HashMap<>(1);
        params.put(Queries.PARAM_TERM, testTerm);
        String myFolderNodeId = getMyNodeId();
        String f1Id = createFolder(myFolderNodeId, "folder sort 1").getId();
        String f2Id = createFolder(myFolderNodeId, "folder sort 2").getId();
        String name = "name";
        Map<String, String> idNameMap = new HashMap<>();
        int nameIdx = f1Count;
        for (int i = 1; i <= f1Count; i++) {
            // create doc - in folder 1
            String contentText = "f1 " + testTerm + " test document " + user1 + " document " + i;
            String num = String.format("%05d", nameIdx);
            String docName = name + num + name + ".txt";
            Document doc = createTextFile(f1Id, docName, contentText, "UTF-8", null);
            f1NodeIds.add(doc.getId());
            idNameMap.put(doc.getId(), docName);
            nameIdx--;
        }
        nameIdx = f2Count;
        for (int i = 1; i <= f2Count; i++) {
            // create doc - in folder 2
            String contentText = "f2 " + testTerm + " test document";
            String num = String.format("%05d", nameIdx);
            String docName = name + num + name + ".txt";
            Document doc = createTextFile(f2Id, docName, contentText, "UTF-8", null);
            f2NodeIds.add(doc.getId());
            idNameMap.put(doc.getId(), docName);
            nameIdx--;
        }
        List<String> idsSortedByNameAsc = new ArrayList<>(sortByValue(idNameMap).keySet());
        List<String> idsSortedByNameDescCreatedAtAsc = new ArrayList<>(totalCount);
        for (int i = 0; i < totalCount; i++) {
            if (i < f1Count) {
                idsSortedByNameDescCreatedAtAsc.add(f1NodeIds.get(i));
            }
            if (i < f2Count) {
                idsSortedByNameDescCreatedAtAsc.add(f2NodeIds.get(i));
            }
        }
        allIds.addAll(idNameMap.keySet());
        // test sort order
        // default sort order (modifiedAt desc)
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, null, paging, 200, false, true, allIds);
        // sort order - modifiedAt asc
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, "modifiedAt asc", paging, 200, false, true, allIds);
        // sort order - modifiedAt desc
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, "modifiedAt desc", paging, 200, true, true, allIds);
        // sort order - createdAt asc
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, "createdAt asc", paging, 200, true, true, allIds);
        // sort order - createdAt desc
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, "createdAt desc", paging, 200, false, true, allIds);
        // sort order - name asc
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, "name asc", paging, 200, true, true, idsSortedByNameAsc);
        // sort order - name desc
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, "name desc", paging, 200, false, true, idsSortedByNameAsc);
        // sort order - name desc, createdAt asc
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, "name desc, createdAt asc", paging, 200, false, true, idsSortedByNameDescCreatedAtAsc);
        // sort order - name asc, createdAt asc
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, "name asc, createdAt desc", paging, 200, true, true, idsSortedByNameDescCreatedAtAsc);
        // basic paging test
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, null, getPaging(0, 100), 200, false, true, allIds);
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, null, getPaging(0, f1Count), 200, false, true, f1NodeIds);
        checkApiCall(null, DEAFULT_QUERY, testTerm, null, null, null, null, getPaging(f1Count, f2Count), 200, false, true, f2NodeIds);
        // TODO sanity check modifiedAt (for now modifiedAt=createdAt)
        // -ve test - invalid sort field
        params = new HashMap<>(2);
        params.put(Queries.PARAM_TERM, testTerm);
        params.put(Queries.PARAM_ORDERBY, "invalid asc");
        getAll(URL_QUERIES_LSN, paging, params, 400);
        // -ve test - unauthenticated - belts-and-braces ;-)
        setRequestContext(null);
        getAll(URL_QUERIES_LSN, paging, params, 401);
    } finally {
        // some cleanup
        setRequestContext(user1);
        for (String docId : allIds) {
            deleteNode(docId, true, 204);
        }
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Paging(org.alfresco.rest.api.tests.client.PublicApiClient.Paging) ArrayList(java.util.ArrayList) Document(org.alfresco.rest.api.tests.client.data.Document) Test(org.junit.Test) AbstractSingleNetworkSiteTest(org.alfresco.rest.AbstractSingleNetworkSiteTest)

Example 22 with Document

use of org.alfresco.rest.api.tests.client.data.Document in project alfresco-remote-api by Alfresco.

the class RenditionsTest method testCreateRenditionForNewVersion.

/**
 * Tests create rendition after uploading new version(s)
 */
@Test
public void testCreateRenditionForNewVersion() throws Exception {
    String PROP_LTM = "cm:lastThumbnailModification";
    String RENDITION_NAME = "imgpreview";
    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 fileName = "quick.pdf";
    File file = getResourceFile(fileName);
    MultiPartRequest reqBody = MultiPartBuilder.create().setFileData(new FileData(fileName, file)).build();
    Map<String, String> params = Collections.singletonMap("include", "properties");
    // Upload quick.pdf file into 'folder' - do not include request to create 'doclib' thumbnail
    HttpResponse response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), params, null, "alfresco", reqBody.getContentType(), 201);
    Document document1 = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    String contentNodeId = document1.getId();
    assertNotNull(document1.getProperties());
    assertNull(document1.getProperties().get(PROP_LTM));
    // pause briefly
    Thread.sleep(DELAY_IN_MS);
    // Get rendition (not created yet) information for node
    response = getSingle(getNodeRenditionsUrl(contentNodeId), RENDITION_NAME, 200);
    Rendition rendition = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Rendition.class);
    assertNotNull(rendition);
    assertEquals(RenditionStatus.NOT_CREATED, rendition.getStatus());
    params = new HashMap<>();
    params.put("placeholder", "false");
    getSingle(getNodeRenditionsUrl(contentNodeId), (RENDITION_NAME + "/content"), params, 404);
    // TODO add test to request creation of rendition as another user (that has read-only access on the content, not write)
    // Create and get 'imgpreview' rendition
    rendition = createAndGetRendition(contentNodeId, RENDITION_NAME);
    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);
    params = new HashMap<>();
    params.put("placeholder", "false");
    response = getSingle(getNodeRenditionsUrl(contentNodeId), (RENDITION_NAME + "/content"), params, 200);
    byte[] renditionBytes1 = response.getResponseAsBytes();
    assertNotNull(renditionBytes1);
    // check node details ...
    params = Collections.singletonMap("include", "properties");
    response = getSingle(NodesEntityResource.class, contentNodeId, params, 200);
    Document document1b = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals(document1b.getModifiedAt(), document1.getModifiedAt());
    assertEquals(document1b.getModifiedByUser().getId(), document1.getModifiedByUser().getId());
    assertEquals(document1b.getModifiedByUser().getDisplayName(), document1.getModifiedByUser().getDisplayName());
    assertNotEquals(document1b.getProperties().get(PROP_LTM), document1.getProperties().get(PROP_LTM));
    // upload another version of "quick.pdf" and check again
    fileName = "quick-2.pdf";
    file = getResourceFile(fileName);
    reqBody = MultiPartBuilder.create().setFileData(new FileData("quick.pdf", file)).setOverwrite(true).build();
    response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, null, "alfresco", reqBody.getContentType(), 201);
    Document document2 = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals(contentNodeId, document2.getId());
    // wait to allow new version of the rendition to be created ...
    Thread.sleep(DELAY_IN_MS * 4);
    params = new HashMap<>();
    params.put("placeholder", "false");
    response = getSingle(getNodeRenditionsUrl(contentNodeId), (RENDITION_NAME + "/content"), params, 200);
    assertNotNull(response.getResponseAsBytes());
    // check rendition binary has changed
    assertNotEquals(renditionBytes1, response.getResponseAsBytes());
    // check node details ...
    params = Collections.singletonMap("include", "properties");
    response = getSingle(NodesEntityResource.class, contentNodeId, params, 200);
    Document document2b = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertTrue(document2b.getModifiedAt().after(document1.getModifiedAt()));
    assertEquals(document2b.getModifiedByUser().getId(), document1.getModifiedByUser().getId());
    assertEquals(document2b.getModifiedByUser().getDisplayName(), document1.getModifiedByUser().getDisplayName());
    // check last thumbnail modification property has changed ! (REPO-1644)
    assertNotEquals(document2b.getProperties().get(PROP_LTM), document1b.getProperties().get(PROP_LTM));
}
Also used : 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) NodesEntityResource(org.alfresco.rest.api.nodes.NodesEntityResource) 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 23 with Document

use of org.alfresco.rest.api.tests.client.data.Document in project alfresco-remote-api by Alfresco.

the class RenditionsTest method testDownloadRendition.

/**
 * Tests download rendition.
 * <p>GET:</p>
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>/renditions/<renditionId>/content}
 */
@Test
public void testDownloadRendition() 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());
    // Download placeholder - by default with Content-Disposition header
    Map<String, String> params = new HashMap<>();
    params.put("placeholder", "true");
    response = getSingle(getNodeRenditionsUrl(contentNodeId), ("doclib/content"), params, 200);
    assertNotNull(response.getResponseAsBytes());
    Map<String, String> responseHeaders = response.getHeaders();
    assertNotNull(responseHeaders);
    String contentDisposition = responseHeaders.get("Content-Disposition");
    assertNotNull(contentDisposition);
    assertTrue(contentDisposition.contains("filename=\"doclib\""));
    String contentType = responseHeaders.get("Content-Type");
    assertNotNull(contentType);
    assertTrue(contentType.startsWith(MimetypeMap.MIMETYPE_IMAGE_PNG));
    // Download placeholder - without Content-Disposition header (attachment=false)
    params.put("attachment", "false");
    response = getSingle(getNodeRenditionsUrl(contentNodeId), ("doclib/content"), params, 200);
    assertNotNull(response.getResponseAsBytes());
    responseHeaders = response.getHeaders();
    assertNotNull(responseHeaders);
    String cacheControl = responseHeaders.get("Cache-Control");
    assertNotNull(cacheControl);
    assertTrue(cacheControl.contains("must-revalidate"));
    assertNull(responseHeaders.get("Content-Disposition"));
    contentType = responseHeaders.get("Content-Type");
    assertNotNull(contentType);
    assertTrue(contentType.startsWith(MimetypeMap.MIMETYPE_IMAGE_PNG));
    // Test 304 response - placeholder=true&attachment=false
    String lastModifiedHeader = responseHeaders.get(LAST_MODIFIED_HEADER);
    assertNotNull(lastModifiedHeader);
    Map<String, String> headers = Collections.singletonMap(IF_MODIFIED_SINCE_HEADER, lastModifiedHeader);
    // Currently the placeholder file is not cached.
    // As the placeholder is not a NodeRef, so we can't get the ContentModel.PROP_MODIFIED date.
    getSingle(getNodeRenditionsUrl(contentNodeId), "doclib/content", params, headers, 200);
    // Create and get 'doclib' rendition
    rendition = createAndGetRendition(contentNodeId, "doclib");
    assertNotNull(rendition);
    assertEquals(RenditionStatus.CREATED, rendition.getStatus());
    // Download rendition - by default with Content-Disposition header
    response = getSingle(getNodeRenditionsUrl(contentNodeId), "doclib/content", 200);
    assertNotNull(response.getResponseAsBytes());
    responseHeaders = response.getHeaders();
    assertNotNull(responseHeaders);
    contentDisposition = responseHeaders.get("Content-Disposition");
    assertNotNull(contentDisposition);
    assertTrue(contentDisposition.contains("filename=\"doclib\""));
    contentType = responseHeaders.get("Content-Type");
    assertNotNull(contentType);
    assertTrue(contentType.startsWith(MimetypeMap.MIMETYPE_IMAGE_PNG));
    // Download rendition - without Content-Disposition header (attachment=false)
    params = Collections.singletonMap("attachment", "false");
    response = getSingle(getNodeRenditionsUrl(contentNodeId), "doclib/content", params, 200);
    assertNotNull(response.getResponseAsBytes());
    responseHeaders = response.getHeaders();
    assertNotNull(responseHeaders);
    assertNull(responseHeaders.get("Content-Disposition"));
    contentType = responseHeaders.get("Content-Type");
    assertNotNull(contentType);
    assertTrue(contentType.startsWith(MimetypeMap.MIMETYPE_IMAGE_PNG));
    // Download rendition - with Content-Disposition header (attachment=true) same as default
    params = Collections.singletonMap("attachment", "true");
    response = getSingle(getNodeRenditionsUrl(contentNodeId), "doclib/content", params, 200);
    assertNotNull(response.getResponseAsBytes());
    responseHeaders = response.getHeaders();
    assertNotNull(responseHeaders);
    // Check the cache settings which have been set in the RenditionsImpl#getContent()
    cacheControl = responseHeaders.get("Cache-Control");
    assertNotNull(cacheControl);
    assertFalse(cacheControl.contains("must-revalidate"));
    assertTrue(cacheControl.contains("max-age=31536000"));
    contentDisposition = responseHeaders.get("Content-Disposition");
    assertNotNull(contentDisposition);
    assertTrue(contentDisposition.contains("filename=\"doclib\""));
    contentType = responseHeaders.get("Content-Type");
    assertNotNull(contentType);
    assertTrue(contentType.startsWith(MimetypeMap.MIMETYPE_IMAGE_PNG));
    // Test 304 response - doclib rendition (attachment=true)
    lastModifiedHeader = responseHeaders.get(LAST_MODIFIED_HEADER);
    assertNotNull(lastModifiedHeader);
    headers = Collections.singletonMap(IF_MODIFIED_SINCE_HEADER, lastModifiedHeader);
    getSingle(getNodeRenditionsUrl(contentNodeId), "doclib/content", params, headers, 304);
    // Here we want to overwrite/update the existing content in order to force a new rendition creation,
    // so the ContentModel.PROP_MODIFIED date would be different. Hence, we use the multipart upload by providing
    // the old fileName and setting overwrite field to true
    file = getResourceFile("quick-2.pdf");
    multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file)).setOverwrite(true);
    reqBody = multiPartBuilder.build();
    // Update quick.pdf
    post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    // The requested "If-Modified-Since" date is older than rendition modified date
    response = getSingleWithDelayRetry(getNodeRenditionsUrl(contentNodeId), "doclib/content", params, headers, MAX_RETRY, PAUSE_TIME, 200);
    assertNotNull(response);
    responseHeaders = response.getHeaders();
    assertNotNull(responseHeaders);
    String newLastModifiedHeader = responseHeaders.get(LAST_MODIFIED_HEADER);
    assertNotNull(newLastModifiedHeader);
    assertNotEquals(lastModifiedHeader, newLastModifiedHeader);
    // -ve tests
    // nodeId in the path parameter does not represent a file
    getSingle(getNodeRenditionsUrl(folder_Id), "doclib/content", 400);
    // nodeId in the path parameter does not exist
    getSingle(getNodeRenditionsUrl(UUID.randomUUID().toString()), "doclib/content", 404);
    // renditionId in the path parameter is not registered/available
    getSingle(getNodeRenditionsUrl(contentNodeId), ("renditionId" + System.currentTimeMillis() + "/content"), 404);
    InputStream inputStream = new ByteArrayInputStream("The quick brown fox jumps over the lazy dog".getBytes());
    file = TempFileProvider.createTempFile(inputStream, "RenditionsTest-", ".abcdef");
    reqBody = MultiPartBuilder.create().setFileData(new FileData(file.getName(), file)).build();
    // Upload temp file into 'folder'
    response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    contentNodeId = document.getId();
    // The content of the rendition does not exist and the placeholder parameter is not present
    getSingle(getNodeRenditionsUrl(contentNodeId), "doclib/content", 404);
    // The content of the rendition does not exist and the placeholder parameter has a value of "false"
    params = Collections.singletonMap("placeholder", "false");
    getSingle(getNodeRenditionsUrl(contentNodeId), "doclib/content", params, 404);
    // The rendition does not exist, a placeholder is not available and the placeholder parameter has a value of "true"
    params = Collections.singletonMap("placeholder", "true");
    getSingle(getNodeRenditionsUrl(contentNodeId), ("renditionId" + System.currentTimeMillis() + "/content"), params, 404);
    // Create a node without any content
    String emptyContentNodeId = addToDocumentLibrary(userOneN1Site, "emptyDoc.txt", TYPE_CM_CONTENT, userOneN1.getId());
    getSingle(getNodeRenditionsUrl(emptyContentNodeId), "doclib/content", params, 200);
}
Also used : MultiPartBuilder(org.alfresco.rest.api.tests.util.MultiPartBuilder) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) Rendition(org.alfresco.rest.api.tests.client.data.Rendition) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) 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 24 with Document

use of org.alfresco.rest.api.tests.client.data.Document in project alfresco-remote-api by Alfresco.

the class SharedLinkApiTest method testGetSharedLinksIncludePath.

/**
 * Tests for get /shared-links?include=path
 *
 * <p>GET:</p>
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/shared-links?include=path}
 */
@Test
@Category({ LuceneTests.class, RedundantTests.class })
public void testGetSharedLinksIncludePath() throws Exception {
    String contentText = "includePathTest" + RUNID;
    Paging paging = getPaging(0, 100);
    Map<String, String> queryParams = new HashMap<>();
    queryParams.put("include", "path");
    // As user 1: Test the backward compatibility by checking response with and without path is consistent when no shared-links
    setRequestContext(user1);
    // Get all shared links visible to user 1
    HttpResponse response = getAll(URL_SHARED_LINKS, paging, 200);
    List<QuickShareLink> sharedLinks = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), QuickShareLink.class);
    // Check that the same no of items is returned with include=path
    response = getAll(URL_SHARED_LINKS, paging, queryParams, 200);
    List<QuickShareLink> sharedLinksWithPath = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), QuickShareLink.class);
    assertEquals("get /shared-links/ API returns same no of shared-links with or without include=path, when there are no shared-links", sharedLinks, sharedLinksWithPath);
    // Create Files in various locations: My Files, SharedFiles, Sites with different visibility
    // Create doc in "My Files"
    Document myFile = createTextFile(getMyNodeId(), "MyFile" + RUNID + ".txt", contentText);
    // Create doc in "Shared" folder
    Document sharedFile = createTextFile(getSharedNodeId(), "SharedFile" + RUNID + ".txt", contentText);
    // Create Sites
    Site publicSite = createSite("TestSite-Public-" + RUNID, SiteVisibility.PUBLIC);
    Site modSite = createSite("TestSite-Moderate-" + RUNID, SiteVisibility.MODERATED);
    Site privateSite = createSite("TestSite-Private-" + RUNID, SiteVisibility.PRIVATE);
    // Create file in Site Public > DocumentLibrary
    String docLibPub = getSiteContainerNodeId(publicSite.getId(), "documentLibrary");
    Document filePublic = createTextFile(docLibPub, "filePublic.txt", contentText);
    // Create files in Site Moderated > DocumentLibrary > Folder 1 and Folder 2
    String docLibMod = getSiteContainerNodeId(modSite.getId(), "documentLibrary");
    Folder folder1 = createFolder(docLibMod, "1");
    Folder folder2 = createFolder(docLibMod, "2");
    Document fileMod = createTextFile(folder1.getId(), "fileMod.txt", contentText);
    Document fileMod2 = createTextFile(folder2.getId(), "fileMod2.txt", contentText);
    // Create file in Site Private > DocumentLibrary
    String docLibPvt = getSiteContainerNodeId(privateSite.getId(), "documentLibrary");
    Document filePrivate = createTextFile(docLibPvt, "filePrivate.txt", contentText);
    // Share the files above in: My Files, SharedFiles, Sites with different visibility
    String myFileLinkId = postSharedLink(myFile);
    String sharedLinkId = postSharedLink(sharedFile);
    String filePublicLinkId = postSharedLink(filePublic);
    String fileModLinkId = postSharedLink(fileMod);
    String fileMod2LinkId = postSharedLink(fileMod2);
    String filePrivateLinkId = postSharedLink(filePrivate);
    // Grant user2: Consumer Permission for Moderated Site > File1
    List<NodePermissions.NodePermission> locallySetPermissions = new ArrayList<>();
    locallySetPermissions.add(new NodePermissions.NodePermission(user2, PermissionService.CONSUMER, AccessStatus.ALLOWED.toString()));
    NodePermissions nodePermissions = new NodePermissions();
    nodePermissions.setIsInheritanceEnabled(false);
    nodePermissions.setLocallySet(locallySetPermissions);
    Document docPermissions = new Document();
    docPermissions.setPermissions(nodePermissions);
    put(URL_NODES, fileMod.getId(), toJsonAsStringNonNull(docPermissions), null, 200);
    // Grant user2: Consumer Permission for Moderated Site > Folder 2, File2
    put(URL_NODES, fileMod2.getId(), toJsonAsStringNonNull(docPermissions), null, 200);
    Folder folderPermissions = new Folder();
    folderPermissions.setPermissions(nodePermissions);
    put(URL_NODES, folder2.getId(), toJsonAsStringNonNull(folderPermissions), null, 200);
    // Get links For User1
    setRequestContext(user1);
    response = getSingle(QuickShareLinkEntityResource.class, myFileLinkId, null, 200);
    QuickShareLink link = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), QuickShareLink.class);
    assertNull("get /shared-links/<id> API does not return Path info by default", link.getPath());
    // Path info is not included for get shared-links/<id>
    response = getSingle(QuickShareLinkEntityResource.class, myFileLinkId, queryParams, 200);
    link = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), QuickShareLink.class);
    assertNull("get /shared-links/<id> API ignores Path info when requested as it is a noAuth API.", link.getPath());
    response = getAll(URL_SHARED_LINKS, paging, 200);
    sharedLinks = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), QuickShareLink.class);
    assertEquals("API returns correct shared-links as expected: without path info", 6, sharedLinks.size());
    sharedLinks.forEach(sharedLink -> assertNull("API does not return Path info for any shared-links by default", sharedLink.getPath()));
    // Path info is included for get shared-links when requested
    response = getAll(URL_SHARED_LINKS, paging, queryParams, 200);
    sharedLinks = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), QuickShareLink.class);
    // Complete path info is retrieved for the user with access to the complete path
    assertEquals("API returns correct shared-links as expected: with path info", 6, sharedLinks.size());
    sharedLinks.forEach(sharedLink -> assertTrue("API returns Complete Path info for each link when requested by content owner", sharedLink.getPath().getIsComplete()));
    // Get links For User2
    setRequestContext(user2);
    response = getAll(URL_SHARED_LINKS, paging, 200);
    sharedLinks = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), QuickShareLink.class);
    // Path info is not included when not requested
    assertEquals("API returns correct shared-links as expected for user2: without path info", 4, sharedLinks.size());
    sharedLinks.forEach(sharedLink -> assertNull("get /shared-links/ API does not return Path info for any shared-links by default", sharedLink.getPath()));
    response = getAll(URL_SHARED_LINKS, paging, queryParams, 200);
    sharedLinks = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), QuickShareLink.class);
    // Path info is retrieved for the user with access to the complete path: Sorted as LIFO
    assertEquals("API returns correct shared-links as expected for user2: with path info", 4, sharedLinks.size());
    sharedLinks.forEach(sharedLink -> assertNotNull("API returns Path info for each link when requested by user2", sharedLink.getPath()));
    // Moderated Site > fileMod2: Path only includes elements where user2 has access
    QuickShareLink sharedLink = sharedLinks.get(0);
    assertEquals("Incorrect sort order or SharedLink ID for fileMod2: " + sharedLink, fileMod2LinkId, sharedLink.getId());
    PathInfo path = sharedLink.getPath();
    assertEquals("Complete Path is returned even when user2 does not have appropriate permissions. SharedLink Path: " + path, false, path.getIsComplete());
    assertEquals("Path omits immediate Parent folder Name when user has access to it. SharedLink Path: " + path, "/" + folder2.getName(), path.getName());
    assertEquals("Path omits immediate Parent folder ID when user has access to it. SharedLink Path: " + path, folder2.getId(), path.getElements().get(0).getId());
    // Moderated Site > fileMod: Path empty when user2 does not have access to the immediate parent
    sharedLink = sharedLinks.get(1);
    assertEquals("Incorrect sort order or SharedLink ID for fileMod: " + sharedLink, fileModLinkId, sharedLink.getId());
    path = sharedLink.getPath();
    assertNotNull("Path info is not included in the response when user does not have right permissions. SharedLink Path: " + path, path);
    assertNull("Path Name is returned when user does not have right permissions. SharedLink Path: " + path, path.getName());
    assertNull("Path info is returned when user does not have right permissions. SharedLink Path: " + path, path.getIsComplete());
    assertNull("Path Elements are returned when user does not have right permissions. SharedLink Path: " + path, path.getElements());
    // Public Site > filePublic: Path includes all the elements when user2 has appropriate access
    sharedLink = sharedLinks.get(2);
    assertEquals("Incorrect sort order or SharedLink ID for filePublic: " + sharedLink, filePublicLinkId, sharedLink.getId());
    path = sharedLink.getPath();
    assertEquals("Complete Path is not returned for user2 for public files. SharedLink Path: " + path, true, path.getIsComplete());
    assertEquals("Incorrect Path Name for Public Site Files. SharedLink Path: " + path, "/Company Home/Sites/" + publicSite.getId() + "/documentLibrary", path.getName());
    assertEquals("Incorrect Path Elements for Public Site Files. SharedLink Path: " + path, 4, path.getElements().size());
    assertEquals("Incorrect ID in the Path for Company Home. SharedLink Path: " + path, getRootNodeId(), path.getElements().get(0).getId());
    assertEquals("Incorrect ID in the Path for Public Site. SharedLink Path: " + path, publicSite.getGuid(), path.getElements().get(2).getId());
    assertEquals("Incorrect ID in the Path for Public Site DocLib. SharedLink Path: " + path, docLibPub, path.getElements().get(3).getId());
    // Shared Files > shared: Path includes all the elements when user2 has appropriate access
    sharedLink = sharedLinks.get(3);
    assertEquals("Incorrect sort order or SharedLink ID for sharedFiles: " + sharedLink, sharedLinkId, sharedLink.getId());
    path = sharedLink.getPath();
    assertEquals("Complete Path is not returned for user2 for shared files. SharedLink Path: " + path, true, path.getIsComplete());
    assertEquals("Incorrect Path Name for Shared Files. SharedLink Path: " + path, "/Company Home/Shared", path.getName());
    assertEquals("Incorrect Path Elements for Shared Files. SharedLink Path: " + path, 2, path.getElements().size());
    assertEquals("Incorrect ID in the Path for Company Home. SharedLink Path: " + path, getRootNodeId(), path.getElements().get(0).getId());
    assertEquals("Incorrect ID in the path for Shared Files. SharedLink Path: " + path, getSharedNodeId(), path.getElements().get(1).getId());
    // Unauthorized request returns 401
    setRequestContext(null, "UserNotKnown", DEFAULT_ADMIN_PWD);
    queryParams = new HashMap<>();
    getAll(URL_SHARED_LINKS, paging, queryParams, 401);
    // Unauthenticated request returns 401
    setRequestContext(user2, null, null);
    getAll(URL_SHARED_LINKS, paging, queryParams, 401);
    // Delete the shared links
    setRequestContext(user1);
    deleteSharedLink(myFileLinkId);
    deleteSharedLink(sharedLinkId);
    deleteSharedLink(filePublicLinkId);
    deleteSharedLink(fileModLinkId);
    deleteSharedLink(fileMod2LinkId);
    deleteSharedLink(filePrivateLinkId);
}
Also used : Site(org.alfresco.rest.api.model.Site) NodePermissions(org.alfresco.rest.api.model.NodePermissions) HashMap(java.util.HashMap) Paging(org.alfresco.rest.api.tests.client.PublicApiClient.Paging) ArrayList(java.util.ArrayList) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) Document(org.alfresco.rest.api.tests.client.data.Document) Folder(org.alfresco.rest.api.tests.client.data.Folder) QuickShareLinkEntityResource(org.alfresco.rest.api.quicksharelinks.QuickShareLinkEntityResource) PathInfo(org.alfresco.rest.api.model.PathInfo) QuickShareLink(org.alfresco.rest.api.model.QuickShareLink) Category(org.junit.experimental.categories.Category) Test(org.junit.Test)

Example 25 with Document

use of org.alfresco.rest.api.tests.client.data.Document in project alfresco-remote-api by Alfresco.

the class SharedLinkApiTest method testEmailSharedLink.

/**
 * Tests emailing shared links.
 * <p>POST:</p>
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/shared-links/<sharedId>/email}
 */
@Test
public void testEmailSharedLink() throws Exception {
    setRequestContext(user1);
    // Create plain text document
    String myFolderNodeId = getMyNodeId();
    String contentText = "The quick brown fox jumps over the lazy dog.";
    String fileName = "file-" + RUNID + ".txt";
    Document doc = createTextFile(myFolderNodeId, fileName, contentText);
    String docId = doc.getId();
    // Create shared link to document
    Map<String, String> body = Collections.singletonMap("nodeId", docId);
    HttpResponse response = post(URL_SHARED_LINKS, toJsonAsStringNonNull(body), 201);
    QuickShareLink resp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), QuickShareLink.class);
    String sharedId = resp.getId();
    assertNotNull(sharedId);
    assertEquals(fileName, resp.getName());
    // Email request with minimal properties
    QuickShareLinkEmailRequest request = new QuickShareLinkEmailRequest();
    request.setClient("share");
    List<String> recipients = new ArrayList<>(2);
    recipients.add(user2 + "@acme.test");
    recipients.add(user2 + "@ping.test");
    request.setRecipientEmails(recipients);
    post(getEmailSharedLinkUrl(sharedId), RestApiUtil.toJsonAsString(request), 202);
    // Email request with all the properties
    request = new QuickShareLinkEmailRequest();
    request.setClient("share");
    request.setMessage("My custom message!");
    request.setLocale(Locale.UK.toString());
    recipients = Collections.singletonList(user2 + "@acme.test");
    request.setRecipientEmails(recipients);
    post(getEmailSharedLinkUrl(sharedId), RestApiUtil.toJsonAsString(request), 202);
    // -ve tests
    // sharedId path parameter does not exist
    post(getEmailSharedLinkUrl(sharedId + System.currentTimeMillis()), RestApiUtil.toJsonAsString(request), 404);
    // Unregistered client
    request = new QuickShareLinkEmailRequest();
    request.setClient("VeryCoolClient" + System.currentTimeMillis());
    List<String> user2Email = Collections.singletonList(user2 + "@acme.test");
    request.setRecipientEmails(user2Email);
    post(getEmailSharedLinkUrl(sharedId), RestApiUtil.toJsonAsString(request), 404);
    // client is mandatory
    request.setClient(null);
    post(getEmailSharedLinkUrl(sharedId), RestApiUtil.toJsonAsString(request), 400);
    // recipientEmails is mandatory
    request.setClient("share");
    request.setRecipientEmails(null);
    post(getEmailSharedLinkUrl(sharedId), RestApiUtil.toJsonAsString(request), 400);
    // TODO if and when these tests are optionally runnable via remote env then we could skip this part of the test
    // (else need to verify test mechanism for enterprise admin via jmx ... etc)
    QuickShareLinksImpl quickShareLinks = applicationContext.getBean("quickShareLinks", QuickShareLinksImpl.class);
    try {
        quickShareLinks.setEnabled(false);
        request = new QuickShareLinkEmailRequest();
        request.setClient("share");
        request.setRecipientEmails(user2Email);
        post(getEmailSharedLinkUrl(sharedId), RestApiUtil.toJsonAsString(request), 501);
    } finally {
        quickShareLinks.setEnabled(true);
    }
}
Also used : QuickShareLinkEmailRequest(org.alfresco.rest.api.tests.client.data.QuickShareLinkEmailRequest) ArrayList(java.util.ArrayList) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) Document(org.alfresco.rest.api.tests.client.data.Document) QuickShareLinksImpl(org.alfresco.rest.api.impl.QuickShareLinksImpl) QuickShareLink(org.alfresco.rest.api.model.QuickShareLink) Test(org.junit.Test)

Aggregations

Document (org.alfresco.rest.api.tests.client.data.Document)60 HttpResponse (org.alfresco.rest.api.tests.client.HttpResponse)49 Test (org.junit.Test)46 HashMap (java.util.HashMap)34 AbstractSingleNetworkSiteTest (org.alfresco.rest.AbstractSingleNetworkSiteTest)30 Folder (org.alfresco.rest.api.tests.client.data.Folder)25 LinkedHashMap (java.util.LinkedHashMap)22 File (java.io.File)20 ArrayList (java.util.ArrayList)20 Node (org.alfresco.rest.api.tests.client.data.Node)19 NodesEntityResource (org.alfresco.rest.api.nodes.NodesEntityResource)18 ContentInfo (org.alfresco.rest.api.tests.client.data.ContentInfo)15 MultiPartBuilder (org.alfresco.rest.api.tests.util.MultiPartBuilder)14 Paging (org.alfresco.rest.api.tests.client.PublicApiClient.Paging)13 NodePermissions (org.alfresco.rest.api.model.NodePermissions)12 FileData (org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData)11 MultiPartRequest (org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest)11 Rendition (org.alfresco.rest.api.tests.client.data.Rendition)10 JSONObject (org.json.simple.JSONObject)9 ByteArrayInputStream (java.io.ByteArrayInputStream)6