Search in sources :

Example 11 with ContentInfo

use of org.alfresco.rest.api.tests.client.data.ContentInfo 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 12 with ContentInfo

use of org.alfresco.rest.api.tests.client.data.ContentInfo 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)

Example 13 with ContentInfo

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

the class NodeApiTest method testCreateEmptyFile.

/**
 * Tests create empty file.
 * <p>POST:</p>
 * {@literal <host>:<port>/alfresco/api/-default-/public/alfresco/versions/1/nodes/<nodeId>/children}
 */
@Test
public void testCreateEmptyFile() throws Exception {
    setRequestContext(user1);
    // create folder f0
    String folder0Name = "f0-testCreateEmptyFile-" + RUNID;
    String f0Id = createFolder(Nodes.PATH_MY, folder0Name).getId();
    UserInfo expectedUser = new UserInfo(user1);
    String postUrl = getNodeChildrenUrl(f0Id);
    Document d1 = new Document();
    d1.setName("d1.txt");
    d1.setNodeType(TYPE_CM_CONTENT);
    // create empty file
    HttpResponse response = post(postUrl, toJsonAsStringNonNull(d1), 201);
    Document documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    String d1Id = documentResp.getId();
    d1.setIsFolder(false);
    d1.setParentId(f0Id);
    d1.setAspectNames(Collections.singletonList("cm:auditable"));
    d1.setCreatedByUser(expectedUser);
    d1.setModifiedByUser(expectedUser);
    ContentInfo ciExpected = new ContentInfo();
    ciExpected.setMimeType("text/plain");
    ciExpected.setMimeTypeName("Plain Text");
    ciExpected.setSizeInBytes(0L);
    ciExpected.setEncoding("UTF-8");
    d1.setContent(ciExpected);
    d1.expected(documentResp);
    // create empty file with properties
    Map<String, Object> props = new HashMap<>();
    props.put("cm:title", "my file title");
    props.put("cm:description", "my file description");
    Document d2 = new Document();
    d2.setName("d2.txt");
    d2.setNodeType(TYPE_CM_CONTENT);
    d2.setProperties(props);
    response = post(postUrl, toJsonAsStringNonNull(d2), 201);
    documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    d2.setIsFolder(false);
    d2.setParentId(f0Id);
    d2.setAspectNames(Arrays.asList("cm:auditable", "cm:titled"));
    d2.setCreatedByUser(expectedUser);
    d2.setModifiedByUser(expectedUser);
    ciExpected = new ContentInfo();
    ciExpected.setMimeType("text/plain");
    ciExpected.setMimeTypeName("Plain Text");
    ciExpected.setSizeInBytes(0L);
    ciExpected.setEncoding("UTF-8");
    d2.setContent(ciExpected);
    d2.expected(documentResp);
    // create another empty file in a (partially existing) folder path
    Node n = new Node();
    n.setName("d3.txt");
    n.setNodeType(TYPE_CM_CONTENT);
    n.setRelativePath("/f1/f2");
    // create node
    response = post(getNodeChildrenUrl(f0Id), RestApiUtil.toJsonAsStringNonNull(n), 201);
    documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    // check parent hierarchy ...
    response = getSingle(NodesEntityResource.class, documentResp.getId(), null, 200);
    Folder folderResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Folder.class);
    assertEquals(folderResp.getName(), "d3.txt");
    response = getSingle(NodesEntityResource.class, folderResp.getParentId(), null, 200);
    folderResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Folder.class);
    assertEquals(folderResp.getName(), "f2");
    response = getSingle(NodesEntityResource.class, folderResp.getParentId(), null, 200);
    folderResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Folder.class);
    assertEquals(folderResp.getName(), "f1");
    response = getSingle(NodesEntityResource.class, folderResp.getParentId(), null, 200);
    folderResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Folder.class);
    assertEquals(f0Id, folderResp.getId());
    // -ve test - name is mandatory
    Document invalid = new Document();
    invalid.setNodeType(TYPE_CM_CONTENT);
    post(postUrl, toJsonAsStringNonNull(invalid), 400);
    // -ve test - node type is mandatory
    invalid = new Document();
    invalid.setName("my file.txt");
    post(postUrl, toJsonAsStringNonNull(invalid), 400);
    // -ve test - invalid (model integrity exception)
    Document d3 = new Document();
    d3.setName("d3.txt");
    d3.setNodeType(TYPE_CM_CONTENT);
    post(getNodeChildrenUrl(d1Id), toJsonAsStringNonNull(d3), 422);
    // -ve test - unknown parent folder node id
    post(getNodeChildrenUrl(UUID.randomUUID().toString()), toJsonAsStringNonNull(d3), 404);
    // -ve test - duplicate name
    post(postUrl, toJsonAsStringNonNull(d1), 409);
    // Create a file with a duplicate name (d1.txt), but set the autoRename to true
    response = post(postUrl, toJsonAsStringNonNull(d1), "?" + Nodes.PARAM_AUTO_RENAME + "=true", 201);
    documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals("d1-1.txt", documentResp.getName());
    // Create a file with a duplicate name (d1.txt) again, but set the autoRename to true
    response = post(postUrl, toJsonAsStringNonNull(d1), "?" + Nodes.PARAM_AUTO_RENAME + "=true", 201);
    documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals("d1-2.txt", documentResp.getName());
    // Create a file with a duplicate name (d1-2.txt) again, but set the autoRename to true
    d1.setName("d1-2.txt");
    response = post(postUrl, toJsonAsStringNonNull(d1), "?" + Nodes.PARAM_AUTO_RENAME + "=true", 201);
    documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals("d1-2-1.txt", documentResp.getName());
    // -ve test - create a file with a duplicate name (d1-2.txt), but set the autoRename to false
    post(postUrl, toJsonAsStringNonNull(d1), "?" + Nodes.PARAM_AUTO_RENAME + "=false", 409);
}
Also used : ContentInfo(org.alfresco.rest.api.tests.client.data.ContentInfo) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Node(org.alfresco.rest.api.tests.client.data.Node) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) UserInfo(org.alfresco.rest.api.tests.client.data.UserInfo) JSONObject(org.json.simple.JSONObject) 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) Test(org.junit.Test) AbstractSingleNetworkSiteTest(org.alfresco.rest.AbstractSingleNetworkSiteTest)

Example 14 with ContentInfo

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

the class NodeApiTest method testGuessMimeTypeAndEncoding.

/**
 * Tests guess mimetype & guess encoding when uploading file/content (create or update) - also empty file/content
 * <p>POST:</p>
 * {@literal <host>:<port>/alfresco/api/-default-/public/alfresco/versions/1/nodes/<nodeId>/children}
 * <p>PUT:</p>
 * {@literal <host>:<port>/alfresco/api/-default-/public/alfresco/versions/1/nodes/<nodeId>/content}
 */
@Test
public void testGuessMimeTypeAndEncoding() throws Exception {
    setRequestContext(user1);
    String fId = createFolder(getMyNodeId(), "test-folder-guess-" + RUNID).getId();
    // create empty files
    Document d = new Document();
    d.setName("my doc");
    d.setNodeType(TYPE_CM_CONTENT);
    HttpResponse response = post(getNodeChildrenUrl(fId), toJsonAsStringNonNull(d), 201);
    Document documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals(MimetypeMap.MIMETYPE_BINARY, documentResp.getContent().getMimeType());
    assertEquals("Binary File (Octet Stream)", documentResp.getContent().getMimeTypeName());
    assertEquals(0L, documentResp.getContent().getSizeInBytes().longValue());
    assertEquals("UTF-8", documentResp.getContent().getEncoding());
    d = new Document();
    d.setName("my doc.txt");
    d.setNodeType(TYPE_CM_CONTENT);
    response = post(getNodeChildrenUrl(fId), toJsonAsStringNonNull(d), 201);
    documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, documentResp.getContent().getMimeType());
    assertEquals("Plain Text", documentResp.getContent().getMimeTypeName());
    assertEquals(0L, documentResp.getContent().getSizeInBytes().longValue());
    assertEquals("UTF-8", documentResp.getContent().getEncoding());
    d = new Document();
    d.setName("my doc.pdf");
    d.setNodeType(TYPE_CM_CONTENT);
    response = post(getNodeChildrenUrl(fId), toJsonAsStringNonNull(d), 201);
    documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    assertEquals(MimetypeMap.MIMETYPE_PDF, documentResp.getContent().getMimeType());
    assertEquals("Adobe PDF Document", documentResp.getContent().getMimeTypeName());
    assertEquals(0L, documentResp.getContent().getSizeInBytes().longValue());
    assertEquals("UTF-8", documentResp.getContent().getEncoding());
    // upload files
    String fileName = "quick-2.pdf";
    File file = getResourceFile(fileName);
    MultiPartBuilder multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    MultiPartRequest reqBody = multiPartBuilder.build();
    response = post(getNodeChildrenUrl(fId), reqBody.getBody(), null, reqBody.getContentType(), 201);
    Document document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    ContentInfo contentInfo = document.getContent();
    assertEquals(MimetypeMap.MIMETYPE_PDF, contentInfo.getMimeType());
    assertEquals("UTF-8", contentInfo.getEncoding());
    fileName = "quick-2.pdf";
    file = getResourceFile(fileName);
    multiPartBuilder = MultiPartBuilder.create().setFileData(// note: we've deliberately dropped the file ext here
    new FileData("quick-2", file));
    reqBody = multiPartBuilder.build();
    response = post(getNodeChildrenUrl(fId), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    contentInfo = document.getContent();
    assertEquals(MimetypeMap.MIMETYPE_PDF, contentInfo.getMimeType());
    assertEquals("UTF-8", contentInfo.getEncoding());
    fileName = "example-1.txt";
    file = getResourceFile(fileName);
    multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    reqBody = multiPartBuilder.build();
    response = post(getNodeChildrenUrl(fId), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    contentInfo = document.getContent();
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    assertEquals("ISO-8859-1", contentInfo.getEncoding());
    fileName = "example-2.txt";
    file = getResourceFile(fileName);
    multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    reqBody = multiPartBuilder.build();
    response = post(getNodeChildrenUrl(fId), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    contentInfo = document.getContent();
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    assertEquals("UTF-8", contentInfo.getEncoding());
    fileName = "shift-jis.txt";
    file = getResourceFile(fileName);
    multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    reqBody = multiPartBuilder.build();
    response = post(getNodeChildrenUrl(fId), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    contentInfo = document.getContent();
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    assertEquals("Shift_JIS", contentInfo.getEncoding());
    fileName = "example-1.xml";
    file = getResourceFile(fileName);
    multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    reqBody = multiPartBuilder.build();
    response = post(getNodeChildrenUrl(fId), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    contentInfo = document.getContent();
    assertEquals(MimetypeMap.MIMETYPE_XML, contentInfo.getMimeType());
    assertEquals("ISO-8859-1", contentInfo.getEncoding());
    fileName = "example-2.xml";
    file = getResourceFile(fileName);
    multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    reqBody = multiPartBuilder.build();
    response = post(getNodeChildrenUrl(fId), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    contentInfo = document.getContent();
    assertEquals(MimetypeMap.MIMETYPE_XML, contentInfo.getMimeType());
    assertEquals("UTF-8", contentInfo.getEncoding());
    // upload file, rename and then update file
    fileName = "quick.pdf";
    file = getResourceFile(fileName);
    multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    reqBody = multiPartBuilder.build();
    response = post(getNodeChildrenUrl(fId), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    String docId = document.getId();
    contentInfo = document.getContent();
    assertEquals(MimetypeMap.MIMETYPE_PDF, contentInfo.getMimeType());
    assertEquals("UTF-8", contentInfo.getEncoding());
    // rename (mimeType remains unchanged, binary has not changed)
    Document dUpdate = new Document();
    dUpdate.setName("quick.docx");
    response = put(URL_NODES, docId, toJsonAsStringNonNull(dUpdate), null, 200);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    contentInfo = document.getContent();
    assertEquals(MimetypeMap.MIMETYPE_PDF, contentInfo.getMimeType());
    assertEquals("UTF-8", contentInfo.getEncoding());
    fileName = "quick.docx";
    file = getResourceFile(fileName);
    BinaryPayload payload = new BinaryPayload(file);
    response = putBinary(getNodeContentUrl(docId), payload, null, null, 200);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    contentInfo = document.getContent();
    assertEquals(MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING, contentInfo.getMimeType());
    assertEquals("UTF-8", contentInfo.getEncoding());
    // additional test
    fileName = "CMIS-Delete.json";
    file = getResourceFile(fileName);
    multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData("special-" + GUID.generate(), file));
    reqBody = multiPartBuilder.build();
    response = post(getNodeChildrenUrl(fId), reqBody.getBody(), null, reqBody.getContentType(), 201);
    document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    contentInfo = document.getContent();
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentInfo.getMimeType());
    assertEquals("UTF-8", contentInfo.getEncoding());
    // cleanup
    deleteNode(fId);
}
Also used : MultiPartBuilder(org.alfresco.rest.api.tests.util.MultiPartBuilder) BinaryPayload(org.alfresco.rest.api.tests.client.PublicApiHttpClient.BinaryPayload) ContentInfo(org.alfresco.rest.api.tests.client.data.ContentInfo) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) MultiPartRequest(org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest) 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) AbstractSingleNetworkSiteTest(org.alfresco.rest.AbstractSingleNetworkSiteTest)

Example 15 with ContentInfo

use of org.alfresco.rest.api.tests.client.data.ContentInfo 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) File(java.io.File) 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)15 ContentInfo (org.alfresco.rest.api.tests.client.data.ContentInfo)15 Document (org.alfresco.rest.api.tests.client.data.Document)15 Test (org.junit.Test)14 File (java.io.File)11 MultiPartBuilder (org.alfresco.rest.api.tests.util.MultiPartBuilder)9 HashMap (java.util.HashMap)8 LinkedHashMap (java.util.LinkedHashMap)8 AbstractSingleNetworkSiteTest (org.alfresco.rest.AbstractSingleNetworkSiteTest)8 FileData (org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData)8 MultiPartRequest (org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest)8 Folder (org.alfresco.rest.api.tests.client.data.Folder)7 NodesEntityResource (org.alfresco.rest.api.nodes.NodesEntityResource)6 Rendition (org.alfresco.rest.api.tests.client.data.Rendition)5 JSONObject (org.json.simple.JSONObject)5 RestApiUtil.toJsonAsString (org.alfresco.rest.api.tests.util.RestApiUtil.toJsonAsString)4 ArrayList (java.util.ArrayList)3 PublicApiClient (org.alfresco.rest.api.tests.client.PublicApiClient)3 ExpectedPaging (org.alfresco.rest.api.tests.client.PublicApiClient.ExpectedPaging)3 Paging (org.alfresco.rest.api.tests.client.PublicApiClient.Paging)3