Merged HEAD (5.2) to 5.2.N (5.2.1)

126385 jkaabimofrad: Merged FILE-FOLDER-API (5.2.0) to HEAD (5.2)
      120469 jvonka: FileFolder API - NodeApiTest - add test to retrieve content
      - also update test fwk to support post request body as byte array (as well as string)
      RA-641


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/BRANCHES/DEV/5.2.N/root@126731 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Ancuta Morarasu
2016-05-11 10:56:47 +00:00
parent 08ac84ff25
commit 7801810028
5 changed files with 235 additions and 70 deletions

View File

@@ -76,7 +76,20 @@ public abstract class AbstractBaseApiTest extends EnterpriseTestApi
return response; return response;
} }
protected HttpResponse post(String url, String runAsUser, String body, String queryString, String contentType, int expectedStatus) throws Exception protected HttpResponse post(String url, String runAsUser, String body, String queryString, String contentType, int expectedStatus) throws Exception
{
publicApiClient.setRequestContext(new RequestContext(runAsUser));
if (queryString != null)
{
url += queryString;
}
HttpResponse response = publicApiClient.post(getScope(), url, null, null, null, body, contentType);
checkStatus(expectedStatus, response.getStatusCode());
return response;
}
protected HttpResponse post(String url, String runAsUser, byte[] body, String queryString, String contentType, int expectedStatus) throws Exception
{ {
publicApiClient.setRequestContext(new RequestContext(runAsUser)); publicApiClient.setRequestContext(new RequestContext(runAsUser));
if (queryString != null) if (queryString != null)

View File

@@ -20,12 +20,7 @@
package org.alfresco.rest.api.tests; package org.alfresco.rest.api.tests;
import static org.alfresco.rest.api.tests.util.RestApiUtil.parsePaging; import static org.alfresco.rest.api.tests.util.RestApiUtil.parsePaging;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.alfresco.model.ContentModel; import org.alfresco.model.ContentModel;
import org.alfresco.model.ForumModel; import org.alfresco.model.ForumModel;
@@ -77,6 +72,8 @@ import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.Serializable; import java.io.Serializable;
import java.net.URL; import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@@ -102,6 +99,8 @@ public class NodeApiTest extends AbstractBaseApiTest
{ {
private static final String RESOURCE_PREFIX = "publicapi/upload/"; private static final String RESOURCE_PREFIX = "publicapi/upload/";
private static final String URL_NODES = "nodes/";
/** /**
* User one from network one * User one from network one
*/ */
@@ -547,10 +546,10 @@ public class NodeApiTest extends AbstractBaseApiTest
MultiPartRequest reqBody = multiPartBuilder.build(); MultiPartRequest reqBody = multiPartBuilder.build();
// Try to upload into a non-existent folder // Try to upload into a non-existent folder
post(getChildrenUrl(UUID.randomUUID().toString()), user1, new String(reqBody.getBody()), null, reqBody.getContentType(), 404); post(getChildrenUrl(UUID.randomUUID().toString()), user1, reqBody.getBody(), null, reqBody.getContentType(), 404);
// Upload // Upload
response = post(getChildrenUrl(Nodes.PATH_MY), user1, new String(reqBody.getBody()), null, reqBody.getContentType(), 201); response = post(getChildrenUrl(Nodes.PATH_MY), user1, reqBody.getBody(), null, reqBody.getContentType(), 201);
Document document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class); Document document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
// Check the upload response // Check the upload response
assertEquals(fileName, document.getName()); assertEquals(fileName, document.getName());
@@ -576,7 +575,7 @@ public class NodeApiTest extends AbstractBaseApiTest
assertEquals(numOfNodes + 1, pagingResult.getCount().intValue()); assertEquals(numOfNodes + 1, pagingResult.getCount().intValue());
// Upload the same file again to check the name conflicts handling // Upload the same file again to check the name conflicts handling
post(getChildrenUrl(Nodes.PATH_MY), user1, new String(reqBody.getBody()), null, reqBody.getContentType(), 409); post(getChildrenUrl(Nodes.PATH_MY), user1, reqBody.getBody(), null, reqBody.getContentType(), 409);
response = getAll(getChildrenUrl(Nodes.PATH_MY), user1, paging, 200); response = getAll(getChildrenUrl(Nodes.PATH_MY), user1, paging, 200);
pagingResult = parsePaging(response.getJsonResponse()); pagingResult = parsePaging(response.getJsonResponse());
@@ -588,13 +587,13 @@ public class NodeApiTest extends AbstractBaseApiTest
.setAutoRename(true) .setAutoRename(true)
.build(); .build();
response = post(getChildrenUrl(Nodes.PATH_MY), user1, new String(reqBody.getBody()), null, reqBody.getContentType(), 201); response = post(getChildrenUrl(Nodes.PATH_MY), user1, reqBody.getBody(), null, reqBody.getContentType(), 201);
document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class); document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
// Check the upload response // Check the upload response
assertEquals("quick-1.pdf", document.getName()); assertEquals("quick-1.pdf", document.getName());
// upload the same file again, and request the path info to be present in the response // upload the same file again, and request the path info to be present in the response
response = post(getChildrenUrl(Nodes.PATH_MY), user1, new String(reqBody.getBody()), "?select=path", reqBody.getContentType(), 201); response = post(getChildrenUrl(Nodes.PATH_MY), user1, reqBody.getBody(), "?select=path", reqBody.getContentType(), 201);
document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class); document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
// Check the upload response // Check the upload response
assertEquals("quick-2.pdf", document.getName()); assertEquals("quick-2.pdf", document.getName());
@@ -613,7 +612,7 @@ public class NodeApiTest extends AbstractBaseApiTest
reqBody = MultiPartBuilder.create() reqBody = MultiPartBuilder.create()
.setFileData(new FileData(fileName2, file2, MimetypeMap.MIMETYPE_TEXT_PLAIN)) .setFileData(new FileData(fileName2, file2, MimetypeMap.MIMETYPE_TEXT_PLAIN))
.build(); .build();
post(getChildrenUrl(user1Home.getId()), user2, new String(reqBody.getBody()), null, reqBody.getContentType(), 403); post(getChildrenUrl(user1Home.getId()), user2, reqBody.getBody(), null, reqBody.getContentType(), 403);
response = getAll(getChildrenUrl(Nodes.PATH_MY), user1, paging, 200); response = getAll(getChildrenUrl(Nodes.PATH_MY), user1, paging, 200);
pagingResult = parsePaging(response.getJsonResponse()); pagingResult = parsePaging(response.getJsonResponse());
@@ -621,11 +620,11 @@ public class NodeApiTest extends AbstractBaseApiTest
assertEquals("Access Denied. The file shouldn't have been uploaded.", numOfNodes + 3, pagingResult.getCount().intValue()); assertEquals("Access Denied. The file shouldn't have been uploaded.", numOfNodes + 3, pagingResult.getCount().intValue());
// User1 tries to upload a file into a document rather than a folder! // User1 tries to upload a file into a document rather than a folder!
post(getChildrenUrl(document.getId()), user1, new String(reqBody.getBody()), null, reqBody.getContentType(), 400); post(getChildrenUrl(document.getId()), user1, reqBody.getBody(), null, reqBody.getContentType(), 400);
// Try to upload a file without defining the required formData // Try to upload a file without defining the required formData
reqBody = MultiPartBuilder.create().setAutoRename(true).build(); reqBody = MultiPartBuilder.create().setAutoRename(true).build();
post(getChildrenUrl(Nodes.PATH_MY), user1, new String(reqBody.getBody()), null, reqBody.getContentType(), 400); post(getChildrenUrl(Nodes.PATH_MY), user1, reqBody.getBody(), null, reqBody.getContentType(), 400);
// Test unsupported node type // Test unsupported node type
reqBody = MultiPartBuilder.create() reqBody = MultiPartBuilder.create()
@@ -633,7 +632,7 @@ public class NodeApiTest extends AbstractBaseApiTest
.setAutoRename(true) .setAutoRename(true)
.setNodeType("cm:link") .setNodeType("cm:link")
.build(); .build();
post(getChildrenUrl(user1Home.getId()), user1, new String(reqBody.getBody()), null, reqBody.getContentType(), 400); post(getChildrenUrl(user1Home.getId()), user1, reqBody.getBody(), null, reqBody.getContentType(), 400);
} }
@@ -662,7 +661,7 @@ public class NodeApiTest extends AbstractBaseApiTest
.setFileData(new FileData(fileName, file, null)); .setFileData(new FileData(fileName, file, null));
MultiPartRequest reqBody = multiPartBuilder.build(); MultiPartRequest reqBody = multiPartBuilder.build();
// Try to upload // Try to upload
response = post(getChildrenUrl(folderA_Ref), userOneN1.getId(), new String(reqBody.getBody()), null, reqBody.getContentType(), 201); response = post(getChildrenUrl(folderA_Ref), userOneN1.getId(), reqBody.getBody(), null, reqBody.getContentType(), 201);
Document document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class); Document document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
// Check the upload response // Check the upload response
assertEquals(fileName, document.getName()); assertEquals(fileName, document.getName());
@@ -686,7 +685,7 @@ public class NodeApiTest extends AbstractBaseApiTest
assertEquals(numOfNodes + 1, pagingResult.getCount().intValue()); assertEquals(numOfNodes + 1, pagingResult.getCount().intValue());
// Upload the same file again to check the name conflicts handling // Upload the same file again to check the name conflicts handling
post(getChildrenUrl(folderA_Ref), userOneN1.getId(), new String(reqBody.getBody()), null, reqBody.getContentType(), 409); post(getChildrenUrl(folderA_Ref), userOneN1.getId(), reqBody.getBody(), null, reqBody.getContentType(), 409);
response = getAll(getChildrenUrl(folderA_Ref), userOneN1.getId(), paging, 200); response = getAll(getChildrenUrl(folderA_Ref), userOneN1.getId(), paging, 200);
pagingResult = parsePaging(response.getJsonResponse()); pagingResult = parsePaging(response.getJsonResponse());
@@ -699,10 +698,10 @@ public class NodeApiTest extends AbstractBaseApiTest
.setFileData(new FileData(fileName2, file2, MimetypeMap.MIMETYPE_TEXT_PLAIN)) .setFileData(new FileData(fileName2, file2, MimetypeMap.MIMETYPE_TEXT_PLAIN))
.build(); .build();
// userTwoN1 tries to upload a new file into the folderA of userOneN1 // userTwoN1 tries to upload a new file into the folderA of userOneN1
post(getChildrenUrl(folderA_Ref), userTwoN1.getId(), new String(reqBody.getBody()), null, reqBody.getContentType(), 403); post(getChildrenUrl(folderA_Ref), userTwoN1.getId(), reqBody.getBody(), null, reqBody.getContentType(), 403);
// Test upload with properties // Test upload with properties
response = post(getChildrenUrl(folderA_Ref), userOneN1.getId(), new String(reqBody.getBody()), null, reqBody.getContentType(), 201); response = post(getChildrenUrl(folderA_Ref), userOneN1.getId(), reqBody.getBody(), null, reqBody.getContentType(), 201);
document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class); document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
// Check the upload response // Check the upload response
assertEquals(fileName2, document.getName()); assertEquals(fileName2, document.getName());
@@ -723,7 +722,7 @@ public class NodeApiTest extends AbstractBaseApiTest
.setProperties(props) .setProperties(props)
.build(); .build();
response = post(getChildrenUrl(folderA_Ref), userOneN1.getId(), new String(reqBody.getBody()), null, reqBody.getContentType(), 201); response = post(getChildrenUrl(folderA_Ref), userOneN1.getId(), reqBody.getBody(), null, reqBody.getContentType(), 201);
document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class); document = jacksonUtil.parseEntry(response.getJsonResponse(), Document.class);
// Check the upload response // Check the upload response
// "quick-2-1.txt" => fileName2 + autoRename // "quick-2-1.txt" => fileName2 + autoRename
@@ -744,7 +743,7 @@ public class NodeApiTest extends AbstractBaseApiTest
.setProperties(props) .setProperties(props)
.build(); .build();
// Prop prefix is unknown // Prop prefix is unknown
post(getChildrenUrl(folderA_Ref), userOneN1.getId(), new String(reqBody.getBody()), null, reqBody.getContentType(), 400); post(getChildrenUrl(folderA_Ref), userOneN1.getId(), reqBody.getBody(), null, reqBody.getContentType(), 400);
} }
/** /**
@@ -803,7 +802,7 @@ public class NodeApiTest extends AbstractBaseApiTest
UserInfo expectedUser = new UserInfo(user1, user1+" "+user1); UserInfo expectedUser = new UserInfo(user1, user1+" "+user1);
String postUrl = "nodes/"+myFilesNodeRef.getId()+"/children"; String postUrl = getChildrenUrl(myFilesNodeRef);
Folder f1 = new Folder(); Folder f1 = new Folder();
f1.setName("f1"); f1.setName("f1");
@@ -859,10 +858,10 @@ public class NodeApiTest extends AbstractBaseApiTest
Folder f3 = new Folder(); Folder f3 = new Folder();
f3.setName("f3"); f3.setName("f3");
f3.setNodeType("cm:folder"); f3.setNodeType("cm:folder");
post("nodes/"+personNodeRef.getId()+"/children", user1, toJsonAsStringNonNull(f3), 400); post(getChildrenUrl(personNodeRef), user1, toJsonAsStringNonNull(f3), 400);
// -ve test - unknown parent folder node id // -ve test - unknown parent folder node id
post("nodes/"+UUID.randomUUID().toString()+"/children", user1, toJsonAsStringNonNull(f3), 404); post(getChildrenUrl(UUID.randomUUID().toString()), user1, toJsonAsStringNonNull(f3), 404);
// -ve test - duplicate name // -ve test - duplicate name
post(postUrl, user1, toJsonAsStringNonNull(f1), 409); post(postUrl, user1, toJsonAsStringNonNull(f1), 409);
@@ -883,7 +882,7 @@ public class NodeApiTest extends AbstractBaseApiTest
UserInfo expectedUser = new UserInfo(user1, user1+" "+user1); UserInfo expectedUser = new UserInfo(user1, user1+" "+user1);
String postUrl = "nodes/"+myFilesNodeRef.getId()+"/children"; String postUrl = getChildrenUrl(myFilesNodeRef);
Document d1 = new Document(); Document d1 = new Document();
d1.setName("d1.txt"); d1.setName("d1.txt");
@@ -954,10 +953,10 @@ public class NodeApiTest extends AbstractBaseApiTest
Document d3 = new Document(); Document d3 = new Document();
d3.setName("d3.txt"); d3.setName("d3.txt");
d3.setNodeType("cm:content"); d3.setNodeType("cm:content");
post("nodes/"+personNodeRef.getId()+"/children", user1, toJsonAsStringNonNull(d3), 400); post(getChildrenUrl(personNodeRef), user1, toJsonAsStringNonNull(d3), 400);
// -ve test - unknown parent folder node id // -ve test - unknown parent folder node id
post("nodes/"+UUID.randomUUID().toString()+"/children", user1, toJsonAsStringNonNull(d3), 404); post(getChildrenUrl(UUID.randomUUID().toString()), user1, toJsonAsStringNonNull(d3), 404);
// -ve test - duplicate name // -ve test - duplicate name
post(postUrl, user1, toJsonAsStringNonNull(d1), 409); post(postUrl, user1, toJsonAsStringNonNull(d1), 409);
@@ -978,7 +977,7 @@ public class NodeApiTest extends AbstractBaseApiTest
UserInfo expectedUser = new UserInfo(user1, user1+" "+user1); UserInfo expectedUser = new UserInfo(user1, user1+" "+user1);
String postUrl = "nodes/"+myFilesNodeRef.getId()+"/children"; String postUrl = getChildrenUrl(myFilesNodeRef);
String folderName = "My Folder"; String folderName = "My Folder";
@@ -1195,7 +1194,7 @@ public class NodeApiTest extends AbstractBaseApiTest
assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, docResp.getContent().getMimeType()); assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, docResp.getContent().getMimeType());
// Update content & Download URL // Update content & Download URL
final String url = "nodes/" + docResp.getId() + "/content"; final String url = URL_NODES + docResp.getId() + "/content";
// Update the empty node's content // Update the empty node's content
String content = "The quick brown fox jumps over the lazy dog."; String content = "The quick brown fox jumps over the lazy dog.";
@@ -1204,10 +1203,10 @@ public class NodeApiTest extends AbstractBaseApiTest
BinaryPayload payload = new BinaryPayload(file, MimetypeMap.MIMETYPE_TEXT_PLAIN); BinaryPayload payload = new BinaryPayload(file, MimetypeMap.MIMETYPE_TEXT_PLAIN);
// Try to update a folder! // Try to update a folder!
putBinary("nodes/" + f1_nodeId + "/content", user1, payload, null, null, 400); putBinary(URL_NODES + f1_nodeId + "/content", user1, payload, null, null, 400);
// Try to update a non-existent file // Try to update a non-existent file
putBinary("nodes/" + UUID.randomUUID().toString() + "/content", user1, payload, null, null, 404); putBinary(URL_NODES + UUID.randomUUID().toString() + "/content", user1, payload, null, null, 404);
// Update the empty file // Update the empty file
response = putBinary(url, user1, payload, null, null, 200); response = putBinary(url, user1, payload, null, null, 200);
@@ -1250,6 +1249,81 @@ public class NodeApiTest extends AbstractBaseApiTest
// TODO add test for file/folder links - creating, getting, listing, deleting // TODO add test for file/folder links - creating, getting, listing, deleting
/**
* 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
{
//
// Test plain text
//
String fileName = "quick-1.txt";
File file = getResourceFile(fileName);
MultiPartBuilder multiPartBuilder = MultiPartBuilder.create()
.setFileData(new FileData(fileName, file, MimetypeMap.MIMETYPE_TEXT_PLAIN));
MultiPartRequest reqBody = multiPartBuilder.build();
// Upload text content
HttpResponse response = post(getChildrenUrl(Nodes.PATH_MY), user1, reqBody.getBody(), null, reqBody.getContentType(), 201);
Document document = jacksonUtil.parseEntry(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, user1, contentNodeId+"/content", null, 200);
String textContent = response.getResponse();
assertEquals("The quick brown fox jumps over the lazy dog", textContent);
assertEquals("attachment; filename=\"quick-1.txt\"; filename*=UTF-8''quick-1.txt", response.getHeaders().get("Content-Disposition"));
//
// 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, MimetypeMap.MIMETYPE_PDF));
reqBody = multiPartBuilder.build();
// Upload binary content
response = post(getChildrenUrl(Nodes.PATH_MY), user1, reqBody.getBody(), null, reqBody.getContentType(), 201);
document = jacksonUtil.parseEntry(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, user1, contentNodeId+"/content", params, 200);
byte[] bytes = response.getResponseAsBytes();
assertArrayEquals(originalBytes, bytes);
assertNull(response.getHeaders().get("Content-Disposition"));
}
private String getChildrenUrl(NodeRef parentNodeRef) private String getChildrenUrl(NodeRef parentNodeRef)
{ {
return getChildrenUrl(parentNodeRef.getId()); return getChildrenUrl(parentNodeRef.getId());
@@ -1257,7 +1331,7 @@ public class NodeApiTest extends AbstractBaseApiTest
private String getChildrenUrl(String parentId) private String getChildrenUrl(String parentId)
{ {
return "nodes/" + parentId + "/children"; return URL_NODES + parentId + "/children";
} }
private File getResourceFile(String fileName) throws FileNotFoundException private File getResourceFile(String fileName) throws FileNotFoundException

View File

@@ -28,33 +28,35 @@ package org.alfresco.rest.api.tests.client;
import java.util.Map; import java.util.Map;
import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.URIException; import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.util.EncodingUtil;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
public class HttpResponse public class HttpResponse
{ {
private HttpMethod method; protected HttpMethod method;
private String user; private String user;
private String response; private byte[] responseBytes;
private Map<String,String> headers; private Map<String,String> headers;
private long time; private long time;
public HttpResponse(HttpMethod method, String user, String response, Map<String,String> headers, long time) public HttpResponse(HttpMethod method, String user, byte[] responseBytes, Map<String,String> headers, long time)
{ {
super();
this.method = method; this.method = method;
this.user = user; this.user = user;
this.time = time; this.time = time;
this.headers = headers; this.headers = headers;
this.response = response; this.responseBytes = responseBytes;
} }
public int getStatusCode() public int getStatusCode()
@@ -64,8 +66,28 @@ public class HttpResponse
public String getResponse() public String getResponse()
{ {
return response; if (responseBytes != null)
{
if (method instanceof HttpMethodBase)
{
// mimic method.getResponseBodyAsString
return EncodingUtil.getString(responseBytes, ((HttpMethodBase)method).getResponseCharSet());
}
else
{
return new String(responseBytes);
}
}
else
{
return null;
}
} }
public byte[] getResponseAsBytes()
{
return responseBytes;
}
public Map<String,String> getHeaders() public Map<String,String> getHeaders()
{ {
@@ -77,53 +99,69 @@ public class HttpResponse
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
String requestType = null; String requestType = null;
String requestBody = null; RequestEntity requestEntity = null;
if(method instanceof GetMethod)
if (method instanceof GetMethod)
{ {
requestType = "GET"; requestType = "GET";
} }
else if (method instanceof PutMethod) else if (method instanceof PutMethod)
{ {
requestType = "PUT"; requestType = "PUT";
RequestEntity requestEntity = ((PutMethod) method).getRequestEntity(); requestEntity = ((PutMethod) method).getRequestEntity();
if (requestEntity instanceof StringRequestEntity)
{
StringRequestEntity stringRequestEntity = (StringRequestEntity) requestEntity;
requestBody = stringRequestEntity.getContent();
}
else if (requestEntity != null)
{
requestBody = requestEntity.toString();
}
} }
else if(method instanceof PostMethod) else if (method instanceof PostMethod)
{ {
requestType = "POST"; requestType = "POST";
StringRequestEntity requestEntity = (StringRequestEntity)((PostMethod)method).getRequestEntity(); requestEntity = ((PostMethod)method).getRequestEntity();
if(requestEntity != null)
{
requestBody = requestEntity.getContent();
}
} }
else if(method instanceof DeleteMethod) else if (method instanceof DeleteMethod)
{ {
requestType = "DELETE"; requestType = "DELETE";
} }
try try
{ {
sb.append(requestType + " request " + method.getURI()); sb.append(requestType).append(" request ").append(method.getURI()).append("\n");
sb.append("\n");
} }
catch (URIException e) catch (URIException e)
{ {
} }
sb.append(requestBody != null ? " \nbody = " + requestBody + "\n" : "");
sb.append("user " + user); if (requestEntity != null)
sb.append("\n"); {
sb.append("returned " + method.getStatusCode() + " and took " + time + "ms"); sb.append("\nRequest body: ");
sb.append("\n"); if (requestEntity instanceof StringRequestEntity)
sb.append("Response content " + response); {
sb.append(((StringRequestEntity)requestEntity).getContent());
}
else if (requestEntity instanceof ByteArrayRequestEntity)
{
sb.append(" << ").append(((ByteArrayRequestEntity)requestEntity).getContent().length).append(" bytes >>");
}
sb.append("\n");
}
sb.append("user ").append(user).append("\n");
sb.append("returned ").append(method.getStatusCode()).append(" and took ").append(time).append("ms").append("\n");
String contentType = method.getResponseHeader("Content-Type").getValue();
sb.append("Response content type: ").append(contentType).append("\n");
if (contentType != null)
{
sb.append("\nResponse body: ");
if (contentType.startsWith("text/plain") || contentType.startsWith("application/json"))
{
sb.append(getResponse());
}
else
{
sb.append(" << ").append(getResponseAsBytes().length).append(" bytes >>");
}
sb.append("\n");
}
return sb.toString(); return sb.toString();
} }
@@ -133,9 +171,10 @@ public class HttpResponse
try try
{ {
if(response != null && response instanceof String) String response = getResponse();
if (response != null)
{ {
Object object = new JSONParser().parse((String)response); Object object = new JSONParser().parse(response);
if(object instanceof JSONObject) if(object instanceof JSONObject)
{ {
return (JSONObject) object; return (JSONObject) object;

View File

@@ -477,6 +477,18 @@ public class PublicApiClient
return response; return response;
} }
public HttpResponse post(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId,
byte[] body, String contentType) throws IOException
{
HttpResponse response = client.post(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName,
relationshipEntityId != null ? relationshipEntityId.toString() : null, body, contentType);
logger.debug(response.toString());
return response;
}
public HttpResponse post(String urlSuffix, String body) throws IOException public HttpResponse post(String urlSuffix, String body) throws IOException
{ {
HttpResponse response = client.post(getRequestContext(), urlSuffix, body); HttpResponse response = client.post(getRequestContext(), urlSuffix, body);

View File

@@ -54,6 +54,7 @@ import org.alfresco.util.Pair;
import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.httpclient.methods.HeadMethod;
@@ -252,7 +253,7 @@ public class PublicApiHttpClient
} }
} }
return new HttpResponse(method, rq.getRunAsUser(), method.getResponseBodyAsString(), headersMap, (end - start)); return new HttpResponse(method, rq.getRunAsUser(), method.getResponseBody(), headersMap, (end - start));
} }
@Override @Override
@@ -513,6 +514,32 @@ public class PublicApiHttpClient
return submitRequest(req, rq); return submitRequest(req, rq);
} }
public HttpResponse post(final RequestContext rq, final String scope, final String entityCollectionName, final Object entityId,
final String relationCollectionName, final Object relationshipEntityId, final byte[] body, String contentType) throws IOException
{
return post(rq, scope, 1, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, body, contentType);
}
public HttpResponse post(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId,
final String relationCollectionName, final Object relationshipEntityId, final byte[] body, String contentType) throws IOException
{
RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName,
relationshipEntityId, null);
String url = endpoint.getUrl();
PostMethod req = new PostMethod(url.toString());
if (body != null)
{
if (contentType == null || contentType.isEmpty())
{
contentType = "application/octet-stream";
}
ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(body, contentType);
req.setRequestEntity(requestEntity);
}
return submitRequest(req, rq);
}
public HttpResponse delete(final Class<?> c, final RequestContext rq, final Object entityId, final Object relationshipEntityId) throws IOException public HttpResponse delete(final Class<?> c, final RequestContext rq, final Object entityId, final Object relationshipEntityId) throws IOException
{ {
RestApiEndpoint endpoint = new RestApiEndpoint(c, rq.getNetworkId(), entityId, relationshipEntityId, null); RestApiEndpoint endpoint = new RestApiEndpoint(c, rq.getNetworkId(), entityId, relationshipEntityId, null);