Merged HEAD-QA to HEAD (4.2) (including moving test classes into separate folders)

51903 to 54309 


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@54310 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Samuel Langlois
2013-08-20 17:17:31 +00:00
parent 0a36e2af67
commit ab4ca7177f
1576 changed files with 36419 additions and 8603 deletions

View File

@@ -42,6 +42,9 @@ import org.alfresco.service.namespace.RegexQNamePattern;
* </pre>
* The ratingSchemeName is the spring bean name of the rating scheme and the rollupName is
* the rollup name as defined in the algorithm class e.g. {@link RatingCountRollupAlgorithm#ROLLUP_NAME}.
* <p/>
* Since Alfresco 4.1.5, the "cm:" prefix is no longer required and any namespace can be used. These are provided
* via injection with {@link RatingSchemeImpl#setModelPrefix(String))}
*
* @author Neil McErlean
* @since 3.5
@@ -62,6 +65,7 @@ public class RatingNamingConventionsUtil
*/
public QName getRatingAssocNameFor(String username, String ratingSchemeName)
{
// Note that the hardcoded "cm:" here is intentional. We do not have a requirement for configuring this assoc name.
StringBuilder compoundString = new StringBuilder();
compoundString.append("cm:").append(username).append(RATING_ASSOC_SEPARATOR).append(ratingSchemeName);
QName result = QName.createQName(compoundString.toString(), namespaceService);
@@ -96,6 +100,7 @@ public class RatingNamingConventionsUtil
*
* @param ratingSchemeName the ratingSchemeName, which is the spring bean name.
* @return the aspect name used to store all property rollups for that scheme.
* @deprecated Use {@link #getRollupAspectNameFor(RatingScheme)} instead. This method assumes a "cm" prefix for the aspect.
*/
public QName getRollupAspectNameFor(String ratingSchemeName)
{
@@ -112,7 +117,11 @@ public class RatingNamingConventionsUtil
*/
public QName getRollupAspectNameFor(RatingScheme ratingScheme)
{
return getRollupAspectNameFor(ratingScheme.getName());
final String modelPrefix = ratingScheme.getModelPrefix();
final String ratingSchemeName = ratingScheme.getName();
String result = modelPrefix + ":" + ratingSchemeName + "Rollups";
return QName.createQName(result, namespaceService);
}
/**
@@ -122,6 +131,8 @@ public class RatingNamingConventionsUtil
* @param ratingSchemeName the ratingSchemeName, which is the spring bean name.
* @param rollupName the name of the property rollup as given by {@link AbstractRatingRollupAlgorithm#getRollupName()}.
* @return the property name used to persist the given rollup in the given scheme.
* @deprecated Use {@link #getRollupPropertyNameFor(RatingScheme, String)} instead.
* This method assumes a "cm" prefix for the aspect.
*/
public QName getRollupPropertyNameFor(String ratingSchemeName, String rollupName)
{
@@ -139,6 +150,10 @@ public class RatingNamingConventionsUtil
*/
public QName getRollupPropertyNameFor(RatingScheme ratingScheme, String rollupName)
{
return getRollupPropertyNameFor(ratingScheme.getName(), rollupName);
final String modelPrefix = ratingScheme.getModelPrefix();
final String ratingSchemeName = ratingScheme.getName();
String result = modelPrefix + ":" + ratingSchemeName + rollupName;
return QName.createQName(result, namespaceService);
}
}

View File

@@ -47,6 +47,16 @@ public class RatingSchemeImpl implements RatingScheme, BeanNameAware, Initializi
*/
private boolean selfRatingAllowed;
/**
* This property is used to determine where in the Alfresco content model the ratings rollup aspect should go.
* If it is not injected, a default value of "cm" for the Alfresco content model is used.
* Individual rating schemes can provide their own namespace prefixes.
* @since 4.1.5
* @see RatingNamingConventionsUtil
* @see RatingsRelatedAspectBehaviours#getAspectsNotToCopy() to prevent aspect copying.
*/
private String modelPrefix = "cm";
public RatingSchemeImpl(RatingSchemeRegistry registry)
{
this.ratingSchemeRegistry = registry;
@@ -57,6 +67,11 @@ public class RatingSchemeImpl implements RatingScheme, BeanNameAware, Initializi
this.propertyRollups = rollupAlgorithms;
}
public void setModelPrefix(String prefix)
{
this.modelPrefix = prefix;
}
public void init()
{
ratingSchemeRegistry.register(this.name, this);
@@ -66,6 +81,11 @@ public class RatingSchemeImpl implements RatingScheme, BeanNameAware, Initializi
{
return Collections.unmodifiableList(this.propertyRollups);
}
public String getModelPrefix()
{
return this.modelPrefix;
}
/*
* (non-Javadoc)
@@ -168,4 +188,10 @@ public class RatingSchemeImpl implements RatingScheme, BeanNameAware, Initializi
return msg.toString();
}
/**
* This method can be used to sort RatingSchemes by name.
* @since 4.1.5
*/
@Override public int compareTo(RatingScheme otherScheme) { return this.name.compareTo(otherScheme.getName()); }
}

View File

@@ -20,8 +20,8 @@
package org.alfresco.repo.rating;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.alfresco.service.cmr.rating.RatingScheme;
import org.apache.commons.logging.Log;
@@ -36,7 +36,7 @@ public class RatingSchemeRegistry
{
private static final Log log = LogFactory.getLog(RatingSchemeRegistry.class);
Map<String, RatingScheme> ratingSchemes = new HashMap<String, RatingScheme>();
Map<String, RatingScheme> ratingSchemes = new TreeMap<String, RatingScheme>();
public void register(String name, RatingScheme ratingScheme)
{

View File

@@ -429,13 +429,13 @@ public class RatingServiceImpl implements RatingService
throw new RatingServiceException("Cannot retrieve rollup. Unrecognized rating scheme " + ratingSchemeName);
}
QName rollupAspectName = ratingNamingConventions.getRollupAspectNameFor(ratingSchemeName);
QName rollupAspectName = ratingNamingConventions.getRollupAspectNameFor(scheme);
Serializable result = null;
// If the rated node has the rollup aspect applied
if (nodeService.hasAspect(targetNode, rollupAspectName))
{
QName rollupPropertyName = ratingNamingConventions.getRollupPropertyNameFor(ratingSchemeName, ratingRollupName);
QName rollupPropertyName = ratingNamingConventions.getRollupPropertyNameFor(scheme, ratingRollupName);
result = nodeService.getProperty(targetNode, rollupPropertyName);
}

View File

@@ -1,490 +0,0 @@
/*
* Copyright (C) 2005-2012 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 static org.junit.Assert.assertEquals;
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 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.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
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.CopyService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.ScriptLocation;
import org.alfresco.service.cmr.repository.ScriptService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.util.test.junitrules.AlfrescoPerson;
import org.alfresco.util.test.junitrules.ApplicationContextInit;
import org.alfresco.util.test.junitrules.RunAsFullyAuthenticatedRule;
import org.alfresco.util.test.junitrules.RunAsFullyAuthenticatedRule.RunAsUser;
import org.alfresco.util.test.junitrules.TemporaryNodes;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
/**
* @author Neil McErlean
* @since 3.4
*/
public class RatingServiceIntegrationTest
{
// Rule to initialise the default Alfresco spring configuration
public static ApplicationContextInit APP_CONTEXT_INIT = new ApplicationContextInit();
// Rules to create 2 test users.
public static AlfrescoPerson TEST_USER1 = new AlfrescoPerson(APP_CONTEXT_INIT, "UserOne");
public static AlfrescoPerson TEST_USER2 = new AlfrescoPerson(APP_CONTEXT_INIT, "UserTwo");
// A rule to manage test nodes reused across all the test methods
public static TemporaryNodes STATIC_TEST_NODES = new TemporaryNodes(APP_CONTEXT_INIT);
// Tie them together in a static Rule Chain
@ClassRule public static RuleChain ruleChain = RuleChain.outerRule(APP_CONTEXT_INIT)
.around(TEST_USER1)
.around(TEST_USER2)
.around(STATIC_TEST_NODES);
// A rule to manage test nodes use in each test method
@Rule public TemporaryNodes testNodes = new TemporaryNodes(APP_CONTEXT_INIT);
// A rule to allow individual test methods all to be run as "UserOne".
// Some test methods need to switch user during execution which they are free to do.
@Rule public RunAsFullyAuthenticatedRule runAsRule = new RunAsFullyAuthenticatedRule(TEST_USER1);
// Various services
private static CopyService COPY_SERVICE;
private static NodeService NODE_SERVICE;
private static RatingService RATING_SERVICE;
private static RetryingTransactionHelper TRANSACTION_HELPER;
private static ScriptService SCRIPT_SERVICE;
private static RatingNamingConventionsUtil RATING_NAMING_CONVENTIONS;
private static NodeRef COMPANY_HOME;
// These NodeRefs are used by the test methods.
private static NodeRef COPY_DEST_FOLDER;
private static NodeRef TEST_FOLDER;
private NodeRef testDoc_Admin;
private NodeRef testDoc_Copy;
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";
@BeforeClass public static void initStaticData() throws Exception
{
COPY_SERVICE = (CopyService) APP_CONTEXT_INIT.getApplicationContext().getBean("copyService");
NODE_SERVICE = (NodeService) APP_CONTEXT_INIT.getApplicationContext().getBean("nodeService");
RATING_NAMING_CONVENTIONS = (RatingNamingConventionsUtil) APP_CONTEXT_INIT.getApplicationContext().getBean("rollupNamingConventions");
RATING_SERVICE = (RatingService) APP_CONTEXT_INIT.getApplicationContext().getBean("ratingService");
SCRIPT_SERVICE = (ScriptService) APP_CONTEXT_INIT.getApplicationContext().getBean("scriptService");
TRANSACTION_HELPER = (RetryingTransactionHelper) APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper");
Repository repositoryHelper = (Repository) APP_CONTEXT_INIT.getApplicationContext().getBean("repositoryHelper");
COMPANY_HOME = repositoryHelper.getCompanyHome();
// Create some static test content
TEST_FOLDER = STATIC_TEST_NODES.createNode(COMPANY_HOME, "testFolder", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
COPY_DEST_FOLDER = STATIC_TEST_NODES.createNode(COMPANY_HOME, "testCopyDestinationFolder", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
}
@Before public void createTestContent()
{
// Create some test content
testDoc_Admin = testNodes.createNode(TEST_FOLDER, "testDocInFolder", ContentModel.TYPE_CONTENT, AuthenticationUtil.getAdminUserName());
testDoc_UserOne = testNodes.createNode(TEST_FOLDER, "userOnesDoc", ContentModel.TYPE_CONTENT, TEST_USER1.getUsername());
testDoc_UserTwo = testNodes.createNode(TEST_FOLDER, "userTwosDoc", ContentModel.TYPE_CONTENT, TEST_USER2.getUsername());
}
/**
* This method tests that the expected 'out of the box' rating schemes are available
* and correctly initialised.
*/
@Test public void outOfTheBoxRatingSchemes() throws Exception
{
Map<String, RatingScheme> schemes = RATING_SERVICE.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, (int)likesRS.getMinRating());
assertEquals("'likes' rating scheme had wrong max.", 1, (int)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, (int)fiveStarRS.getMinRating());
assertEquals("'5*' rating scheme had wrong max.", 5, (int)fiveStarRS.getMaxRating());
}
/**
* This test method ensures that an attempt to apply an out-of-range rating value
* throws the expected exception.
*/
@Test public void applyIllegalRatings() 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
{
RATING_SERVICE.applyRating(nodeRef, illegalRating, schemeName);
}
catch (RatingServiceException expectedException)
{
return;
}
fail("Illegal rating " + illegalRating + " should have caused exception.");
}
@Test public void applyUpdateDeleteRatings() throws Exception
{
TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// We'll do all this as user 'UserTwo'.
AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER2.getUsername());
//Before we start, let's ensure the read behaviour on a pristine node is correct.
Rating nullRating = RATING_SERVICE.getRatingByCurrentUser(testDoc_Admin, LIKES_SCHEME_NAME);
assertNull("Expected a null rating,", nullRating);
assertNull("Expected a null remove result.", RATING_SERVICE.removeRatingByCurrentUser(testDoc_Admin, LIKES_SCHEME_NAME));
final int fiveStarScore = 5;
RATING_SERVICE.applyRating(testDoc_Admin, fiveStarScore, FIVE_STAR_SCHEME_NAME);
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
// Some basic node structure tests.
assertTrue(ContentModel.ASPECT_RATEABLE + " aspect missing.",
NODE_SERVICE.hasAspect(testDoc_Admin, ContentModel.ASPECT_RATEABLE));
List<ChildAssociationRef> allChildren = NODE_SERVICE.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__ratingScheme>
QName expectedAssocName = RATING_NAMING_CONVENTIONS.getRatingAssocNameFor(AuthenticationUtil.getFullyAuthenticatedUser(), FIVE_STAR_SCHEME_NAME);
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 = RATING_SERVICE.getRatingByCurrentUser(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertNotNull("'5*' rating was null.", fiveStarRating);
assertEquals("Wrong score for rating", fiveStarScore, (int)fiveStarRating.getScore());
assertEquals("Wrong user for rating", AuthenticationUtil.getFullyAuthenticatedUser(), fiveStarRating.getAppliedBy());
final Date fiveStarRatingAppliedAt = fiveStarRating.getAppliedAt();
// Now we'll update a rating
final int updatedFiveStarScore = 3;
RATING_SERVICE.applyRating(testDoc_Admin, updatedFiveStarScore, FIVE_STAR_SCHEME_NAME);
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
// Some basic node structure tests.
allChildren = NODE_SERVICE.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 = RATING_SERVICE.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, (int)updatedFiveStarRating.getScore());
assertEquals("Wrong user for rating", AuthenticationUtil.getFullyAuthenticatedUser(), updatedFiveStarRating.getAppliedBy());
assertTrue("five star rating date was unchanged.", fiveStarRatingAppliedAt.equals(updatedFiveStarRating.getAppliedAt()) == false);
// And delete the 'five star' rating.
Rating deletedStarRating = RATING_SERVICE.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, (int)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.", RATING_SERVICE.getRatingByCurrentUser(testDoc_Admin, FIVE_STAR_SCHEME_NAME));
return null;
}
});
}
@Test public void oneUserRatesAndRerates() throws Exception
{
TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
RATING_SERVICE.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.
RATING_SERVICE.applyRating(testDoc_Admin, 2.0f, FIVE_STAR_SCHEME_NAME);
float meanRating = RATING_SERVICE.getAverageRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong mean rating.", 2, (int)meanRating);
float totalRating = RATING_SERVICE.getTotalRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong total rating.", 2, (int)totalRating);
int ratingsCount = RATING_SERVICE.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 , NODE_SERVICE.getChildAssocs(testDoc_Admin).size());
return null;
}
});
}
/**
* 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 not be thrown.
*/
@Test public void oneUserRatesInTwoSchemes() throws Exception
{
TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
RATING_SERVICE.applyRating(testDoc_UserTwo, 2.0f, FIVE_STAR_SCHEME_NAME);
// A new score in a different rating scheme by the same user should not fail.
RATING_SERVICE.applyRating(testDoc_UserTwo, 1.0f, LIKES_SCHEME_NAME);
// There should be two rating child nodes under the rated node.
assertEquals("Wrong number of child nodes", 2 , NODE_SERVICE.getChildAssocs(testDoc_UserTwo).size());
List<Rating> ratings = RATING_SERVICE.getRatingsByCurrentUser(testDoc_UserTwo);
assertEquals(2, ratings.size());
assertEquals(FIVE_STAR_SCHEME_NAME, ratings.get(0).getScheme().getName());
assertEquals(LIKES_SCHEME_NAME, ratings.get(1).getScheme().getName());
return null;
}
});
}
/**
* 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.
*/
@Test public void applyRating_MultipleUsers() throws Exception
{
TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
// 2 different users rating the same piece of content in the same rating scheme
AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER1.getUsername());
RATING_SERVICE.applyRating(testDoc_Admin, 4.0f, FIVE_STAR_SCHEME_NAME);
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER2.getUsername());
RATING_SERVICE.applyRating(testDoc_Admin, 2.0f, FIVE_STAR_SCHEME_NAME);
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
float meanRating = RATING_SERVICE.getAverageRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong mean rating.", 3, (int)meanRating);
float totalRating = RATING_SERVICE.getTotalRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong total rating.", 6, (int)totalRating);
int ratingsCount = RATING_SERVICE.getRatingsCount(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong ratings count.", 2, ratingsCount);
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
// One user removes their rating.
RATING_SERVICE.removeRatingByCurrentUser(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
meanRating = RATING_SERVICE.getAverageRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong mean rating.", 4, (int)meanRating);
totalRating = RATING_SERVICE.getTotalRating(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong total rating.", 4, (int)totalRating);
ratingsCount = RATING_SERVICE.getRatingsCount(testDoc_Admin, FIVE_STAR_SCHEME_NAME);
assertEquals("Document had wrong ratings count.", 1, ratingsCount);
assertModifierIs(testDoc_Admin, AuthenticationUtil.getAdminUserName());
return null;
}
});
}
/**
* 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)NODE_SERVICE.getProperty(nodeRef, ContentModel.PROP_MODIFIER);
assertEquals("Incorrect cm:modifier", expectedModifier, actualModifier);
}
@Test public void usersCantRateTheirOwnContent() throws Exception
{
TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// In the likes rating scheme, users can rate their own content.
RATING_SERVICE.applyRating(testDoc_UserOne, 1, LIKES_SCHEME_NAME);
// But fiveStar rating scheme disallows rating your own content.
boolean expectedExceptionThrown = false;
try
{
RATING_SERVICE.applyRating(testDoc_UserOne, 4, FIVE_STAR_SCHEME_NAME);
} catch (RatingServiceException expected)
{
expectedExceptionThrown = true;
}
assertTrue(expectedExceptionThrown);
return null;
}
});
}
@Test @RunAsUser(userName="UserTwo") public void javascriptAPI() throws Exception
{
TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
Map<String, Object> model = new HashMap<String, Object>();
model.put("testNode", testDoc_UserOne);
ScriptLocation location = new ClasspathScriptLocation("org/alfresco/repo/rating/script/test_ratingService.js");
SCRIPT_SERVICE.executeScript(location, model);
return null;
}
});
}
@Test public void copyNodeNotRatings()
{
TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Apply ratings to node
AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER1.getUsername());
RATING_SERVICE.applyRating(testDoc_UserTwo, 2.0f, FIVE_STAR_SCHEME_NAME);
// A new score in a different rating scheme by the same user should not fail.
RATING_SERVICE.applyRating(testDoc_UserTwo, 1.0f, LIKES_SCHEME_NAME);
// There should be two rating child nodes under the rated node.
assertEquals("Wrong number of child nodes", 2 , NODE_SERVICE.getChildAssocs(testDoc_UserTwo).size());
List<Rating> ratings = RATING_SERVICE.getRatingsByCurrentUser(testDoc_UserTwo);
assertEquals(2, ratings.size());
assertEquals(FIVE_STAR_SCHEME_NAME, ratings.get(0).getScheme().getName());
assertEquals(LIKES_SCHEME_NAME, ratings.get(1).getScheme().getName());
// Copy the node
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
final QName childName = QName.createQName(NamespaceService.APP_MODEL_1_0_URI, "userTwosDoc");;
final NodeRef testDocCopy = COPY_SERVICE.copy(testDoc_UserTwo, COPY_DEST_FOLDER, ContentModel.ASSOC_CONTAINS, childName, true);
testNodes.addNodeRef(testDocCopy);
// Check that the user ratings aren't copied
AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER1.getUsername());
List<Rating> copiedRatings = RATING_SERVICE.getRatingsByCurrentUser(testDocCopy);
assertEquals(0, copiedRatings.size());
// Check that the roll ups aren't copied
final int likesRatingCount = RATING_SERVICE.getRatingsCount(testDocCopy, LIKES_SCHEME_NAME);
final int fiveStarRatingCount = RATING_SERVICE.getRatingsCount(testDocCopy, FIVE_STAR_SCHEME_NAME);
assertEquals(0, fiveStarRatingCount);
assertEquals(0, likesRatingCount);
return null;
}
});
}
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (C) 2005-2013 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.Arrays;
import java.util.List;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.copy.CopyBehaviourCallback;
import org.alfresco.repo.copy.CopyDetails;
import org.alfresco.repo.copy.CopyServicePolicies;
import org.alfresco.repo.copy.DefaultCopyBehaviourCallback;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.service.cmr.rating.RatingService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.Pair;
/**
* Aspect behaviour bean for {@link RatingService}-related aspects.
*
* @author Neil Mc Erlean
* @since 4.1.5
*/
public class RatingsRelatedAspectBehaviours implements CopyServicePolicies.OnCopyNodePolicy
{
private PolicyComponent policyComponent;
public void setPolicyComponent(PolicyComponent policyComponent) { this.policyComponent = policyComponent; }
public void init()
{
for (QName aspect : getAspectsNotToCopy())
{
this.policyComponent.bindClassBehaviour(
QName.createQName(NamespaceService.ALFRESCO_URI, "getCopyCallback"),
aspect,
new JavaBehaviour(this, "getCopyCallback"));
}
}
/**
* This method returns the default list of ratings-related aspects which should not be
* copied when a rated node is copied.
*
* @return a List of QNames of ratings-related aspects which should not be copied.
*/
protected List<QName> getAspectsNotToCopy()
{
return Arrays.asList(new QName[] {ContentModel.ASPECT_RATEABLE,
ContentModel.ASPECT_LIKES_RATING_SCHEME_ROLLUPS,
ContentModel.ASPECT_FIVESTAR_RATING_SCHEME_ROLLUPS});
}
/**
* @return Returns {@link RatingRelatedAspectsCopyBehaviourCallback}
*/
@Override public CopyBehaviourCallback getCopyCallback(QName classRef, CopyDetails copyDetails)
{
return RatingRelatedAspectsCopyBehaviourCallback.INSTANCE;
}
/**
* This class defines a 'do not copy' behaviour for all relevant aspects.
*/
private static class RatingRelatedAspectsCopyBehaviourCallback extends DefaultCopyBehaviourCallback
{
private static final CopyBehaviourCallback INSTANCE = new RatingRelatedAspectsCopyBehaviourCallback();
/** Do not copy any of these aspects. */
@Override public boolean getMustCopy(QName classQName, CopyDetails copyDetails) { return false; }
@Override public Pair<AssocCopySourceAction, AssocCopyTargetAction> getAssociationCopyAction(
QName classQName,
CopyDetails copyDetails,
CopyAssociationDetails assocCopyDetails)
{
return new Pair<AssocCopySourceAction, AssocCopyTargetAction>(
AssocCopySourceAction.IGNORE,
AssocCopyTargetAction.USE_COPIED_OTHERWISE_ORIGINAL_TARGET);
}
@Override public ChildAssocCopyAction getChildAssociationCopyAction(QName classQName,
CopyDetails copyDetails,
CopyChildAssociationDetails childAssocCopyDetails)
{ return ChildAssocCopyAction.IGNORE; }
}
}

View File

@@ -1,53 +0,0 @@
function testRatingSchemes()
{
var schemeNames = ratingService.getRatingSchemeNames();
test.assertEquals(2, schemeNames.length);
test.assertEquals('likesRatingScheme', schemeNames[0]);
test.assertEquals('fiveStarRatingScheme', schemeNames[1]);
test.assertEquals(1, ratingService.getMin('likesRatingScheme'));
test.assertEquals(1, ratingService.getMax('likesRatingScheme'));
test.assertEquals(true, ratingService.isSelfRatingAllowed('likesRatingScheme'));
test.assertEquals(1, ratingService.getMin('fiveStarRatingScheme'));
test.assertEquals(5, ratingService.getMax('fiveStarRatingScheme'));
test.assertEquals(false, ratingService.isSelfRatingAllowed('fiveStarRatingScheme'));
}
function testApplyUpdateDeleteRatings()
{
// Check the pristine state of the test node.
test.assertEquals(0, ratingService.getRatingsCount(testNode, 'fiveStarRatingScheme'));
test.assertEquals(0, ratingService.getTotalRating(testNode, 'fiveStarRatingScheme'));
test.assertEquals(-1, ratingService.getAverageRating(testNode, 'fiveStarRatingScheme'));
// Now apply some ratings.
ratingService.applyRating(testNode, 2.0, 'fiveStarRatingScheme');
test.assertEquals(2.0, ratingService.getRating(testNode, 'fiveStarRatingScheme'));
test.assertNotNull(ratingService.getRatingAppliedAt(testNode, 'fiveStarRatingScheme'));
test.assertEquals(1, ratingService.getRatingsCount(testNode, 'fiveStarRatingScheme'));
test.assertEquals(2, ratingService.getTotalRating(testNode, 'fiveStarRatingScheme'));
test.assertEquals(2, ratingService.getAverageRating(testNode, 'fiveStarRatingScheme'));
// And update them
ratingService.applyRating(testNode, 4.5, 'fiveStarRatingScheme');
test.assertEquals(4.5, ratingService.getRating(testNode, 'fiveStarRatingScheme'));
test.assertNotNull(ratingService.getRatingAppliedAt(testNode, 'fiveStarRatingScheme'));
test.assertEquals(1, ratingService.getRatingsCount(testNode, 'fiveStarRatingScheme'));
test.assertEquals(4.5, ratingService.getTotalRating(testNode, 'fiveStarRatingScheme'));
test.assertEquals(4.5, ratingService.getAverageRating(testNode, 'fiveStarRatingScheme'));
// Now delete them.
ratingService.removeRating(testNode, 'fiveStarRatingScheme');
test.assertEquals(-1, ratingService.getRating(testNode, 'fiveStarRatingScheme'));
}
// Execute tests
testRatingSchemes();
testApplyUpdateDeleteRatings();