}
}
public UserRating setUserRating(PermissibleObject permissibleObject, int rating) throws SimpleMessageException {
if (permissibleObject == null) {
throw new SimpleMessageException("PermissibleObject not supplied.");
}
User authUser = getAuthenticatedUser(session.get());
Transaction tx = session.get().beginTransaction();
try {
permissibleObject = (PermissibleObject) session.get().load(PermissibleObject.class, permissibleObject.getId());
if (!SecurityHelper.doesUserHavePermission(session.get(), authUser, permissibleObject, PERM.READ)) {
throw new SimpleMessageException("User is not authorized to set rating on this content.");
}
UserRating userRating = RatingHelper.getUserRating(session.get(), permissibleObject, authUser, getVoterGUID());
// check if rating already exists
if (userRating != null) {
// TODO: consider changing the vote
// simply subtract the previous amount and decrement the numRatingVotes and redivide
throw new SimpleMessageException("Already voted.");
}
float totalRating = (float) permissibleObject.getNumRatingVotes() * permissibleObject.getAverageRating();
totalRating += rating;
permissibleObject.setNumRatingVotes(permissibleObject.getNumRatingVotes() + 1);
float newAvg = totalRating / (float) permissibleObject.getNumRatingVotes();
permissibleObject.setAverageRating(newAvg);
session.get().save(permissibleObject);
userRating = new UserRating();
userRating.setPermissibleObject(permissibleObject);
userRating.setRating(rating);
userRating.setVoter(authUser);
userRating.setVoterGUID(getVoterGUID());
session.get().save(userRating);
tx.commit();
return userRating;
} catch (Throwable t) {
Logger.log(t);
try {
tx.rollback();
} catch (Throwable tt) {
}
throw new SimpleMessageException(t.getMessage());
}
}