Search in sources :

Example 1 with PathInfo

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

the class NodeApiTest method testGetNodeInfo.

/**
 * Tests get node information.
 * <p>GET:</p>
 * {@literal <host>:<port>/alfresco/api/-default-/public/alfresco/versions/1/nodes/<nodeId>}
 */
@Test
public void testGetNodeInfo() throws Exception {
    setRequestContext(user1);
    HttpResponse response = getSingle(NodesEntityResource.class, Nodes.PATH_ROOT, null, 200);
    Node node = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Node.class);
    String rootNodeId = node.getId();
    response = getSingle(NodesEntityResource.class, Nodes.PATH_MY, null, 200);
    node = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Node.class);
    String myFilesNodeId = node.getId();
    assertNotNull(myFilesNodeId);
    assertEquals(user1, node.getName());
    assertTrue(node.getIsFolder());
    assertFalse(node.getIsFile());
    String userHomesId = node.getParentId();
    // /Company Home/User Homes/user<timestamp>/folder<timestamp>_A
    String folderA = "folder" + RUNID + "_A";
    String folderA_Id = createFolder(myFilesNodeId, folderA).getId();
    // /Company Home/User Homes/user<timestamp>/folder<timestamp>_A/folder<timestamp>_B
    String folderB = "folder" + RUNID + "_B";
    String folderB_Id = createFolder(folderA_Id, folderB).getId();
    // /Company Home/User Homes/user<timestamp>/folder<timestamp>_A/folder<timestamp>_B/content<timestamp>
    String title = "test title";
    Map<String, String> docProps = new HashMap<>();
    docProps.put("cm:title", title);
    String contentName = "content " + RUNID + ".txt";
    String content1Id = createTextFile(folderB_Id, contentName, "The quick brown fox jumps over the lazy dog.", "UTF-8", docProps).getId();
    // get node info
    response = getSingle(NodesEntityResource.class, content1Id, null, 200);
    Document documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    String content_Id = documentResp.getId();
    // Expected result ...
    UserInfo expectedUser = new UserInfo(user1);
    Document d1 = new Document();
    d1.setId(content_Id);
    d1.setParentId(folderB_Id);
    d1.setName(contentName);
    d1.setNodeType(TYPE_CM_CONTENT);
    ContentInfo ciExpected = new ContentInfo();
    ciExpected.setMimeType("text/plain");
    ciExpected.setMimeTypeName("Plain Text");
    ciExpected.setSizeInBytes(44L);
    ciExpected.setEncoding("ISO-8859-1");
    d1.setContent(ciExpected);
    d1.setCreatedByUser(expectedUser);
    d1.setModifiedByUser(expectedUser);
    Map<String, Object> props = new HashMap<>();
    props.put("cm:title", title);
    props.put("cm:versionLabel", "1.0");
    props.put("cm:versionType", "MAJOR");
    d1.setProperties(props);
    d1.setAspectNames(Arrays.asList("cm:auditable", "cm:titled", "cm:versionable", "cm:author"));
    // Note: Path is not part of the default info
    d1.expected(documentResp);
    // get node info + path
    // ...nodes/nodeId?include=path
    Map<String, String> params = Collections.singletonMap("include", "path");
    response = getSingle(NodesEntityResource.class, content1Id, params, 200);
    documentResp = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
    // Expected path ...
    // note: the pathInfo should only include the parents (not the requested node)
    List<ElementInfo> elements = new ArrayList<>(5);
    elements.add(new ElementInfo(rootNodeId, "Company Home"));
    elements.add(new ElementInfo(userHomesId, "User Homes"));
    elements.add(new ElementInfo(myFilesNodeId, user1));
    elements.add(new ElementInfo(folderA_Id, folderA));
    elements.add(new ElementInfo(folderB_Id, folderB));
    PathInfo expectedPath = new PathInfo("/Company Home/User Homes/" + user1 + "/" + folderA + "/" + folderB, true, elements);
    d1.setPath(expectedPath);
    d1.expected(documentResp);
    // get node info via relativePath
    params = Collections.singletonMap(Nodes.PARAM_RELATIVE_PATH, "/" + folderA + "/" + folderB);
    response = getSingle(NodesEntityResource.class, Nodes.PATH_MY, params, 200);
    Folder folderResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Folder.class);
    assertEquals(folderB_Id, folderResp.getId());
    params = Collections.singletonMap(Nodes.PARAM_RELATIVE_PATH, folderA + "/" + folderB + "/" + contentName);
    response = getSingle(NodesEntityResource.class, Nodes.PATH_MY, params, 200);
    documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals(content_Id, documentResp.getId());
    // test path with utf-8 encoded param (eg. ¢ => )
    String folderC = "folder" + RUNID + " ¢";
    String folderC_Id = createFolder(folderB_Id, folderC).getId();
    params = Collections.singletonMap(Nodes.PARAM_RELATIVE_PATH, "/" + folderA + "/" + folderB + "/" + folderC);
    response = getSingle(NodesEntityResource.class, Nodes.PATH_MY, params, 200);
    folderResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Folder.class);
    assertEquals(folderC_Id, folderResp.getId());
    // -ve test - get info for unknown node should return 404
    getSingle(NodesEntityResource.class, UUID.randomUUID().toString(), null, 404);
    // -ve test - user2 tries to get node info about user1's home folder
    setRequestContext(user2);
    getSingle(NodesEntityResource.class, myFilesNodeId, null, 403);
    setRequestContext(user1);
    // -ve test - try to get node info using relative path to unknown node
    params = Collections.singletonMap(Nodes.PARAM_RELATIVE_PATH, folderA + "/unknown");
    getSingle(NodesEntityResource.class, Nodes.PATH_MY, params, 404);
    // -ve test - try to get node info using relative path to node for which user does not have read permission (expect 404 instead of 403)
    params = Collections.singletonMap(Nodes.PARAM_RELATIVE_PATH, "User Homes/" + user2);
    getSingle(NodesEntityResource.class, Nodes.PATH_ROOT, params, 404);
    // -ve test - attempt to get node info for non-folder node with relative path should return 400
    params = Collections.singletonMap(Nodes.PARAM_RELATIVE_PATH, "/unknown");
    getSingle(NodesEntityResource.class, content_Id, params, 400);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ElementInfo(org.alfresco.rest.api.tests.client.data.PathInfo.ElementInfo) Node(org.alfresco.rest.api.tests.client.data.Node) ArrayList(java.util.ArrayList) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) UserInfo(org.alfresco.rest.api.tests.client.data.UserInfo) 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) ContentInfo(org.alfresco.rest.api.tests.client.data.ContentInfo) JSONObject(org.json.simple.JSONObject) PathInfo(org.alfresco.rest.api.tests.client.data.PathInfo) Test(org.junit.Test) AbstractSingleNetworkSiteTest(org.alfresco.rest.AbstractSingleNetworkSiteTest)

Example 2 with PathInfo

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

the class DeletedNodesTest method testCreateAndDelete.

/**
 * Tests getting deleted nodes
 * <p>GET:</p>
 * {@literal <host>:<port>/alfresco/api/-default-/public/alfresco/versions/1/deleted-nodes/}
 * {@literal <host>:<port>/alfresco/api/-default-/public/alfresco/versions/1/deleted-nodes/<nodeId>/}
 */
@Test
public void testCreateAndDelete() throws Exception {
    setRequestContext(user1);
    Date now = new Date();
    String folder1 = "folder-testCreateAndDelete-" + now.getTime() + "_1";
    Folder createdFolder = createFolder(tDocLibNodeId, folder1, null);
    assertNotNull(createdFolder);
    String f1Id = createdFolder.getId();
    // Create a folder outside a site
    Folder createdFolderNonSite = createFolder(Nodes.PATH_MY, folder1, null);
    assertNotNull(createdFolderNonSite);
    Document document = createEmptyTextFile(f1Id, "d1.txt");
    PublicApiClient.Paging paging = getPaging(0, 100);
    // First get any deleted nodes
    HttpResponse response = getAll(URL_DELETED_NODES, paging, 200);
    List<Node> nodes = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), Node.class);
    assertNotNull(nodes);
    int numOfNodes = nodes.size();
    deleteNode(document.getId());
    deleteNode(createdFolder.getId());
    deleteNode(createdFolderNonSite.getId());
    response = getAll(URL_DELETED_NODES, paging, 200);
    nodes = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), Node.class);
    assertNotNull(nodes);
    assertEquals(numOfNodes + 3, nodes.size());
    // The list is ordered with the most recently deleted node first
    checkDeletedNodes(now, createdFolder, createdFolderNonSite, document, nodes);
    // sanity check paging
    paging = getPaging(1, 1);
    response = getAll(URL_DELETED_NODES, paging, 200);
    nodes = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), Node.class);
    assertNotNull(nodes);
    assertEquals(1, nodes.size());
    PublicApiClient.ExpectedPaging expectedPaging = RestApiUtil.parsePaging(response.getJsonResponse());
    assertEquals(numOfNodes + 3, expectedPaging.getTotalItems().intValue());
    assertEquals(1, expectedPaging.getCount().intValue());
    assertEquals(1, expectedPaging.getSkipCount().intValue());
    assertEquals(1, expectedPaging.getMaxItems().intValue());
    assertTrue(expectedPaging.getHasMoreItems().booleanValue());
    Map<String, String> params = Collections.singletonMap("include", "path");
    response = getSingle(URL_DELETED_NODES, document.getId(), params, 200);
    Document node = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
    assertNotNull(node);
    assertEquals(user1, node.getArchivedByUser().getId());
    assertTrue(node.getArchivedAt().after(now));
    PathInfo path = node.getPath();
    assertNull("Path should be null because its parent has been deleted", path);
    assertNull("We don't show the parent id for a deleted node", node.getParentId());
    response = getSingle(URL_DELETED_NODES, createdFolder.getId(), params, 200);
    Folder fNode = jacksonUtil.parseEntry(response.getJsonResponse(), Folder.class);
    assertNotNull(fNode);
    assertEquals(user1, fNode.getArchivedByUser().getId());
    assertTrue(fNode.getArchivedAt().after(now));
    path = fNode.getPath();
    assertNotNull(path);
    assertEquals("/Company Home/Sites/" + tSiteId + "/documentLibrary", path.getName());
    assertTrue(path.getIsComplete());
    assertNull("We don't show the parent id for a deleted node", fNode.getParentId());
    response = getSingle(URL_DELETED_NODES, createdFolderNonSite.getId(), params, 200);
    fNode = jacksonUtil.parseEntry(response.getJsonResponse(), Folder.class);
    assertNotNull(fNode);
    assertEquals(user1, fNode.getArchivedByUser().getId());
    assertTrue(fNode.getArchivedAt().after(now));
    path = fNode.getPath();
    assertNotNull(path);
    assertEquals("/Company Home/User Homes/" + user1, path.getName());
    assertTrue(path.getIsComplete());
    // User 2 can't get it but user 1 can.
    setRequestContext(user2);
    getSingle(URL_DELETED_NODES, createdFolderNonSite.getId(), Status.STATUS_FORBIDDEN);
    setRequestContext(user1);
    // Invalid node ref
    getSingle(URL_DELETED_NODES, "iddontexist", 404);
    // Now as admin
    setRequestContext(networkAdmin);
    paging = getPaging(0, 100);
    response = publicApiClient.get(getScope(), URL_DELETED_NODES, null, null, null, createParams(paging, null));
    checkStatus(200, response.getStatusCode());
    nodes = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), Node.class);
    assertNotNull(nodes);
    checkDeletedNodes(now, createdFolder, createdFolderNonSite, document, nodes);
}
Also used : Node(org.alfresco.rest.api.tests.client.data.Node) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) Folder(org.alfresco.rest.api.tests.client.data.Folder) Document(org.alfresco.rest.api.tests.client.data.Document) Date(java.util.Date) PublicApiClient(org.alfresco.rest.api.tests.client.PublicApiClient) PathInfo(org.alfresco.rest.api.tests.client.data.PathInfo) Test(org.junit.Test)

Example 3 with PathInfo

use of org.alfresco.rest.api.tests.client.data.PathInfo 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) NodeDefinitionConstraint(org.alfresco.rest.api.model.NodeDefinitionConstraint) 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) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) FileData(org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData) Test(org.junit.Test) AbstractSingleNetworkSiteTest(org.alfresco.rest.AbstractSingleNetworkSiteTest)

Example 4 with PathInfo

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

the class NodeApiTest method testGetPathElements_DocLib.

/**
 * Tests get node with path information.
 * <p>GET:</p>
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>?include=path}
 */
@Test
public void testGetPathElements_DocLib() throws Exception {
    setRequestContext(user1);
    // user1 creates a private site and adds user2 as a site consumer
    String site1Title = "site-testGetPathElements_DocLib-" + RUNID;
    String site1Id = createSite(site1Title, SiteVisibility.PRIVATE).getId();
    addSiteMember(site1Id, user2, SiteRole.SiteConsumer);
    String site1DocLibNodeId = getSiteContainerNodeId(site1Id, "documentLibrary");
    // /Company Home/Sites/RandomSite<timestamp>/documentLibrary/folder<timestamp>_A
    String folderA = "folder" + RUNID + "_A";
    String folderA_Id = createFolder(site1DocLibNodeId, folderA).getId();
    // /Company Home/Sites/RandomSite<timestamp>/documentLibrary/folder<timestamp>_A/folder<timestamp>_B
    String folderB = "folder" + RUNID + "_B";
    String folderB_Id = createFolder(folderA_Id, folderB).getId();
    NodeRef folderB_Ref = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, folderB_Id);
    // /Company Home/Sites/RandomSite<timestamp>/documentLibrary/folder<timestamp>_A/folder<timestamp>_B/folder<timestamp>_C
    String folderC = "folder" + RUNID + "_C";
    String folderC_Id = createFolder(folderB_Id, folderC).getId();
    NodeRef folderC_Ref = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, folderC_Id);
    // /Company Home/Sites/RandomSite<timestamp>/documentLibrary/folder<timestamp>_A/folder<timestamp>_B/folder<timestamp>_C/content<timestamp>
    String content = "content" + RUNID;
    String content1_Id = createTextFile(folderC_Id, content, "The quick brown fox jumps over the lazy dog.").getId();
    // TODO refactor with remote permission api calls (maybe use v0 until we have v1 ?)
    final String tenantDomain = (networkOne != null ? networkOne.getId() : TenantService.DEFAULT_DOMAIN);
    AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>() {

        @Override
        public Void doWork() throws Exception {
            return TenantUtil.runAsTenant(new TenantUtil.TenantRunAsWork<Void>() {

                public Void doWork() throws Exception {
                    // Revoke folderB inherited permissions
                    permissionService.setInheritParentPermissions(folderB_Ref, false);
                    // Grant user2 permission for folderC
                    permissionService.setPermission(folderC_Ref, user2, PermissionService.CONSUMER, true);
                    return null;
                }
            }, tenantDomain);
        }
    }, user1);
    // ...nodes/nodeId?include=path
    Map<String, String> params = Collections.singletonMap("include", "path");
    HttpResponse response = getSingle(NodesEntityResource.class, content1_Id, params, 200);
    Document node = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
    PathInfo path = node.getPath();
    assertNotNull(path);
    assertTrue(path.getIsComplete());
    assertNotNull(path.getName());
    // the path should only include the parents (not the requested node)
    assertFalse(path.getName().endsWith(content));
    assertTrue(path.getName().startsWith("/Company Home"));
    List<ElementInfo> pathElements = path.getElements();
    assertEquals(7, pathElements.size());
    // Check path element names and types, and one or two random aspects.
    assertEquals("Company Home", pathElements.get(0).getName());
    assertEquals("cm:folder", pathElements.get(0).getNodeType());
    assertEquals("Sites", pathElements.get(1).getName());
    assertEquals("st:sites", pathElements.get(1).getNodeType());
    assertEquals(site1Id, pathElements.get(2).getName());
    assertEquals("st:site", pathElements.get(2).getNodeType());
    assertTrue(pathElements.get(2).getAspectNames().contains("cm:titled"));
    // Check that sys:* is filtered out - to be consistent with other aspect name lists
    // e.g. /nodes/{nodeId}/children?include=aspectNames
    assertFalse(pathElements.get(2).getAspectNames().contains("sys:undeletable"));
    assertFalse(pathElements.get(2).getAspectNames().contains("sys:unmovable"));
    assertEquals("documentLibrary", pathElements.get(3).getName());
    assertEquals("cm:folder", pathElements.get(3).getNodeType());
    assertTrue(pathElements.get(3).getAspectNames().contains("st:siteContainer"));
    assertEquals(folderA, pathElements.get(4).getName());
    assertEquals("cm:folder", pathElements.get(4).getNodeType());
    assertEquals(folderB, pathElements.get(5).getName());
    assertEquals("cm:folder", pathElements.get(5).getNodeType());
    assertEquals(folderC, pathElements.get(6).getName());
    assertEquals("cm:folder", pathElements.get(6).getNodeType());
    // Try the above tests with user2 (site consumer)
    setRequestContext(user2);
    response = getSingle(NodesEntityResource.class, content1_Id, params, 200);
    node = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
    path = node.getPath();
    assertNotNull(path);
    assertFalse("The path is not complete as the user doesn't have permission to access the full path.", path.getIsComplete());
    assertNotNull(path.getName());
    // site consumer (user2) dose not have access to the folderB
    assertFalse("site consumer (user2) dose not have access to the folderB", path.getName().contains(folderB));
    assertFalse(path.getName().startsWith("/Company Home"));
    // Go up as far as they can, before getting access denied (i.e. "/folderC")
    assertTrue(path.getName().endsWith(folderC));
    pathElements = path.getElements();
    assertEquals(1, pathElements.size());
    assertEquals(folderC, pathElements.get(0).getName());
    // cleanup
    setRequestContext(user1);
    deleteSite(site1Id, true, 204);
}
Also used : ElementInfo(org.alfresco.rest.api.tests.client.data.PathInfo.ElementInfo) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) NodesEntityResource(org.alfresco.rest.api.nodes.NodesEntityResource) Document(org.alfresco.rest.api.tests.client.data.Document) NodeRef(org.alfresco.service.cmr.repository.NodeRef) AuthenticationUtil(org.alfresco.repo.security.authentication.AuthenticationUtil) PathInfo(org.alfresco.rest.api.tests.client.data.PathInfo) Test(org.junit.Test) AbstractSingleNetworkSiteTest(org.alfresco.rest.AbstractSingleNetworkSiteTest)

Example 5 with PathInfo

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

the class NodeApiTest method testUpdateFileWithBinaryUpload.

/**
 * Tests update file content
 * <p>PUT:</p>
 * {@literal <host>:<port>/alfresco/api/-default-/public/alfresco/versions/1/nodes/<nodeId>/content}
 */
@Test
public void testUpdateFileWithBinaryUpload() throws Exception {
    setRequestContext(user1);
    String myNodeId = getMyNodeId();
    String folderName = "f1-testUpdateFileWithBinaryUpload-" + RUNID;
    Folder folderResp = createFolder(myNodeId, folderName);
    String f1_nodeId = folderResp.getId();
    String anoNodeName = "another";
    createFolder(f1_nodeId, anoNodeName);
    Document doc = new Document();
    final String docName = "testdoc.txt";
    doc.setName(docName);
    doc.setNodeType(TYPE_CM_CONTENT);
    doc.setProperties(Collections.singletonMap("cm:title", (Object) "test title"));
    ContentInfo contentInfo = new ContentInfo();
    doc.setContent(contentInfo);
    // create an empty file within F1 folder
    HttpResponse response = post(getNodeChildrenUrl(f1_nodeId), toJsonAsStringNonNull(doc), 201);
    Document docResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals(docName, docResp.getName());
    assertNotNull(docResp.getContent());
    assertEquals(0, docResp.getContent().getSizeInBytes().intValue());
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, docResp.getContent().getMimeType());
    // Default encoding
    assertEquals("UTF-8", docResp.getContent().getEncoding());
    // Update the empty node's content
    String content = "The quick brown fox jumps over the lazy dog.";
    ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes());
    File txtFile = TempFileProvider.createTempFile(inputStream, getClass().getSimpleName(), ".txt");
    BinaryPayload payload = new BinaryPayload(txtFile);
    // Try to update a folder!
    putBinary(getNodeContentUrl(f1_nodeId), payload, null, null, 400);
    // Try to update a non-existent file
    putBinary(getNodeContentUrl(UUID.randomUUID().toString()), payload, null, null, 404);
    final String url = getNodeContentUrl(docResp.getId());
    // Update the empty file
    response = putBinary(url, payload, null, null, 200);
    docResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals(docName, docResp.getName());
    assertNotNull(docResp.getId());
    assertNotNull(docResp.getCreatedAt());
    assertNotNull(docResp.getCreatedByUser());
    assertNotNull(docResp.getModifiedAt());
    assertNotNull(docResp.getModifiedByUser());
    assertFalse(docResp.getIsFolder());
    assertTrue(docResp.getIsFile());
    assertNull(docResp.getIsLink());
    assertEquals(TYPE_CM_CONTENT, docResp.getNodeType());
    assertNotNull(docResp.getParentId());
    assertEquals(f1_nodeId, docResp.getParentId());
    assertNotNull(docResp.getProperties());
    assertNotNull(docResp.getAspectNames());
    contentInfo = docResp.getContent();
    assertNotNull(contentInfo);
    assertNotNull(contentInfo.getEncoding());
    assertTrue(contentInfo.getSizeInBytes() > 0);
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    assertNotNull(contentInfo.getMimeTypeName());
    assertEquals("ISO-8859-1", contentInfo.getEncoding());
    // path is not part of the default response
    assertNull(docResp.getPath());
    // Download the file
    response = getSingle(url, user1, null, 200);
    assertEquals(content, response.getResponse());
    // Update the node's content again. Also make the response return the path!
    content = "The quick brown fox jumps over the lazy dog updated !";
    inputStream = new ByteArrayInputStream(content.getBytes());
    txtFile = TempFileProvider.createTempFile(inputStream, getClass().getSimpleName(), ".txt");
    payload = new BinaryPayload(txtFile);
    response = putBinary(url + "?include=path", payload, null, null, 200);
    docResp = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
    assertEquals(docName, docResp.getName());
    assertNotNull(docResp.getContent());
    assertTrue(docResp.getContent().getSizeInBytes().intValue() > 0);
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, docResp.getContent().getMimeType());
    assertEquals("ISO-8859-1", docResp.getContent().getEncoding());
    PathInfo pathInfo = docResp.getPath();
    assertNotNull(pathInfo);
    assertTrue(pathInfo.getIsComplete());
    List<ElementInfo> pathElements = pathInfo.getElements();
    assertNotNull(pathElements);
    assertTrue(pathElements.size() > 0);
    // check the last element is F1
    assertEquals(folderResp.getName(), pathElements.get(pathElements.size() - 1).getName());
    // Download the file
    response = getSingle(url, user1, null, 200);
    assertEquals(content, response.getResponse());
    // Update the node's content again. Also rename the file !
    content = "The quick brown fox jumps over the lazy dog updated again !";
    inputStream = new ByteArrayInputStream(content.getBytes());
    txtFile = TempFileProvider.createTempFile(inputStream, getClass().getSimpleName(), ".txt");
    payload = new BinaryPayload(txtFile);
    String docName2 = "hello-world.txt";
    Map params = new HashMap<>();
    params.put(Nodes.PARAM_NAME, docName2);
    response = putBinary(url, payload, null, params, 200);
    docResp = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
    assertEquals(docName2, docResp.getName());
    // Download the file
    response = getSingle(url, user1, null, 200);
    assertEquals(content, response.getResponse());
    // -ve - optional "name" is invalid
    params = new HashMap<>();
    params.put(Nodes.PARAM_NAME, "hello/world.txt");
    payload = new BinaryPayload(txtFile);
    putBinary(url, payload, null, params, 422);
    // -ve - optional "name" already exists ...
    params = new HashMap<>();
    params.put(Nodes.PARAM_NAME, anoNodeName);
    payload = new BinaryPayload(txtFile);
    putBinary(url, payload, null, params, 409);
    // -ve - try to  update content using multi-part form data
    payload = new BinaryPayload(txtFile, "multipart/form-data", null);
    putBinary(url, payload, null, null, 415);
    // -ve - try to invalid media type argument (when parsing request)
    payload = new BinaryPayload(txtFile, "/jpeg", null);
    putBinary(url, payload, null, null, 415);
}
Also used : ElementInfo(org.alfresco.rest.api.tests.client.data.PathInfo.ElementInfo) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) Folder(org.alfresco.rest.api.tests.client.data.Folder) Document(org.alfresco.rest.api.tests.client.data.Document) BinaryPayload(org.alfresco.rest.api.tests.client.PublicApiHttpClient.BinaryPayload) ContentInfo(org.alfresco.rest.api.tests.client.data.ContentInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) JSONObject(org.json.simple.JSONObject) PathInfo(org.alfresco.rest.api.tests.client.data.PathInfo) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) MultiValueMap(org.apache.commons.collections.map.MultiValueMap) Map(java.util.Map) MimetypeMap(org.alfresco.repo.content.MimetypeMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test) AbstractSingleNetworkSiteTest(org.alfresco.rest.AbstractSingleNetworkSiteTest)

Aggregations

HttpResponse (org.alfresco.rest.api.tests.client.HttpResponse)5 Document (org.alfresco.rest.api.tests.client.data.Document)5 PathInfo (org.alfresco.rest.api.tests.client.data.PathInfo)5 Test (org.junit.Test)5 AbstractSingleNetworkSiteTest (org.alfresco.rest.AbstractSingleNetworkSiteTest)4 Folder (org.alfresco.rest.api.tests.client.data.Folder)4 ElementInfo (org.alfresco.rest.api.tests.client.data.PathInfo.ElementInfo)4 HashMap (java.util.HashMap)3 LinkedHashMap (java.util.LinkedHashMap)3 NodesEntityResource (org.alfresco.rest.api.nodes.NodesEntityResource)3 ContentInfo (org.alfresco.rest.api.tests.client.data.ContentInfo)3 File (java.io.File)2 RandomAccessFile (java.io.RandomAccessFile)2 PublicApiClient (org.alfresco.rest.api.tests.client.PublicApiClient)2 Node (org.alfresco.rest.api.tests.client.data.Node)2 JSONObject (org.json.simple.JSONObject)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 Map (java.util.Map)1