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

125783 rmunteanu: Merged 5.1.N (5.1.2) to 5.2.N (5.2.1)
      125605 rmunteanu: Merged 5.1.1 (5.1.1) to 5.1.N (5.1.2)
         125498 slanglois: MNT-16155 Update source headers - remove svn:eol-style property on Java and JSP source files


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@127809 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Alan Davis
2016-06-03 16:45:04 +00:00
parent da8101a5ba
commit 19fcf2c411
325 changed files with 59952 additions and 59952 deletions

View File

@@ -1,230 +1,230 @@
package org.alfresco.repo.web.scripts;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.util.PropertyMap;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.DeleteRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* Junit test for login / logout and validate web scripts
*
* testing uri /api/login
*/
public class LoginTest extends BaseWebScriptTest
{
private MutableAuthenticationService authenticationService;
private AuthenticationComponent authenticationComponent;
private PersonService personService;
private static final String USER_ONE = "AuthenticationTestOne";
protected void setUp() throws Exception
{
super.setUp();
this.authenticationService = (MutableAuthenticationService)getServer().getApplicationContext().getBean("AuthenticationService");
this.authenticationComponent = (AuthenticationComponent)getServer().getApplicationContext().getBean("authenticationComponent");
this.personService = (PersonService)getServer().getApplicationContext().getBean("PersonService");
this.authenticationComponent.setSystemUserAsCurrentUser();
createUser(USER_ONE, USER_ONE);
}
protected void tearDown() throws Exception
{
super.tearDown();
}
private void createUser(String userName, String password)
{
if (this.authenticationService.authenticationExists(userName) == false)
{
this.authenticationService.createAuthentication(userName, password.toCharArray());
PropertyMap ppOne = new PropertyMap(4);
ppOne.put(ContentModel.PROP_USERNAME, userName);
ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
ppOne.put(ContentModel.PROP_EMAIL, "email@email.com");
ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");
this.personService.createPerson(ppOne);
}
}
private String parseTicket(String ticketResult)
{
int startTag = ticketResult.indexOf("<ticket>");
int endTag = ticketResult.indexOf("</ticket>");
if ((startTag != -1) && (endTag != -1))
{
return ticketResult.substring(startTag+("<ticket>".length()), endTag);
}
return "";
}
/**
* Positive test - login and retrieve a ticket via get - return xml,
* - via get method
* validate ticket
* logout
* fail to validate ticket
* fail to get ticket
*/
public void testAuthentication() throws Exception
{
/**
* Login via get method to return xml
*/
String loginURL = "/api/login?u=" + USER_ONE + "&pw=" + USER_ONE;
Response resp = sendRequest(new GetRequest(loginURL), Status.STATUS_OK);
String xmlFragment = resp.getContentAsString();
assertNotNull("xmlFragment");
assertTrue("xmlFragment contains ticket", xmlFragment.contains("<ticket>"));
String ticket = parseTicket(xmlFragment);
String ticketURL = "/api/login/ticket/"+ticket;
/**
* Negative test - validate as AuthenticationUtil.getAdminUserName() - should fail with a 404
*/
setDefaultRunAs(AuthenticationUtil.getAdminUserName());
sendRequest(new GetRequest(ticketURL), Status.STATUS_NOT_FOUND);
/**
* Validate the ticket - should succeed
*/
setDefaultRunAs(USER_ONE);
sendRequest(new GetRequest(ticketURL), Status.STATUS_OK);
/**
* Logout
*/
sendRequest(new DeleteRequest(ticketURL), Status.STATUS_OK);
/**
* Validate the ticket - should fail now
*/
sendRequest(new GetRequest(ticketURL), Status.STATUS_NOT_FOUND);
}
/**
* Positive test - login and retrieve a ticket,
* - via json method
*/
public void testAuthenticationGetJSON() throws Exception
{
/**
* Login via get method to return json
*/
String loginURL = "/api/login.json?u=" + USER_ONE + "&pw=" + USER_ONE ;
Response resp = sendRequest(new GetRequest(loginURL), Status.STATUS_OK);
JSONObject result = new JSONObject(resp.getContentAsString());
JSONObject data = result.getJSONObject("data");
String ticket = data.getString("ticket");
assertNotNull("ticket is null", ticket);
/**
* This is now testing the framework ... With a different format.
*/
String login2URL = "/api/login?u=" + USER_ONE + "&pw=" + USER_ONE + "&format=json";
Response resp2 = sendRequest(new GetRequest(login2URL), Status.STATUS_OK);
JSONObject result2 = new JSONObject(resp2.getContentAsString());
JSONObject data2 = result2.getJSONObject("data");
String ticket2 = data2.getString("ticket");
assertNotNull("ticket is null", ticket2);
}
/**
* Authenticate via a POST
* @throws Exception
*/
public void testPostLogin() throws Exception
{
String loginURL = "/api/login";
/**
* logon via POST and JSON
*/
{
JSONObject req = new JSONObject();
req.put("username", USER_ONE);
req.put("password", USER_ONE);
Response response = sendRequest(new PostRequest(loginURL, req.toString(), "application/json"), Status.STATUS_OK);
JSONObject result = new JSONObject(response.getContentAsString());
JSONObject data = result.getJSONObject("data");
String ticket = data.getString("ticket");
assertNotNull("ticket null", ticket);
}
/**
* Negative test - wrong password
*/
{
JSONObject req = new JSONObject();
req.put("username", USER_ONE);
req.put("password", "blurb");
sendRequest(new PostRequest(loginURL, req.toString(), "application/json"), Status.STATUS_FORBIDDEN);
}
/**
* Negative test - missing username
*/
{
JSONObject req = new JSONObject();
req.put("password", USER_ONE);
sendRequest(new PostRequest(loginURL, req.toString(), "application/json"), Status.STATUS_BAD_REQUEST);
}
/**
* Negative test - missing password
*/
{
JSONObject req = new JSONObject();
req.put("username", USER_ONE);
sendRequest(new PostRequest(loginURL, req.toString(), "application/json"), Status.STATUS_BAD_REQUEST);
}
}
/**
* Negative tests - wrong password
*/
public void testWrongPassword() throws Exception
{
/**
* Login via get method and wrong password, should get FORBIDDEN
*/
String loginURL = "/api/login?u=" + USER_ONE + "&pw=" + "crap";
sendRequest(new GetRequest(loginURL), Status.STATUS_FORBIDDEN);
}
/**
* Negative test - missing parameters
*/
public void testMissingParameters() throws Exception
{
/**
* Login via get method missing pw
*/
String loginURL = "/api/login?u=" + USER_ONE;
sendRequest(new GetRequest(loginURL), Status.STATUS_BAD_REQUEST);
/**
* Login via get method missing u
*/
String login2URL = "/api/login?&pw=" + USER_ONE;
sendRequest(new GetRequest(login2URL), Status.STATUS_BAD_REQUEST);
}
}
package org.alfresco.repo.web.scripts;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.util.PropertyMap;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.DeleteRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* Junit test for login / logout and validate web scripts
*
* testing uri /api/login
*/
public class LoginTest extends BaseWebScriptTest
{
private MutableAuthenticationService authenticationService;
private AuthenticationComponent authenticationComponent;
private PersonService personService;
private static final String USER_ONE = "AuthenticationTestOne";
protected void setUp() throws Exception
{
super.setUp();
this.authenticationService = (MutableAuthenticationService)getServer().getApplicationContext().getBean("AuthenticationService");
this.authenticationComponent = (AuthenticationComponent)getServer().getApplicationContext().getBean("authenticationComponent");
this.personService = (PersonService)getServer().getApplicationContext().getBean("PersonService");
this.authenticationComponent.setSystemUserAsCurrentUser();
createUser(USER_ONE, USER_ONE);
}
protected void tearDown() throws Exception
{
super.tearDown();
}
private void createUser(String userName, String password)
{
if (this.authenticationService.authenticationExists(userName) == false)
{
this.authenticationService.createAuthentication(userName, password.toCharArray());
PropertyMap ppOne = new PropertyMap(4);
ppOne.put(ContentModel.PROP_USERNAME, userName);
ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
ppOne.put(ContentModel.PROP_EMAIL, "email@email.com");
ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");
this.personService.createPerson(ppOne);
}
}
private String parseTicket(String ticketResult)
{
int startTag = ticketResult.indexOf("<ticket>");
int endTag = ticketResult.indexOf("</ticket>");
if ((startTag != -1) && (endTag != -1))
{
return ticketResult.substring(startTag+("<ticket>".length()), endTag);
}
return "";
}
/**
* Positive test - login and retrieve a ticket via get - return xml,
* - via get method
* validate ticket
* logout
* fail to validate ticket
* fail to get ticket
*/
public void testAuthentication() throws Exception
{
/**
* Login via get method to return xml
*/
String loginURL = "/api/login?u=" + USER_ONE + "&pw=" + USER_ONE;
Response resp = sendRequest(new GetRequest(loginURL), Status.STATUS_OK);
String xmlFragment = resp.getContentAsString();
assertNotNull("xmlFragment");
assertTrue("xmlFragment contains ticket", xmlFragment.contains("<ticket>"));
String ticket = parseTicket(xmlFragment);
String ticketURL = "/api/login/ticket/"+ticket;
/**
* Negative test - validate as AuthenticationUtil.getAdminUserName() - should fail with a 404
*/
setDefaultRunAs(AuthenticationUtil.getAdminUserName());
sendRequest(new GetRequest(ticketURL), Status.STATUS_NOT_FOUND);
/**
* Validate the ticket - should succeed
*/
setDefaultRunAs(USER_ONE);
sendRequest(new GetRequest(ticketURL), Status.STATUS_OK);
/**
* Logout
*/
sendRequest(new DeleteRequest(ticketURL), Status.STATUS_OK);
/**
* Validate the ticket - should fail now
*/
sendRequest(new GetRequest(ticketURL), Status.STATUS_NOT_FOUND);
}
/**
* Positive test - login and retrieve a ticket,
* - via json method
*/
public void testAuthenticationGetJSON() throws Exception
{
/**
* Login via get method to return json
*/
String loginURL = "/api/login.json?u=" + USER_ONE + "&pw=" + USER_ONE ;
Response resp = sendRequest(new GetRequest(loginURL), Status.STATUS_OK);
JSONObject result = new JSONObject(resp.getContentAsString());
JSONObject data = result.getJSONObject("data");
String ticket = data.getString("ticket");
assertNotNull("ticket is null", ticket);
/**
* This is now testing the framework ... With a different format.
*/
String login2URL = "/api/login?u=" + USER_ONE + "&pw=" + USER_ONE + "&format=json";
Response resp2 = sendRequest(new GetRequest(login2URL), Status.STATUS_OK);
JSONObject result2 = new JSONObject(resp2.getContentAsString());
JSONObject data2 = result2.getJSONObject("data");
String ticket2 = data2.getString("ticket");
assertNotNull("ticket is null", ticket2);
}
/**
* Authenticate via a POST
* @throws Exception
*/
public void testPostLogin() throws Exception
{
String loginURL = "/api/login";
/**
* logon via POST and JSON
*/
{
JSONObject req = new JSONObject();
req.put("username", USER_ONE);
req.put("password", USER_ONE);
Response response = sendRequest(new PostRequest(loginURL, req.toString(), "application/json"), Status.STATUS_OK);
JSONObject result = new JSONObject(response.getContentAsString());
JSONObject data = result.getJSONObject("data");
String ticket = data.getString("ticket");
assertNotNull("ticket null", ticket);
}
/**
* Negative test - wrong password
*/
{
JSONObject req = new JSONObject();
req.put("username", USER_ONE);
req.put("password", "blurb");
sendRequest(new PostRequest(loginURL, req.toString(), "application/json"), Status.STATUS_FORBIDDEN);
}
/**
* Negative test - missing username
*/
{
JSONObject req = new JSONObject();
req.put("password", USER_ONE);
sendRequest(new PostRequest(loginURL, req.toString(), "application/json"), Status.STATUS_BAD_REQUEST);
}
/**
* Negative test - missing password
*/
{
JSONObject req = new JSONObject();
req.put("username", USER_ONE);
sendRequest(new PostRequest(loginURL, req.toString(), "application/json"), Status.STATUS_BAD_REQUEST);
}
}
/**
* Negative tests - wrong password
*/
public void testWrongPassword() throws Exception
{
/**
* Login via get method and wrong password, should get FORBIDDEN
*/
String loginURL = "/api/login?u=" + USER_ONE + "&pw=" + "crap";
sendRequest(new GetRequest(loginURL), Status.STATUS_FORBIDDEN);
}
/**
* Negative test - missing parameters
*/
public void testMissingParameters() throws Exception
{
/**
* Login via get method missing pw
*/
String loginURL = "/api/login?u=" + USER_ONE;
sendRequest(new GetRequest(loginURL), Status.STATUS_BAD_REQUEST);
/**
* Login via get method missing u
*/
String login2URL = "/api/login?&pw=" + USER_ONE;
sendRequest(new GetRequest(login2URL), Status.STATUS_BAD_REQUEST);
}
}

View File

@@ -1,162 +1,162 @@
package org.alfresco.repo.web.scripts;
import java.util.List;
import org.alfresco.repo.node.archive.NodeArchiveService;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.site.SiteInfo;
import org.alfresco.service.cmr.site.SiteService;
import org.alfresco.service.cmr.site.SiteVisibility;
import org.alfresco.service.transaction.TransactionService;
import org.springframework.context.ApplicationContext;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* Set of tests that ensure GET REST APIs are run successfully in a read-only
* transaction (ALF-10179).
*
* Some webscripts have a side effect of creating a "container" these tests
* are to ensure this is handled gracefully in a way that allows the main
* transaction to be declared as readonly for performance reasons.
*
* @author Gavin Cornwell
* @since 4.0
*/
public class ReadOnlyTransactionInGetRestApiTest extends BaseWebScriptTest
{
private static final String TEST_SITE_NAME = "readOnlyTestSite";
private static final String URL_GET_SITE_BLOG = "/api/blog/site/" + TEST_SITE_NAME + "/blog";
private static final String URL_GET_SITE_FORUM_POSTS = "/api/forum/site/" + TEST_SITE_NAME + "/discussions/posts";
private static final String URL_GET_SITE_LINKS = "/api/links/site/" + TEST_SITE_NAME + "/links?page=1&pageSize=10";
private static final String URL_GET_SITE_LINK = "/api/links/link/site/" + TEST_SITE_NAME + "/links/123456789";
private static final String URL_GET_SITE_TAGS = "/api/tagscopes/site/" + TEST_SITE_NAME + "/tags";
private SiteService siteService;
private NodeService nodeService;
private TransactionService transactionService;
private NodeArchiveService nodeArchiveService;
private NodeRef testSiteNodeRef;
private String testSiteNodeRefString;
private boolean logEnabled = false;
@Override
protected void setUp() throws Exception
{
super.setUp();
ApplicationContext appContext = getServer().getApplicationContext();
this.siteService = (SiteService)appContext.getBean("SiteService");
this.nodeService = (NodeService)appContext.getBean("NodeService");
this.transactionService = (TransactionService)appContext.getBean("TransactionService");
this.nodeArchiveService = (NodeArchiveService)getServer().getApplicationContext().getBean("nodeArchiveService");
// set admin as current user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// delete the test site if it's still hanging around from previous runs
SiteInfo site = siteService.getSite(TEST_SITE_NAME);
if (site != null)
{
siteService.deleteSite(TEST_SITE_NAME);
nodeArchiveService.purgeArchivedNode(nodeArchiveService.getArchivedNode(site.getNodeRef()));
}
// create the test site, this should create a site but it won't have any containers created
SiteInfo siteInfo = this.siteService.createSite("collaboration", TEST_SITE_NAME, "Read Only Test Site",
"Test site for ReadOnlyTransactionRestApiTest", SiteVisibility.PUBLIC);
this.testSiteNodeRef = siteInfo.getNodeRef();
this.testSiteNodeRefString = this.testSiteNodeRef.toString().replace("://", "/");
// ensure there are no containers present at the start of the test
List<ChildAssociationRef> children = nodeService.getChildAssocs(this.testSiteNodeRef);
assertTrue("The test site should not have any containers", children.isEmpty());
}
/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception
{
super.tearDown();
SiteInfo site = siteService.getSite(TEST_SITE_NAME);
// use retrying transaction to delete the site
this.transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
// delete the test site
siteService.deleteSite(TEST_SITE_NAME);
return null;
}
});
nodeArchiveService.purgeArchivedNode(nodeArchiveService.getArchivedNode(site.getNodeRef()));
AuthenticationUtil.clearCurrentSecurityContext();
}
public void testGetSiteBlog() throws Exception
{
// TODO: Fixme - This REST API still requires a readwrite transaction to be successful
// Also add tests for all other blog GET REST APIs
Response response = sendRequest(new GetRequest(URL_GET_SITE_BLOG), 200);
logResponse(response);
assertEquals(Status.STATUS_OK, response.getStatus());
}
public void testGetSiteForumPosts() throws Exception
{
Response response = sendRequest(new GetRequest(URL_GET_SITE_FORUM_POSTS), 200);
logResponse(response);
assertEquals(Status.STATUS_OK, response.getStatus());
}
public void testGetSiteLinks() throws Exception
{
Response response = sendRequest(new GetRequest(URL_GET_SITE_LINKS), 200);
logResponse(response);
assertEquals(Status.STATUS_OK, response.getStatus());
}
public void testGetSiteLink() throws Exception
{
Response response = sendRequest(new GetRequest(URL_GET_SITE_LINK), 404);
logResponse(response);
assertEquals(Status.STATUS_NOT_FOUND, response.getStatus());
}
public void testGetSiteTags() throws Exception
{
Response response = sendRequest(new GetRequest(URL_GET_SITE_TAGS), 200);
logResponse(response);
assertEquals(Status.STATUS_OK, response.getStatus());
}
private void logResponse(Response response)
{
if (this.logEnabled)
{
try
{
System.out.println(response.getContentAsString());
}
catch (Exception e)
{
System.err.println("Unable to log response: " + e.toString());
}
}
}
}
package org.alfresco.repo.web.scripts;
import java.util.List;
import org.alfresco.repo.node.archive.NodeArchiveService;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.site.SiteInfo;
import org.alfresco.service.cmr.site.SiteService;
import org.alfresco.service.cmr.site.SiteVisibility;
import org.alfresco.service.transaction.TransactionService;
import org.springframework.context.ApplicationContext;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* Set of tests that ensure GET REST APIs are run successfully in a read-only
* transaction (ALF-10179).
*
* Some webscripts have a side effect of creating a "container" these tests
* are to ensure this is handled gracefully in a way that allows the main
* transaction to be declared as readonly for performance reasons.
*
* @author Gavin Cornwell
* @since 4.0
*/
public class ReadOnlyTransactionInGetRestApiTest extends BaseWebScriptTest
{
private static final String TEST_SITE_NAME = "readOnlyTestSite";
private static final String URL_GET_SITE_BLOG = "/api/blog/site/" + TEST_SITE_NAME + "/blog";
private static final String URL_GET_SITE_FORUM_POSTS = "/api/forum/site/" + TEST_SITE_NAME + "/discussions/posts";
private static final String URL_GET_SITE_LINKS = "/api/links/site/" + TEST_SITE_NAME + "/links?page=1&pageSize=10";
private static final String URL_GET_SITE_LINK = "/api/links/link/site/" + TEST_SITE_NAME + "/links/123456789";
private static final String URL_GET_SITE_TAGS = "/api/tagscopes/site/" + TEST_SITE_NAME + "/tags";
private SiteService siteService;
private NodeService nodeService;
private TransactionService transactionService;
private NodeArchiveService nodeArchiveService;
private NodeRef testSiteNodeRef;
private String testSiteNodeRefString;
private boolean logEnabled = false;
@Override
protected void setUp() throws Exception
{
super.setUp();
ApplicationContext appContext = getServer().getApplicationContext();
this.siteService = (SiteService)appContext.getBean("SiteService");
this.nodeService = (NodeService)appContext.getBean("NodeService");
this.transactionService = (TransactionService)appContext.getBean("TransactionService");
this.nodeArchiveService = (NodeArchiveService)getServer().getApplicationContext().getBean("nodeArchiveService");
// set admin as current user
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
// delete the test site if it's still hanging around from previous runs
SiteInfo site = siteService.getSite(TEST_SITE_NAME);
if (site != null)
{
siteService.deleteSite(TEST_SITE_NAME);
nodeArchiveService.purgeArchivedNode(nodeArchiveService.getArchivedNode(site.getNodeRef()));
}
// create the test site, this should create a site but it won't have any containers created
SiteInfo siteInfo = this.siteService.createSite("collaboration", TEST_SITE_NAME, "Read Only Test Site",
"Test site for ReadOnlyTransactionRestApiTest", SiteVisibility.PUBLIC);
this.testSiteNodeRef = siteInfo.getNodeRef();
this.testSiteNodeRefString = this.testSiteNodeRef.toString().replace("://", "/");
// ensure there are no containers present at the start of the test
List<ChildAssociationRef> children = nodeService.getChildAssocs(this.testSiteNodeRef);
assertTrue("The test site should not have any containers", children.isEmpty());
}
/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception
{
super.tearDown();
SiteInfo site = siteService.getSite(TEST_SITE_NAME);
// use retrying transaction to delete the site
this.transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
// delete the test site
siteService.deleteSite(TEST_SITE_NAME);
return null;
}
});
nodeArchiveService.purgeArchivedNode(nodeArchiveService.getArchivedNode(site.getNodeRef()));
AuthenticationUtil.clearCurrentSecurityContext();
}
public void testGetSiteBlog() throws Exception
{
// TODO: Fixme - This REST API still requires a readwrite transaction to be successful
// Also add tests for all other blog GET REST APIs
Response response = sendRequest(new GetRequest(URL_GET_SITE_BLOG), 200);
logResponse(response);
assertEquals(Status.STATUS_OK, response.getStatus());
}
public void testGetSiteForumPosts() throws Exception
{
Response response = sendRequest(new GetRequest(URL_GET_SITE_FORUM_POSTS), 200);
logResponse(response);
assertEquals(Status.STATUS_OK, response.getStatus());
}
public void testGetSiteLinks() throws Exception
{
Response response = sendRequest(new GetRequest(URL_GET_SITE_LINKS), 200);
logResponse(response);
assertEquals(Status.STATUS_OK, response.getStatus());
}
public void testGetSiteLink() throws Exception
{
Response response = sendRequest(new GetRequest(URL_GET_SITE_LINK), 404);
logResponse(response);
assertEquals(Status.STATUS_NOT_FOUND, response.getStatus());
}
public void testGetSiteTags() throws Exception
{
Response response = sendRequest(new GetRequest(URL_GET_SITE_TAGS), 200);
logResponse(response);
assertEquals(Status.STATUS_OK, response.getStatus());
}
private void logResponse(Response response)
{
if (this.logEnabled)
{
try
{
System.out.println(response.getContentAsString());
}
catch (Exception e)
{
System.err.println("Unable to log response: " + e.toString());
}
}
}
}

View File

@@ -1,65 +1,65 @@
package org.alfresco.repo.web.scripts.content;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.transform.ContentTransformerRegistry;
import org.alfresco.repo.content.transform.PdfBoxContentTransformer;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.springframework.context.ApplicationContext;
/**
* Tests the {@link MimetypesGet} endpoint
*/
public class MimetypesGetTest extends BaseWebScriptTest
{
private ApplicationContext ctx;
private ContentTransformerRegistry contentTransformerRegistry;
@Override
protected void setUp() throws Exception
{
super.setUp();
ctx = getServer().getApplicationContext();
contentTransformerRegistry = (ContentTransformerRegistry) ctx.getBean("contentTransformerRegistry");
}
/**
* Tests the <code>mimetypesGet.getTransformer</code> method directly for
* varefication of label text
*
* @throws Exception
*/
public void testGetTransformer() throws Exception
{
MimetypesGet mimetypesGet = new MimetypesGet();
mimetypesGet.setApplicationContext(ctx);
mimetypesGet.setContentTransformerRegistry(contentTransformerRegistry);
mimetypesGet.afterPropertiesSet();
// Test a Java transformer name
String transformerName = mimetypesGet.getTransformer(MimetypeMap.MIMETYPE_PDF, 1000, MimetypeMap.MIMETYPE_TEXT_PLAIN);
assertEquals(PdfBoxContentTransformer.class.getCanonicalName(), transformerName);
// Test a generic proxy transformer name
transformerName = mimetypesGet.getTransformer(MimetypeMap.MIMETYPE_IMAGE_JPEG, 1000, MimetypeMap.MIMETYPE_IMAGE_PNG);
assertNotNull(transformerName);
assertTrue("Expected transformerName to contain 'Proxy' but was " + transformerName,
transformerName.contains("Proxy via"));
boolean oodirectPresent = ctx.containsBean(MimetypesGet.OODIRECT_WORKER_BEAN);
boolean jodPresent = ctx.containsBean(MimetypesGet.JOD_WORKER_BEAN);
// Test the office transformer name
transformerName = mimetypesGet.getTransformer(MimetypeMap.MIMETYPE_WORD, 1000, MimetypeMap.MIMETYPE_PDF);
assertNotNull(transformerName);
if (oodirectPresent)
{
assertEquals("Using a Direct Open Office Connection", transformerName);
}
else if (jodPresent)
{
assertEquals("Using JOD Converter / Open Office", transformerName);
}
}
}
package org.alfresco.repo.web.scripts.content;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.transform.ContentTransformerRegistry;
import org.alfresco.repo.content.transform.PdfBoxContentTransformer;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.springframework.context.ApplicationContext;
/**
* Tests the {@link MimetypesGet} endpoint
*/
public class MimetypesGetTest extends BaseWebScriptTest
{
private ApplicationContext ctx;
private ContentTransformerRegistry contentTransformerRegistry;
@Override
protected void setUp() throws Exception
{
super.setUp();
ctx = getServer().getApplicationContext();
contentTransformerRegistry = (ContentTransformerRegistry) ctx.getBean("contentTransformerRegistry");
}
/**
* Tests the <code>mimetypesGet.getTransformer</code> method directly for
* varefication of label text
*
* @throws Exception
*/
public void testGetTransformer() throws Exception
{
MimetypesGet mimetypesGet = new MimetypesGet();
mimetypesGet.setApplicationContext(ctx);
mimetypesGet.setContentTransformerRegistry(contentTransformerRegistry);
mimetypesGet.afterPropertiesSet();
// Test a Java transformer name
String transformerName = mimetypesGet.getTransformer(MimetypeMap.MIMETYPE_PDF, 1000, MimetypeMap.MIMETYPE_TEXT_PLAIN);
assertEquals(PdfBoxContentTransformer.class.getCanonicalName(), transformerName);
// Test a generic proxy transformer name
transformerName = mimetypesGet.getTransformer(MimetypeMap.MIMETYPE_IMAGE_JPEG, 1000, MimetypeMap.MIMETYPE_IMAGE_PNG);
assertNotNull(transformerName);
assertTrue("Expected transformerName to contain 'Proxy' but was " + transformerName,
transformerName.contains("Proxy via"));
boolean oodirectPresent = ctx.containsBean(MimetypesGet.OODIRECT_WORKER_BEAN);
boolean jodPresent = ctx.containsBean(MimetypesGet.JOD_WORKER_BEAN);
// Test the office transformer name
transformerName = mimetypesGet.getTransformer(MimetypeMap.MIMETYPE_WORD, 1000, MimetypeMap.MIMETYPE_PDF);
assertNotNull(transformerName);
if (oodirectPresent)
{
assertEquals("Using a Direct Open Office Connection", transformerName);
}
else if (jodPresent)
{
assertEquals("Using JOD Converter / Open Office", transformerName);
}
}
}

View File

@@ -1,118 +1,118 @@
package org.alfresco.repo.web.scripts.search;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.util.PropertyMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* Unit test for PersonSearch Web Script.
*
* /alfresco/service/api/search/person?q=*
* @author Mark Rogers
*/
public class PersonSearchTest extends BaseWebScriptTest
{
private static Log logger = LogFactory.getLog(PersonSearchTest.class);
private MutableAuthenticationService authenticationService;
private AuthenticationComponent authenticationComponent;
private PersonService personService;
private static final String USER_ONE = "PersonSearchTestOne";
private static final String USER_TWO = "PersonSearchTestTwo";
private static final String USER_THREE = "PersonSearchTestThree";
@Override
protected void setUp() throws Exception
{
super.setUp();
this.authenticationService = (MutableAuthenticationService)getServer().getApplicationContext().getBean("AuthenticationService");
this.authenticationComponent = (AuthenticationComponent)getServer().getApplicationContext().getBean("authenticationComponent");
this.personService = (PersonService)getServer().getApplicationContext().getBean("PersonService");
this.authenticationComponent.setSystemUserAsCurrentUser();
// Create users
createUser(USER_ONE);
createUser(USER_TWO);
createUser(USER_THREE);
// Do tests as user one
this.authenticationComponent.setCurrentUser(USER_ONE);
}
private void createUser(String userName)
{
if (this.authenticationService.authenticationExists(userName) == false)
{
this.authenticationService.createAuthentication(userName, "PWD".toCharArray());
PropertyMap ppOne = new PropertyMap(4);
ppOne.put(ContentModel.PROP_USERNAME, userName);
ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
ppOne.put(ContentModel.PROP_EMAIL, "email@email.com");
ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");
this.personService.createPerson(ppOne);
}
}
@Override
protected void tearDown() throws Exception
{
super.tearDown();
this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
}
/**
* This is a basic sanity check of the search/person script.
*/
public void testSearch() throws Exception
{
/*
* Do the first query for default format and all results
*/
{
Response response = sendRequest(new GetRequest("/api/search/person?q=*"), Status.STATUS_OK);
logger.debug(response.getContentAsString());
}
/*
* Same search with HTML format
*/
{
Response response = sendRequest(new GetRequest("/api/search/person.html?q=*"), Status.STATUS_OK);
logger.debug(response.getContentAsString());
}
/*
* Negative test - missing mandatory parameter
*
* Should really be a INVALID_REQUEST
*/
sendRequest(new GetRequest("/api/search/person?"), Status.STATUS_INTERNAL_SERVER_ERROR);
}
public void testPortletSearch() throws Exception
{
Response response = sendRequest(new GetRequest("/api/search/person.portlet?q=*"), Status.STATUS_OK);
logger.debug(response.getContentAsString());
}
public void testAtomSearch() throws Exception
{
Response response = sendRequest(new GetRequest("/api/search/person.atom?q=*"), Status.STATUS_OK);
logger.debug(response.getContentAsString());
}
}
package org.alfresco.repo.web.scripts.search;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.util.PropertyMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* Unit test for PersonSearch Web Script.
*
* /alfresco/service/api/search/person?q=*
* @author Mark Rogers
*/
public class PersonSearchTest extends BaseWebScriptTest
{
private static Log logger = LogFactory.getLog(PersonSearchTest.class);
private MutableAuthenticationService authenticationService;
private AuthenticationComponent authenticationComponent;
private PersonService personService;
private static final String USER_ONE = "PersonSearchTestOne";
private static final String USER_TWO = "PersonSearchTestTwo";
private static final String USER_THREE = "PersonSearchTestThree";
@Override
protected void setUp() throws Exception
{
super.setUp();
this.authenticationService = (MutableAuthenticationService)getServer().getApplicationContext().getBean("AuthenticationService");
this.authenticationComponent = (AuthenticationComponent)getServer().getApplicationContext().getBean("authenticationComponent");
this.personService = (PersonService)getServer().getApplicationContext().getBean("PersonService");
this.authenticationComponent.setSystemUserAsCurrentUser();
// Create users
createUser(USER_ONE);
createUser(USER_TWO);
createUser(USER_THREE);
// Do tests as user one
this.authenticationComponent.setCurrentUser(USER_ONE);
}
private void createUser(String userName)
{
if (this.authenticationService.authenticationExists(userName) == false)
{
this.authenticationService.createAuthentication(userName, "PWD".toCharArray());
PropertyMap ppOne = new PropertyMap(4);
ppOne.put(ContentModel.PROP_USERNAME, userName);
ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
ppOne.put(ContentModel.PROP_EMAIL, "email@email.com");
ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");
this.personService.createPerson(ppOne);
}
}
@Override
protected void tearDown() throws Exception
{
super.tearDown();
this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
}
/**
* This is a basic sanity check of the search/person script.
*/
public void testSearch() throws Exception
{
/*
* Do the first query for default format and all results
*/
{
Response response = sendRequest(new GetRequest("/api/search/person?q=*"), Status.STATUS_OK);
logger.debug(response.getContentAsString());
}
/*
* Same search with HTML format
*/
{
Response response = sendRequest(new GetRequest("/api/search/person.html?q=*"), Status.STATUS_OK);
logger.debug(response.getContentAsString());
}
/*
* Negative test - missing mandatory parameter
*
* Should really be a INVALID_REQUEST
*/
sendRequest(new GetRequest("/api/search/person?"), Status.STATUS_INTERNAL_SERVER_ERROR);
}
public void testPortletSearch() throws Exception
{
Response response = sendRequest(new GetRequest("/api/search/person.portlet?q=*"), Status.STATUS_OK);
logger.debug(response.getContentAsString());
}
public void testAtomSearch() throws Exception
{
Response response = sendRequest(new GetRequest("/api/search/person.atom?q=*"), Status.STATUS_OK);
logger.debug(response.getContentAsString());
}
}

View File

@@ -1,288 +1,288 @@
package org.alfresco.repo.web.scripts.subscriptions;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.util.PropertyMap;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PutRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* Subscription Service REST API tests
*/
public class SubscriptionServiceRestApiTest extends BaseWebScriptTest
{
public static final String USER_BOB = "bob";
public static final String USER_TOM = "tom";
public static final String USER_LISA = "lisa";
private static final String URL_FOLLOW = "/api/subscriptions/{userid}/follow";
private static final String URL_UNFOLLOW = "/api/subscriptions/{userid}/unfollow";
private static final String URL_FOLLOWERS = "/api/subscriptions/{userid}/followers";
private static final String URL_FOLLOWERS_COUNT = "/api/subscriptions/{userid}/followers/count";
private static final String URL_FOLLOWING = "/api/subscriptions/{userid}/following";
private static final String URL_FOLLOWING_COUNT = "/api/subscriptions/{userid}/following/count";
private static final String URL_FOLLOWS = "/api/subscriptions/{userid}/follows";
private static final String URL_PRIVATE = "/api/subscriptions/{userid}/private";
protected PersonService personService;
@Override
public void setUp() throws Exception
{
// Get the required services
personService = (PersonService) getServer().getApplicationContext().getBean("PersonService");
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
createPerson(USER_BOB);
createPerson(USER_TOM);
createPerson(USER_LISA);
}
@Override
protected void tearDown() throws Exception
{
deletePerson(USER_BOB);
deletePerson(USER_TOM);
deletePerson(USER_LISA);
}
protected void deletePerson(String userId)
{
personService.deletePerson(userId);
}
protected NodeRef createPerson(String userId)
{
deletePerson(userId);
PropertyMap properties = new PropertyMap(5);
properties.put(ContentModel.PROP_USERNAME, userId);
properties.put(ContentModel.PROP_FIRSTNAME, userId);
properties.put(ContentModel.PROP_LASTNAME, "Test");
properties.put(ContentModel.PROP_EMAIL, userId + "@test.demo.alfresco.com");
return personService.createPerson(properties);
}
protected String getUrl(String urlPattern, String user)
{
return urlPattern.replaceFirst("\\{userid\\}", user);
}
protected void follow(String user1, String user2) throws Exception
{
JSONArray jsonUsers = new JSONArray();
jsonUsers.put(user2);
String url = getUrl(URL_FOLLOW, user1);
sendRequest(new PostRequest(url, jsonUsers.toString(), "application/json"), Status.STATUS_NO_CONTENT);
}
protected void unfollow(String user1, String user2) throws Exception
{
JSONArray jsonUsers = new JSONArray();
jsonUsers.put(user2);
String url = getUrl(URL_UNFOLLOW, user1);
sendRequest(new PostRequest(url, jsonUsers.toString(), "application/json"), Status.STATUS_NO_CONTENT);
}
protected boolean follows(String user1, String user2) throws Exception
{
JSONArray jsonUsers = new JSONArray();
jsonUsers.put(user2);
String url = getUrl(URL_FOLLOWS, user1);
Response response = sendRequest(new PostRequest(url, jsonUsers.toString(), "application/json"),
Status.STATUS_OK);
JSONArray resultArray = new JSONArray(response.getContentAsString());
assertEquals(1, resultArray.length());
JSONObject resultObject = resultArray.getJSONObject(0);
assertTrue(resultObject.has(user2));
return resultObject.getBoolean(user2);
}
protected int getFollowingCount(String user) throws Exception
{
String url = getUrl(URL_FOLLOWING_COUNT, user);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("count"));
return resultObject.getInt("count");
}
protected int getFollowersCount(String user) throws Exception
{
String url = getUrl(URL_FOLLOWERS_COUNT, user);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("count"));
return resultObject.getInt("count");
}
protected List<String> getFollowing(String user) throws Exception
{
String url = getUrl(URL_FOLLOWING, user);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("people"));
List<String> result = new ArrayList<String>();
JSONArray people = resultObject.getJSONArray("people");
for (int i = 0; i < people.length(); i++)
{
JSONObject person = people.getJSONObject(i);
assertTrue(person.has("userName"));
assertTrue(person.has("firstName"));
assertTrue(person.has("lastName"));
result.add(person.getString("userName"));
}
return result;
}
protected List<String> getFollowers(String user) throws Exception
{
String url = getUrl(URL_FOLLOWERS, user);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("people"));
List<String> result = new ArrayList<String>();
JSONArray people = resultObject.getJSONArray("people");
for (int i = 0; i < people.length(); i++)
{
JSONObject person = people.getJSONObject(i);
assertTrue(person.has("userName"));
assertTrue(person.has("firstName"));
assertTrue(person.has("lastName"));
result.add(person.getString("userName"));
}
return result;
}
protected boolean isSubscriptionListPrivate(String user) throws Exception
{
String url = getUrl(URL_PRIVATE, user);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("private"));
return resultObject.getBoolean("private");
}
protected void setSubscriptionListPrivate(String user, boolean setPrivate) throws Exception
{
JSONObject privateObject = new JSONObject();
privateObject.put("private", setPrivate);
String url = getUrl(URL_PRIVATE, user);
Response response = sendRequest(new PutRequest(url, privateObject.toString(), "application/json"),
Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("private"));
assertEquals(setPrivate, resultObject.getBoolean("private"));
}
public void testFollow() throws Exception
{
String userId1 = USER_BOB;
String userId2 = USER_TOM;
String userId3 = USER_LISA;
// check follows first
if (follows(userId1, userId2))
{
unfollow(userId1, userId2);
}
assertFalse(follows(userId1, userId2));
// count the people user 1 is following
int count = getFollowingCount(userId1);
assertTrue(count >= 0);
// user 1 follows user 2 -- twice (the second follow request should be
// ignored)
follow(userId1, userId2);
follow(userId1, userId2);
assertEquals(count + 1, getFollowingCount(userId1));
assertTrue(follows(userId1, userId2));
// user 1 follows user 3
follow(userId1, userId3);
assertEquals(count + 2, getFollowingCount(userId1));
assertTrue(follows(userId1, userId3));
// get following list of user 1
List<String> following = getFollowing(userId1);
assertNotNull(following);
assertTrue(following.contains(userId2));
assertTrue(following.contains(userId3));
// count followers of user 2
int followerCount = getFollowersCount(userId2);
assertTrue(followerCount > 0);
// get followers of user 2
List<String> followers = getFollowers(userId2);
assertNotNull(followers);
assertTrue(followers.contains(userId1));
// unfollow
unfollow(userId1, userId2);
assertEquals(count + 1, getFollowingCount(userId1));
assertFalse(follows(userId1, userId2));
assertTrue(follows(userId1, userId3));
unfollow(userId1, userId3);
assertEquals(count, getFollowingCount(userId1));
assertFalse(follows(userId1, userId3));
}
public void testPrivateList() throws Exception
{
final String userId1 = USER_BOB;
assertFalse(isSubscriptionListPrivate(userId1));
setSubscriptionListPrivate(userId1, false);
assertFalse(isSubscriptionListPrivate(userId1));
setSubscriptionListPrivate(userId1, true);
assertTrue(isSubscriptionListPrivate(userId1));
setSubscriptionListPrivate(userId1, false);
assertFalse(isSubscriptionListPrivate(userId1));
setSubscriptionListPrivate(userId1, true);
assertTrue(isSubscriptionListPrivate(userId1));
}
}
package org.alfresco.repo.web.scripts.subscriptions;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.web.scripts.BaseWebScriptTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.util.PropertyMap;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.PutRequest;
import org.springframework.extensions.webscripts.TestWebScriptServer.Response;
/**
* Subscription Service REST API tests
*/
public class SubscriptionServiceRestApiTest extends BaseWebScriptTest
{
public static final String USER_BOB = "bob";
public static final String USER_TOM = "tom";
public static final String USER_LISA = "lisa";
private static final String URL_FOLLOW = "/api/subscriptions/{userid}/follow";
private static final String URL_UNFOLLOW = "/api/subscriptions/{userid}/unfollow";
private static final String URL_FOLLOWERS = "/api/subscriptions/{userid}/followers";
private static final String URL_FOLLOWERS_COUNT = "/api/subscriptions/{userid}/followers/count";
private static final String URL_FOLLOWING = "/api/subscriptions/{userid}/following";
private static final String URL_FOLLOWING_COUNT = "/api/subscriptions/{userid}/following/count";
private static final String URL_FOLLOWS = "/api/subscriptions/{userid}/follows";
private static final String URL_PRIVATE = "/api/subscriptions/{userid}/private";
protected PersonService personService;
@Override
public void setUp() throws Exception
{
// Get the required services
personService = (PersonService) getServer().getApplicationContext().getBean("PersonService");
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
createPerson(USER_BOB);
createPerson(USER_TOM);
createPerson(USER_LISA);
}
@Override
protected void tearDown() throws Exception
{
deletePerson(USER_BOB);
deletePerson(USER_TOM);
deletePerson(USER_LISA);
}
protected void deletePerson(String userId)
{
personService.deletePerson(userId);
}
protected NodeRef createPerson(String userId)
{
deletePerson(userId);
PropertyMap properties = new PropertyMap(5);
properties.put(ContentModel.PROP_USERNAME, userId);
properties.put(ContentModel.PROP_FIRSTNAME, userId);
properties.put(ContentModel.PROP_LASTNAME, "Test");
properties.put(ContentModel.PROP_EMAIL, userId + "@test.demo.alfresco.com");
return personService.createPerson(properties);
}
protected String getUrl(String urlPattern, String user)
{
return urlPattern.replaceFirst("\\{userid\\}", user);
}
protected void follow(String user1, String user2) throws Exception
{
JSONArray jsonUsers = new JSONArray();
jsonUsers.put(user2);
String url = getUrl(URL_FOLLOW, user1);
sendRequest(new PostRequest(url, jsonUsers.toString(), "application/json"), Status.STATUS_NO_CONTENT);
}
protected void unfollow(String user1, String user2) throws Exception
{
JSONArray jsonUsers = new JSONArray();
jsonUsers.put(user2);
String url = getUrl(URL_UNFOLLOW, user1);
sendRequest(new PostRequest(url, jsonUsers.toString(), "application/json"), Status.STATUS_NO_CONTENT);
}
protected boolean follows(String user1, String user2) throws Exception
{
JSONArray jsonUsers = new JSONArray();
jsonUsers.put(user2);
String url = getUrl(URL_FOLLOWS, user1);
Response response = sendRequest(new PostRequest(url, jsonUsers.toString(), "application/json"),
Status.STATUS_OK);
JSONArray resultArray = new JSONArray(response.getContentAsString());
assertEquals(1, resultArray.length());
JSONObject resultObject = resultArray.getJSONObject(0);
assertTrue(resultObject.has(user2));
return resultObject.getBoolean(user2);
}
protected int getFollowingCount(String user) throws Exception
{
String url = getUrl(URL_FOLLOWING_COUNT, user);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("count"));
return resultObject.getInt("count");
}
protected int getFollowersCount(String user) throws Exception
{
String url = getUrl(URL_FOLLOWERS_COUNT, user);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("count"));
return resultObject.getInt("count");
}
protected List<String> getFollowing(String user) throws Exception
{
String url = getUrl(URL_FOLLOWING, user);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("people"));
List<String> result = new ArrayList<String>();
JSONArray people = resultObject.getJSONArray("people");
for (int i = 0; i < people.length(); i++)
{
JSONObject person = people.getJSONObject(i);
assertTrue(person.has("userName"));
assertTrue(person.has("firstName"));
assertTrue(person.has("lastName"));
result.add(person.getString("userName"));
}
return result;
}
protected List<String> getFollowers(String user) throws Exception
{
String url = getUrl(URL_FOLLOWERS, user);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("people"));
List<String> result = new ArrayList<String>();
JSONArray people = resultObject.getJSONArray("people");
for (int i = 0; i < people.length(); i++)
{
JSONObject person = people.getJSONObject(i);
assertTrue(person.has("userName"));
assertTrue(person.has("firstName"));
assertTrue(person.has("lastName"));
result.add(person.getString("userName"));
}
return result;
}
protected boolean isSubscriptionListPrivate(String user) throws Exception
{
String url = getUrl(URL_PRIVATE, user);
Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("private"));
return resultObject.getBoolean("private");
}
protected void setSubscriptionListPrivate(String user, boolean setPrivate) throws Exception
{
JSONObject privateObject = new JSONObject();
privateObject.put("private", setPrivate);
String url = getUrl(URL_PRIVATE, user);
Response response = sendRequest(new PutRequest(url, privateObject.toString(), "application/json"),
Status.STATUS_OK);
JSONObject resultObject = new JSONObject(response.getContentAsString());
assertTrue(resultObject.has("private"));
assertEquals(setPrivate, resultObject.getBoolean("private"));
}
public void testFollow() throws Exception
{
String userId1 = USER_BOB;
String userId2 = USER_TOM;
String userId3 = USER_LISA;
// check follows first
if (follows(userId1, userId2))
{
unfollow(userId1, userId2);
}
assertFalse(follows(userId1, userId2));
// count the people user 1 is following
int count = getFollowingCount(userId1);
assertTrue(count >= 0);
// user 1 follows user 2 -- twice (the second follow request should be
// ignored)
follow(userId1, userId2);
follow(userId1, userId2);
assertEquals(count + 1, getFollowingCount(userId1));
assertTrue(follows(userId1, userId2));
// user 1 follows user 3
follow(userId1, userId3);
assertEquals(count + 2, getFollowingCount(userId1));
assertTrue(follows(userId1, userId3));
// get following list of user 1
List<String> following = getFollowing(userId1);
assertNotNull(following);
assertTrue(following.contains(userId2));
assertTrue(following.contains(userId3));
// count followers of user 2
int followerCount = getFollowersCount(userId2);
assertTrue(followerCount > 0);
// get followers of user 2
List<String> followers = getFollowers(userId2);
assertNotNull(followers);
assertTrue(followers.contains(userId1));
// unfollow
unfollow(userId1, userId2);
assertEquals(count + 1, getFollowingCount(userId1));
assertFalse(follows(userId1, userId2));
assertTrue(follows(userId1, userId3));
unfollow(userId1, userId3);
assertEquals(count, getFollowingCount(userId1));
assertFalse(follows(userId1, userId3));
}
public void testPrivateList() throws Exception
{
final String userId1 = USER_BOB;
assertFalse(isSubscriptionListPrivate(userId1));
setSubscriptionListPrivate(userId1, false);
assertFalse(isSubscriptionListPrivate(userId1));
setSubscriptionListPrivate(userId1, true);
assertTrue(isSubscriptionListPrivate(userId1));
setSubscriptionListPrivate(userId1, false);
assertFalse(isSubscriptionListPrivate(userId1));
setSubscriptionListPrivate(userId1, true);
assertTrue(isSubscriptionListPrivate(userId1));
}
}