alfresco-community-repo/source/java/org/alfresco/repo/rating/RatingServiceIntegrationTest.java
N Smith 2980cf9f78 Merging DEV/ACTIVITI_INTEGRATION2 to HEAD
25933: Updated activiti jars to 5.3 release + temporarily disabled query-tests for activtiti
	25932: Fixed failing FormServiceImplTest.
	25930: Fixed ClassCastException and NullPointerException when using JBPM and Activiti tasks in Alfresco Explorer.
	25898: Implemented testGetWorkflows() which tests the methods getWorkflows() getActiveWorkflows() and getCompletedWorkflows() for both workflow engines.
	25888: Fixed failing testOutcome.
	25884: Workflow console fully tested using activiti engine + small bugfixes
	25854: Implemented testGetPathProperties on AbstractWorkflowServiceIntegrationTest. This tests getPathProperties for Activiti and JBPM workflow engines.
	25827: Added lifecycle sample for activiti engine
	25801: Added a new WorkflowRestApiTest testTaskInstancesForWorkflowGet. Also fixed issues with ActivitWorkflowEngine.queryTasks() relating to the start task being returned incorrectly.
	25731: Added timer execution test to verify Authentication and Transactional behavior + added license headers to 2 files
	25682: ALF-6902 delete identitylinks + added timer sample + adhoc notify me feature
	25649: Redeploying of parallel activiti WF's turned of (remainder from development)
	25645: Fixing getWorkflows test, using valid date to check "due before"
	25642: Implemented getPathProperties() on ActivitiWorkflowEngine. Also refactored ActivitiTypeConverter to create ActivitiPropertyConverter which uses a WorkflowPropertyHandlerRegistry.
	25636: Fixes for use of Activiti workflows in JSF client
	25615: Added parallel review and approve process (regular + grouped)
	25520: Added REST-test for review workflow and pooled review workflow for both engines
	25471: Added queryTasks test for both engines
	25397: Testing getTimers() on both engines
	25368: Using authorityName instead of name for candidate-group + fixed priority WF vs. Task mixup in start-task
	25335: F96: A form control for LIST constraint based decision properties in Activiti tasks exists
	25324: Added correct sources for current 5.3-SNAPSHOT
	25323: Implemented TaskQuery further and added extra test-coverage + delete/cancel WF now deletes History as well 
	25318: The signal() method on ActivitiWorkflowEngine now returns a WorkflowPath if the signal ended the WorkflowInstance.
	25300: Fixed start workflow form for Activiti pooled review and approve process definition
	25294: Implemented signal() method on ActivitiWorkflowEngine. Currently it returns null if the signal() ended the Workflowinstance.
	25199: Implemented getTimers() + fixed some issues with the outcome prop name + upgraded to activiti 5.3
	25179: Added support for wf:outcome property on Activiti tasks. Now ian arbitrary property can be set as the property from which outcomes are read.
	25152: Refactored the WorkflowServiceImplTest to create an AbstractWorkflowServiceImplTest. Extended this base test with Jbpm and Activiti implementations.
	25134: Fixed workflowPath node issue on start-task + Task variables are no longer flushed to process-instance variables
	25131: ALF-6901 start task completion date + taskListeners using ScriptService instead of activiti's built-in JSR-223
	25105: Implemented getWorkflows() and getCompletedWorkflows() methods on ActivitiWorkflowEngine.
	25098: Mandatory properties are now checked in TaskCompleteListener to allow setting of mandatory properties in end-task listeners before the check is performed + review-pooled used person to set as bpm_assignee + removed duplicate messageService in ActivitiWE
	25089: Merged ActivitiTaskComponent and ActivitiWorkflowComponent into a single class, ActivitiWorkflowEngine.
	25048: Implemented getStartTask(String) method on WorkflowService interface. This gets the start task instance for a given workflow instance Id. Also, modified the start task returned by the ActivitiTaskComponent so that it has the correct title.
	25028: Added WorkflowDefinitionGet webscript and test + tested WorkflowInstanceDelete and fixed WorkflowTaskDefinition bug
	25003: Added getStartTask() method to WorkflowService. Implemented for JBPMEngine and ActivitiTaskComponent.
	24996: Added activiti process-definition for pooled review/approve workflow + new version of activiti 5.2 to allow releasing task to pool agian
	24972: Extended TaskInstanceGet REST-test + upgraded activiti lib due to bug in HistoricTaskInstance
	24934: Refactored package assignment/creation so that it is now mainly performed by the WOrkflowPackageComponent rather than the WorkflowComponent or TaskComponent. Implemented correct package behaviour for Activiti workflow engine.
	24926: Extended TaskInstancePut REST-test + added extra logic for ignoring tasks for deleted/canceled WF's
	24895: Added new tests to FormServiceImplTest to check TaskFormProcessor correctly transitions tasks with both workflow engines.
	24888: Updated WorkflowRestApiTest, enhanced testing of getTaskInstances
	24861: Updated the FormServiceImplTest so that it includes tests for the TaskFormProcessor using both workflow engines.
	24851: Made WorkflowRestApiTest abstract and created a subtype for activiti and jbpm
	24832: Added integration test to FormServiceImplTest to check WorkflowFormProcessor works correctly with both Activiti and Jbpm engines.
	24829: ALF-6195 Pooled actors are now available on completed tasks
	24806: Added null check for parameters variable
	24805: Cleaned up WorkflowRestAPITest to remove deprecated field access.
	24797: ALF-6016 start-task now contains variables, upgraded to activiti 5.2-SNAPSHOT
	24796: Removed accidentaly checked-in folder
	24795: Share project "Catalina-virtual" into "https://svn.alfresco.com/repos/enterprise/alfresco/BRANCHES/DEV/ACTIVITI_INTEGRATION2/root"
	24780: Created Activiti Review & Approve workflow.
	24702: ALF-6201 cleaned up WOFactory.createInstance + removed candidate group from adhoc WF (pooled task)
	24693: ALF-6438 implemented getWorkflowById for completed workflows + added unittest for getWorkflowById from running and complete processes
	24686: ALF-6195 added formKey (typeDefinition name) to variables to make available in history + added test for getTaskById() for a completed task
	24642: ALF-6003 + ALF-6195 Introduced mapping of WorkfloTask from HistoricTaskInstance and it's variables
	24565: ALF-6016 tested getting start task by id + added initial test for taskQuery
	24560: ALF-6217 implemented and tested pooled actors using activiti-candidate user/group
	24520: ALF-6003 ALF-6014 tested + various minor improvements + TaskTypeEvaluator matchin pattern adjusted to be able to use workflow-detail form for activiti start-tasks
	24417: ALF-6003, ALF-6014 Added tasklisteners to set default task props + flush variables when task ends + running script in tasklistener (to set task-variables in script based on wf-props)
	24399: Merged BRANCHES/V3.4 to BRANCHES/DEV/ACTIVITI_INTEGRATION2:
   24396: Fix for ALF-6126: TaskTypeEvaluator uses task-name instead of taskType-name for node-type matching
	24396: Fix for ALF-6126: TaskTypeEvaluator uses task-name instead of taskType-name for node-type matching
	24334: ALF-6015 ALF-6016: Completing a task implemented + using task-local variables
	24125: ALF-5995 properties passed when starting workflow are stored
	24111: ALF-5974, ALF-5972 Task-update implemented + capturing company-home, initiator and initiator home implemented and tested
	23891: Fixing failing tests in ActivitiWorkflowComponentTest
	23776: Upgraded activiti to 5.0-SNAPSHOT + Introduced error-handling using messages + initial support for HistoricActivity/ProcessInstances
	23600: Removing unneeded folder that was introduced accidentally when reattaching SVN to eclipse
	23599: 
	23298: 
	23250: Rolling back revisions 23212 to 23113 to fix issue with logging in.
	23212: Trying to fix the problem with logging in.
	23200: Added Form config for the Activiti Adhoc Process. Fixed failing tests in ActivitiWorkflowComponentTest.
	23197: Fixed failing tests in WorkflowServiceeImplTest. Updated Activiti jars in 3rdParty.
	23191: Adding Activiti Ahodc Workflow to Workflow Deployer to demonstrate Activiti Workflow/Task..Component integration with UI.
	23129: Copy Activiti JAR files when building WAR and doing exploded deploy
	23113: Implemented ActivitiTaskComponent.getTaskById()
	23079: Created ActivitiTaskComponent and started to implement various task getter methods.
	22890: Added testStartTask to WorkflowServiceImplTests to test that the start task functionality works as required by the Workflow UI.
	22889: Added testStartTask to WorkflowServiceImplTests to test that the start task functionality works as required by the Workflow UI.
	22888: Added testStartTask to WorkflowServiceImplTests to test that the start task functionality works as required by the Workflow UI.
	22887: Added testStartTask to WorkflowServiceImplTests to test that the start task functionality works as required by the Workflow UI.
	22769: Added more functionality to ActivitiWorkflowComponent.startWorkflow.
	22759: Implemented more methods for getting WorkflowDefinitions on ActivitiWorkflowComponent. Also added more functionality to the startWorkflow method.
	22758: Implemented more methods for getting WorkflowDefinitions on ActivitiWorkflowComponent. Also added more functionality to the startWorkflow method.
	22672: Created ActivitiWorkflowComponent and implemented deployDefinition(), undeployDefinition() and isDefinitionDeployed() methods.
	22659: Replacing Activiti Jars
	22359: Added tests to check rollback of transactions in Activiti.
	22358: Got some simple transaction tests working. These test transaction visibility is working properly and also check that rollbacks work correctly.
	22342: Created a patch to add the Activiti tables in.
	22333: Added some simple tests to check if Activiti works using a DataSource and TransactionManager.
	22332: Updating Activiti to the beta release.
	22286: Added Activiti and its dependencies to 3rd Party libraries. Updated JUnit jar to 4.8. Created package org/alfresco/repo/workflow/activiti and added some simple tests to check Activiti integration.
	21879: Branch to develop support for Activiti workflow engine.
	23264: Creating branch ACTIVITI_INTEGRATION2 to merge HEAD back into the existing ACTIVITI_INTEGGRATION branch.

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@25984 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
2011-03-02 17:12:35 +00:00

410 lines
19 KiB
Java

/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.rating;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.jscript.ClasspathScriptLocation;
import org.alfresco.repo.model.Repository;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.rating.Rating;
import org.alfresco.service.cmr.rating.RatingScheme;
import org.alfresco.service.cmr.rating.RatingService;
import org.alfresco.service.cmr.rating.RatingServiceException;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.ScriptLocation;
import org.alfresco.service.cmr.repository.ScriptService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.util.BaseAlfrescoSpringTest;
import org.alfresco.util.PropertyMap;
/**
* @author Neil McErlean
* @since 3.4
*/
public class RatingServiceIntegrationTest extends BaseAlfrescoSpringTest
{
private static final String USER_ONE = "UserOne";
private static final String USER_TWO = "UserTwo";
// private CopyService copyService;
private PersonService personService;
private RatingService ratingService;
private Repository repositoryHelper;
private ScriptService scriptService;
// private RetryingTransactionHelper transactionHelper;
private NodeRef companyHome;
// These NodeRefs are used by the test methods.
private NodeRef testFolder;
// private NodeRef testFolderCopyDest;
private NodeRef testDoc_Admin;
private NodeRef testDoc_UserOne;
private NodeRef testDoc_UserTwo;
// The out of the box scheme names.
private static final String LIKES_SCHEME_NAME = "likesRatingScheme";
private static final String FIVE_STAR_SCHEME_NAME = "fiveStarRatingScheme";
@SuppressWarnings("deprecation")
@Override
protected void onSetUpInTransaction() throws Exception
{
super.onSetUpInTransaction();
// this.copyService = (CopyService)this.applicationContext.getBean("CopyService");
this.personService = (PersonService)this.applicationContext.getBean("PersonService");
this.ratingService = (RatingService) this.applicationContext.getBean("ratingService");
this.repositoryHelper = (Repository) this.applicationContext.getBean("repositoryHelper");
// this.transactionHelper = (RetryingTransactionHelper) this.applicationContext.getBean("retryingTransactionHelper");
this.scriptService = (ScriptService) this.applicationContext.getBean("scriptService");
// Set the current security context as admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
companyHome = this.repositoryHelper.getCompanyHome();
testFolder = createNode(companyHome, "testFolder", ContentModel.TYPE_FOLDER);
// testFolderCopyDest = createNode(companyHome, "testFolderCopyDest", ContentModel.TYPE_FOLDER);
testDoc_Admin = createNode(testFolder, "testDocInFolder", ContentModel.TYPE_CONTENT);
createUser(USER_ONE);
createUser(USER_TWO);
AuthenticationUtil.setFullyAuthenticatedUser(USER_TWO);
testDoc_UserOne = createNode(testFolder, "userOnesDoc", ContentModel.TYPE_CONTENT);
AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE);
testDoc_UserTwo = createNode(testFolder, "userTwosDoc", ContentModel.TYPE_CONTENT);
// And back to admin
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
}
@Override
protected void onTearDownInTransaction() throws Exception
{
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
deleteUser(USER_TWO);
deleteUser(USER_ONE);
}
/**
* This method tests that the expected 'out of the box' rating schemes are available
* and correctly initialised.
*/
public void testOutOfTheBoxRatingSchemes() throws Exception
{
Map<String, RatingScheme> schemes = this.ratingService.getRatingSchemes();
assertNotNull("rating scheme collection was null.", schemes);
assertTrue("rating scheme collection was empty.", schemes.isEmpty() == false);
RatingScheme likesRS = schemes.get(LIKES_SCHEME_NAME);
assertNotNull("'likes' rating scheme was missing.", likesRS);
assertEquals("'likes' rating scheme had wrong name.", LIKES_SCHEME_NAME, likesRS.getName());
assertEquals("'likes' rating scheme had wrong min.", 1.0f, likesRS.getMinRating());
assertEquals("'likes' rating scheme had wrong max.", 1.0f, likesRS.getMaxRating());
RatingScheme fiveStarRS = schemes.get(FIVE_STAR_SCHEME_NAME);
assertNotNull("'5*' rating scheme was missing.", fiveStarRS);
assertEquals("'5*' rating scheme had wrong name.", FIVE_STAR_SCHEME_NAME, fiveStarRS.getName());
assertEquals("'5*' rating scheme had wrong min.", 1.0f, fiveStarRS.getMinRating());
assertEquals("'5*' rating scheme had wrong max.", 5.0f, fiveStarRS.getMaxRating());
}
/**
* This test method ensures that an attempt to apply an out-of-range rating value
* throws the expected exception.
*/
public void testApplyIllegalRatings() throws Exception
{
// See rating-services-context.xml for definitions of these rating schemes.
float[] illegalRatings = new float[]{0.0f, 2.0f};
for (float illegalRating : illegalRatings)
{
applyIllegalRating(testDoc_Admin, illegalRating, LIKES_SCHEME_NAME);
}
}
private void applyIllegalRating(NodeRef nodeRef, float illegalRating, String schemeName)
{
try
{
ratingService.applyRating(nodeRef, illegalRating, schemeName);
} catch (RatingServiceException expectedException)
{
return;
}
fail("Illegal rating " + illegalRating + " should have caused exception.");
}
public void testApplyUpdateDeleteRatings() throws Exception
{
// We'll do all this as user 'UserOne'.
AuthenticationUtil.setFullyAuthenticatedUser(USER_TWO);
//Before we start, let's ensure the read behaviour on a pristine node is correct.
Rating nullRating = ratingService.getRatingByCurrentUser(testDoc_Admin, LIKES_SCHEME_NAME);
assertNull("Expected a null rating,", nullRating);
assertNull("Expected a null remove result.", ratingService.removeRatingByCurrentUser(testDoc_Admin, LIKES_SCHEME_NAME));
final float fiveStarScore = 5;
ratingService.applyRating(testDoc_Admin, fiveStarScore, FIVE_STAR_SCHEME_NAME);
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
// Some basic node structure tests.
assertTrue(ContentModel.ASPECT_RATEABLE + " aspect missing.",
nodeService.hasAspect(testDoc_Admin, ContentModel.ASPECT_RATEABLE));
List<ChildAssociationRef> allChildren = nodeService.getChildAssocs(testDoc_Admin,
ContentModel.ASSOC_RATINGS, RegexQNamePattern.MATCH_ALL);
// It's one cm:rating node per user
assertEquals("Wrong number of ratings nodes.", 1, allChildren.size());
// child-assoc of type cm:ratings
assertEquals("Wrong type qname on ratings assoc", ContentModel.ASSOC_RATINGS, allChildren.get(0).getTypeQName());
// child-assoc of name cm:<username>
QName expectedAssocName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, AuthenticationUtil.getFullyAuthenticatedUser());
assertEquals("Wrong qname on ratings assoc", expectedAssocName, allChildren.get(0).getQName());
// node structure seems ok.
// Now to check the persisted ratings data are ok.
Rating fiveStarRating = ratingService.getRatingByCurrentUser(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertNotNull("'5*' rating was null.", fiveStarRating);
assertEquals("Wrong score for rating", fiveStarScore, fiveStarRating.getScore());
assertEquals("Wrong user for rating", AuthenticationUtil.getFullyAuthenticatedUser(), fiveStarRating.getAppliedBy());
final Date fiveStarRatingAppliedAt = fiveStarRating.getAppliedAt();
assertDateIsCloseToNow(fiveStarRatingAppliedAt);
// Now we'll update a rating
final float updatedFiveStarScore = 3;
ratingService.applyRating(testDoc_Admin, updatedFiveStarScore, FIVE_STAR_SCHEME_NAME);
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
// Some basic node structure tests.
allChildren = nodeService.getChildAssocs(testDoc_Admin,
ContentModel.ASSOC_RATINGS, RegexQNamePattern.MATCH_ALL);
// Still one cm:rating node
assertEquals("Wrong number of ratings nodes.", 1, allChildren.size());
// Same assoc names
assertEquals("Wrong type qname on ratings assoc", ContentModel.ASSOC_RATINGS, allChildren.get(0).getTypeQName());
assertEquals("Wrong qname on ratings assoc", expectedAssocName, allChildren.get(0).getQName());
// node structure seems ok.
// Now to check the updated ratings data are ok.
Rating updatedFiveStarRating = ratingService.getRatingByCurrentUser(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
// 'five star' data should be changed - new score, new date
assertNotNull("'5*' rating was null.", updatedFiveStarRating);
assertEquals("Wrong score for rating", updatedFiveStarScore, updatedFiveStarRating.getScore());
assertEquals("Wrong user for rating", AuthenticationUtil.getFullyAuthenticatedUser(), updatedFiveStarRating.getAppliedBy());
assertTrue("five star rating date was unchanged.", fiveStarRatingAppliedAt.equals(updatedFiveStarRating.getAppliedAt()) == false);
assertDateIsCloseToNow(updatedFiveStarRating.getAppliedAt());
// And delete the 'five star' rating.
Rating deletedStarRating = ratingService.removeRatingByCurrentUser(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
// 'five star' rating data should be unchanged.
assertNotNull("'5*' rating was null.", deletedStarRating);
assertEquals("Wrong score for rating", updatedFiveStarScore, deletedStarRating.getScore());
assertEquals("Wrong user for rating", AuthenticationUtil.getFullyAuthenticatedUser(), deletedStarRating.getAppliedBy());
assertEquals("Wrong date for rating", updatedFiveStarRating.getAppliedAt(), deletedStarRating.getAppliedAt());
// And the deleted ratings should be gone.
assertNull("5* rating not null.", ratingService.getRatingByCurrentUser(testDoc_Admin, FIVE_STAR_SCHEME_NAME));
}
/**
* This test method asserts that the specified date is effectively equal to now.
* We can't assert that the two dates are exactly equal but we do assert that
* they are equal to within a specified tolerance.
* @param d the date to check
*/
private void assertDateIsCloseToNow(Date d)
{
//TODO Turning this assertion off temporarily
// assertNotNull("Date was unexpectedly null", d);
// Date now = new Date();
// assertTrue("Date was not before 'now'", now.after(d));
// final long millisTolerance = 5000l; // 5 seconds
// assertTrue("Date was not within " + millisTolerance + "ms of 'now'.", now.getTime() - d.getTime() < millisTolerance);
}
public void testOneUserRatesAndRerates() throws Exception
{
AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE);
ratingService.applyRating(testDoc_Admin, 1.0f, FIVE_STAR_SCHEME_NAME);
// A new score in the same rating scheme by the same user should replace the previous score.
ratingService.applyRating(testDoc_Admin, 2.0f, FIVE_STAR_SCHEME_NAME);
float meanRating = ratingService.getAverageRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong mean rating.", 2f, meanRating);
float totalRating = ratingService.getTotalRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong total rating.", 2.0f, totalRating);
int ratingsCount = ratingService.getRatingsCount(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong ratings count.", 1, ratingsCount);
// There should only be one rating child node under the rated node.
assertEquals("Wrong number of child nodes", 1 , nodeService.getChildAssocs(testDoc_Admin).size());
}
/**
* This test method ensures that if a single user attempts to rate a piece of content in two
* different rating schemes, then an exception should be thrown.
* @throws Exception
*/
public void testOneUserRatesInTwoSchemes() throws Exception
{
AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE);
ratingService.applyRating(testDoc_Admin, 1.0f, FIVE_STAR_SCHEME_NAME);
// A new score in a different rating scheme by the same user should fail.
boolean correctExceptionThrown = false;
try
{
ratingService.applyRating(testDoc_Admin, 2.0f, LIKES_SCHEME_NAME);
} catch (RatingServiceException expected)
{
correctExceptionThrown = true;
}
if (correctExceptionThrown == false)
{
fail("Expected exception not thrown.");
}
float meanRating = ratingService.getAverageRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong mean rating.", 1f, meanRating);
float totalRating = ratingService.getTotalRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong total rating.", 1f, totalRating);
int ratingsCount = ratingService.getRatingsCount(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong ratings count.", 1, ratingsCount);
// There should only be one rating child node under the rated node.
assertEquals("Wrong number of child nodes", 1 , nodeService.getChildAssocs(testDoc_Admin).size());
}
/**
* This test method applies ratings to a single node as a number of different users.
* It checks that the ratings are applied correctly and that the cm:modifier is not
* updated by these changes.
*/
public void testApplyRating_MultipleUsers() throws Exception
{
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
// 2 different users rating the same piece of content in the same rating scheme
AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE);
ratingService.applyRating(testDoc_Admin, 4.0f, FIVE_STAR_SCHEME_NAME);
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
AuthenticationUtil.setFullyAuthenticatedUser(USER_TWO);
ratingService.applyRating(testDoc_Admin, 2.0f, FIVE_STAR_SCHEME_NAME);
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
float meanRating = ratingService.getAverageRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong mean rating.", 3f, meanRating);
float totalRating = ratingService.getTotalRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong total rating.", 6.0f, totalRating);
int ratingsCount = ratingService.getRatingsCount(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong ratings count.", 2, ratingsCount);
}
/**
* This method asserts that the modifier of the specified node is equal to the
* provided modifier name.
* @param nodeRef the nodeRef to check.
* @param expectedModifier the expected modifier e.g. "admin".
*/
private void assertModifierIs(NodeRef nodeRef, final String expectedModifier)
{
String actualModifier = (String)nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIER);
assertEquals("Incorrect cm:modifier", expectedModifier, actualModifier);
}
public void testUsersCantRateTheirOwnContent() throws Exception
{
try
{
AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE);
ratingService.applyRating(testDoc_UserTwo, 4, FIVE_STAR_SCHEME_NAME);
} catch (RatingServiceException expected)
{
return;
}
fail("Expected exception not thrown");
}
private void createUser(String userName)
{
if (! authenticationService.authenticationExists(userName))
{
authenticationService.createAuthentication(userName, "PWD".toCharArray());
}
if (! personService.personExists(userName))
{
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");
personService.createPerson(ppOne);
}
}
private void deleteUser(String userName)
{
if (personService.personExists(userName))
{
personService.deletePerson(userName);
}
}
public void testJavascriptAPI() throws Exception
{
Map<String, Object> model = new HashMap<String, Object>();
model.put("testNode", this.testDoc_UserOne);
ScriptLocation location = new ClasspathScriptLocation("org/alfresco/repo/rating/script/test_ratingService.js");
this.scriptService.executeScript(location, model);
}
}