Index: lams_admin/conf/language/lams/ApplicationResources.properties =================================================================== diff -u -r5835d5dd250ed2c1e670627ff0a6a20339e7236f -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_admin/conf/language/lams/ApplicationResources.properties (.../ApplicationResources.properties) (revision 5835d5dd250ed2c1e670627ff0a6a20339e7236f) +++ lams_admin/conf/language/lams/ApplicationResources.properties (.../ApplicationResources.properties) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -417,10 +417,6 @@ label.html.flashTheme =Flash Theme config.use.internal.smtp.server =Use Internal SMTP Server label.email =Email -admin.email.to =To -admin.email.subject =Subject -admin.email.send =Send -admin.email.compose.mail =Compose email title.clone.lessons =Clone Lessons label.ok =OK title.clone.lessons.for =Clone Lessons for {0} Fisheye: Tag 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc refers to a dead (removed) revision in file `lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/EmailUserAction.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc refers to a dead (removed) revision in file `lams_admin/src/java/org/lamsfoundation/lams/admin/web/form/EmailForm.java'. Fisheye: No comparison available. Pass `N' to diff? Index: lams_admin/web/WEB-INF/tiles-defs.xml =================================================================== diff -u -r2b88dada3266a4b0f83f4b5c4cf617553496ca59 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_admin/web/WEB-INF/tiles-defs.xml (.../tiles-defs.xml) (revision 2b88dada3266a4b0f83f4b5c4cf617553496ca59) +++ lams_admin/web/WEB-INF/tiles-defs.xml (.../tiles-defs.xml) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -108,11 +108,6 @@ - - - - - Fisheye: Tag 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc refers to a dead (removed) revision in file `lams_admin/web/emailuser.jsp'. Fisheye: No comparison available. Pass `N' to diff? Index: lams_admin/web/usersearchlist.jsp =================================================================== diff -u -r73c6c78a8c692997a40ab3506078274d623b492b -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_admin/web/usersearchlist.jsp (.../usersearchlist.jsp) (revision 73c6c78a8c692997a40ab3506078274d623b492b) +++ lams_admin/web/usersearchlist.jsp (.../usersearchlist.jsp) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -91,7 +91,7 @@ [">] - [">] + [&returnUrl=admin/usersearch.do">] Index: lams_build/lib/lams/lams-central.jar =================================================================== diff -u -re64a90c0cc74118c5b88f5cbae323065abd59cac -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc Binary files differ Index: lams_build/lib/lams/lams.jar =================================================================== diff -u -reb42380458dff71406b1964f915d8428a4bf2a2e -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc Binary files differ Index: lams_central/conf/language/lams/ApplicationResources.properties =================================================================== diff -u -rcc9171cd97e801e507969f3fba48edfc7a6d7e5a -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_central/conf/language/lams/ApplicationResources.properties (.../ApplicationResources.properties) (revision cc9171cd97e801e507969f3fba48edfc7a6d7e5a) +++ lams_central/conf/language/lams/ApplicationResources.properties (.../ApplicationResources.properties) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -406,6 +406,9 @@ label.questions.choice.title =Choose questions label.questions.choice.select.all =Select all label.questions.choice.missing =Please check at least one question. +email.to =To +email.subject =Subject +email.send =Send +email.compose.mail =Compose email - #======= End labels: Exported 400 labels for en AU ===== Index: lams_central/src/java/org/lamsfoundation/lams/web/EmailForm.java =================================================================== diff -u --- lams_central/src/java/org/lamsfoundation/lams/web/EmailForm.java (revision 0) +++ lams_central/src/java/org/lamsfoundation/lams/web/EmailForm.java (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -0,0 +1,76 @@ +/**************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * License Information: http://lamsfoundation.org/licensing/lams/2.0/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2.0 + * as published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA + * + * http://www.gnu.org/licenses/gpl.txt + * **************************************************************** + */ + +/* $Id$ */ +package org.lamsfoundation.lams.web; + +import org.apache.struts.action.ActionForm; + +/** + * + * Form for email composing + * + * @author Andrey Balan + * + * @struts.form name="emailForm" + */ +public class EmailForm extends ActionForm { + private static final long serialVersionUID = 7775887425863041037L; + + private Long userId; + + private String to; + private String subject; + private String body; + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getTo() { + return to; + } + + public void setTo(String name) { + this.to = name; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String description) { + this.subject = description; + } + + public String getBody() { + return body; + } + + public void setBody(String imageDirectory) { + this.body = imageDirectory; + } +} Index: lams_central/src/java/org/lamsfoundation/lams/web/EmailUserAction.java =================================================================== diff -u --- lams_central/src/java/org/lamsfoundation/lams/web/EmailUserAction.java (revision 0) +++ lams_central/src/java/org/lamsfoundation/lams/web/EmailUserAction.java (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -0,0 +1,178 @@ +/**************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * License Information: http://lamsfoundation.org/licensing/lams/2.0/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2.0 + * as published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA + * + * http://www.gnu.org/licenses/gpl.txt + * **************************************************************** + */ + +/* $Id$ */ +package org.lamsfoundation.lams.web; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.validator.EmailValidator; +import org.apache.log4j.Logger; +import org.apache.struts.action.ActionForm; +import org.apache.struts.action.ActionForward; +import org.apache.struts.action.ActionMapping; +import org.apache.struts.action.ActionMessage; +import org.apache.struts.action.ActionMessages; +import org.lamsfoundation.lams.events.IEventNotificationService; +import org.lamsfoundation.lams.lesson.Lesson; +import org.lamsfoundation.lams.usermanagement.Role; +import org.lamsfoundation.lams.usermanagement.User; +import org.lamsfoundation.lams.usermanagement.dto.UserDTO; +import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; +import org.lamsfoundation.lams.util.CentralConstants; +import org.lamsfoundation.lams.util.MessageService; +import org.lamsfoundation.lams.util.WebUtil; +import org.lamsfoundation.lams.web.action.LamsDispatchAction; +import org.lamsfoundation.lams.web.session.SessionManager; +import org.lamsfoundation.lams.web.util.AttributeNames; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.WebApplicationContextUtils; + +/** + * @author Andrey Balan, Marcin Cieslak + * + * @struts:action path="/emailUser" name="emailForm" parameter="method" validate="false" + * + * @struts:action-forward name="emailuser" path="/emailuser.jsp" + */ +public class EmailUserAction extends LamsDispatchAction { + + private static Logger log = Logger.getLogger(EmailUserAction.class); + private static final EmailValidator emailValidator = EmailValidator.getInstance(); + private static IUserManagementService userManagementService; + private static IEventNotificationService eventNotificationService; + private static MessageService messageService; + + public ActionForward composeMail(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { + UserDTO currentUser = (UserDTO) SessionManager.getSession().getAttribute(AttributeNames.USER); + + if (canSend(request, currentUser)) { + Integer userId = WebUtil.readIntParam(request, AttributeNames.PARAM_USER_ID); + User user = (User) getUserManagementService().findById(User.class, userId); + request.setAttribute(AttributeNames.USER, user); + if (!EmailUserAction.emailValidator.isValid(user.getEmail())) { + EmailUserAction.log.error("Recipient " + user.getLogin() + " does not have a valid email"); + saveError(request, "error.valid.email.required", true); + } + } else { + EmailUserAction.log.error("User " + currentUser.getLogin() + " is not allowed to send email"); + saveError(request, "error.authorisation", true); + } + + return mapping.findForward("emailuser"); + } + + public ActionForward send(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { + UserDTO currentUser = (UserDTO) SessionManager.getSession().getAttribute(AttributeNames.USER); + + if (!canSend(request, currentUser)) { + EmailUserAction.log.error("User " + currentUser.getLogin() + " is not allowed to send email"); + response.setContentType("text/plain;charset=utf-8"); + response.getWriter().write(getMessageService().getMessage("error.authorisation")); + return null; + } + + EmailForm emailForm = (EmailForm) form; + Long userId = emailForm.getUserId(); + + String subject = emailForm.getSubject(); + String body = WebUtil.removeHTMLtags(emailForm.getBody()); + + if (EmailUserAction.log.isDebugEnabled()) { + EmailUserAction.log.debug("User " + currentUser.getLogin() + " (" + currentUser.getEmail() + ") " + + " sent email to user ID " + userId + ": \n[subject] " + subject + "\n[message] " + body); + } + + getEventNotificationService().sendMessage(currentUser.getUserID(), userId.intValue(), + IEventNotificationService.DELIVERY_METHOD_MAIL, subject, body, false); + + return null; + } + + private void saveError(HttpServletRequest request, String error, boolean sendDisabled) { + ActionMessages errors = new ActionMessages(); + errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(error)); + saveErrors(request, errors); + request.setAttribute("errorsPresent", true); + request.setAttribute("sendDisabled", sendDisabled); + } + + private IEventNotificationService getEventNotificationService() { + if (EmailUserAction.eventNotificationService == null) { + WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() + .getServletContext()); + EmailUserAction.eventNotificationService = (IEventNotificationService) ctx + .getBean("eventNotificationService"); + } + return EmailUserAction.eventNotificationService; + } + + private MessageService getMessageService() { + if (EmailUserAction.messageService == null) { + WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() + .getServletContext()); + EmailUserAction.messageService = (MessageService) ctx + .getBean(CentralConstants.CENTRAL_MESSAGE_SERVICE_BEAN_NAME); + + } + return EmailUserAction.messageService; + } + + private IUserManagementService getUserManagementService() { + if (EmailUserAction.userManagementService == null) { + WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() + .getServletContext()); + EmailUserAction.userManagementService = (IUserManagementService) ctx.getBean("userManagementService"); + } + return EmailUserAction.userManagementService; + } + + private boolean canSend(HttpServletRequest request, UserDTO currentUser) { + if (currentUser == null) { + currentUser = (UserDTO) SessionManager.getSession().getAttribute(AttributeNames.USER); + } + + boolean result = request.isUserInRole(Role.SYSADMIN) || getUserManagementService().isUserGlobalGroupAdmin(); + if (!result) { + String orgId = request.getParameter(AttributeNames.PARAM_ORGANISATION_ID); + if (StringUtils.isBlank(orgId)) { + String lessonId = request.getParameter(AttributeNames.PARAM_LESSON_ID); + if (!StringUtils.isBlank(lessonId)) { + Lesson lesson = (Lesson) getUserManagementService().findById(Lesson.class, new Long(lessonId)); + if (lesson != null) { + orgId = lesson.getOrganisation().getOrganisationId().toString(); + } + } + } + if (!StringUtils.isBlank(orgId)) { + result = getUserManagementService().isUserInRole(currentUser.getUserID(), new Integer(orgId), + Role.MONITOR); + } + } + + return result; + } +} \ No newline at end of file Index: lams_central/src/java/org/lamsfoundation/lams/webservice/RegisterAction.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_central/src/java/org/lamsfoundation/lams/webservice/RegisterAction.java (.../RegisterAction.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_central/src/java/org/lamsfoundation/lams/webservice/RegisterAction.java (.../RegisterAction.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -18,9 +18,9 @@ * * http://www.gnu.org/licenses/gpl.txt * **************************************************************** - */ - -/* $Id$ */ + */ + +/* $Id$ */ package org.lamsfoundation.lams.webservice; import java.io.IOException; @@ -77,7 +77,7 @@ /** * @author Andrey Balan * - * ----------------XDoclet Tags-------------------- + * ----------------XDoclet Tags-------------------- * * @web:servlet name="RegisterServlet" * @web:servlet-mapping url-pattern="/services/Register/*" @@ -86,7 +86,7 @@ public class RegisterAction extends HttpServlet { private static Logger logger = Logger.getLogger(RegisterAction.class); - + private static IntegrationService integrationService = null; private static ILearnerProgressDAO learnerProgressDAO = null; @@ -96,13 +96,13 @@ private static ICoreLearnerService learnerService = null; private static IGroupUserDAO groupUserDAO = null; - + private static IUserManagementService userManagementService = null; - - private static IEventNotificationService eventNotificationService = null; - - private static MessageService messageService = null; - + + private static IEventNotificationService eventNotificationService = null; + + private static MessageService messageService = null; + public synchronized void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -118,12 +118,12 @@ } } - + /** * Initialization of the servlet.
* * @throws ServletException - * if an error occured + * if an error occured */ public void init() throws ServletException { learnerProgressDAO = (ILearnerProgressDAO) WebApplicationContextUtils.getRequiredWebApplicationContext( @@ -138,8 +138,8 @@ learnerService = (ICoreLearnerService) WebApplicationContextUtils.getRequiredWebApplicationContext( getServletContext()).getBean("learnerService"); - groupUserDAO = (IGroupUserDAO) WebApplicationContextUtils.getRequiredWebApplicationContext( - getServletContext()).getBean("groupUserDAO"); + groupUserDAO = (IGroupUserDAO) WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()) + .getBean("groupUserDAO"); userManagementService = (IUserManagementService) WebApplicationContextUtils.getRequiredWebApplicationContext( getServletContext()).getBean("userManagementService"); @@ -150,29 +150,48 @@ messageService = (MessageService) WebApplicationContextUtils.getRequiredWebApplicationContext( getServletContext()).getBean(CentralConstants.CENTRAL_MESSAGE_SERVICE_BEAN_NAME); } - + /** - * Add user to group lessons. + * Add user to group lessons. * * External server call must follow the next format: - * http://<>/lams/central/Register.do?method=addUserToGroupLessons&serverId=%serverId%&datetime=%datetime% - * &hashValue=%hashValue%&courseId=%courseId%&username=%username%&firstName=%firstName%&lastName=%lastName%&email=%email&isJoinLesson=%isJoinLesson% + * http://<>/lams/central/Register.do?method=addUserToGroupLessons + * &serverId=%serverId%&datetime=%datetime% + * &hashValue=%hashValue%&courseId=%courseId%&username=%username%&firstName= + * %firstName%&lastName=%lastName%&email=%email&isJoinLesson=%isJoinLesson% * &isEmailParticipant=%isEmailParticipant%&isEmailCoordinator=%isEmailCoordinator% * * Here are the parameters explanation: - * @param method=addUserToGroupLessons - selfexplanatory. - * @param serverId - this is a string of characters we'll provide to you - * @param datetime - a character string with the date and time you make this request (format example 2011100608:15:10) - * @param hashValue - The hash value is generated using the SHA1 algorithm on the following (all in lower case) [ datetime + username + method + serverId + serverKey ] - * @param courseId - courseId is essentially a unique identifier for your Functional Speciality (note this is not the name of the Functional Speciality but its unique id) - * @param username - this is your WV Central ID - * @param usePrefix - if set to 1 - force the addition of the server integration prefix to usernames - * @param firstName - well, first name - * @param lastName - last name - * @param email - email - * @param isJoinLesson - if set to 1 -then join user to lesson - * @param isEmailParticipant - if set to 1 -then LAMS will email the user his/her login details - * @param isEmailCoordinator - if an email confirmation to and admin is required, just put the email address for the admin person here. + * + * @param method + * =addUserToGroupLessons - selfexplanatory. + * @param serverId + * - this is a string of characters we'll provide to you + * @param datetime + * - a character string with the date and time you make this request (format example 2011100608:15:10) + * @param hashValue + * - The hash value is generated using the SHA1 algorithm on the following (all in lower case) [ datetime + * + username + method + serverId + serverKey ] + * @param courseId + * - courseId is essentially a unique identifier for your Functional Speciality (note this is not the + * name of the Functional Speciality but its unique id) + * @param username + * - this is your WV Central ID + * @param usePrefix + * - if set to 1 - force the addition of the server integration prefix to usernames + * @param firstName + * - well, first name + * @param lastName + * - last name + * @param email + * - email + * @param isJoinLesson + * - if set to 1 -then join user to lesson + * @param isEmailParticipant + * - if set to 1 -then LAMS will email the user his/her login details + * @param isEmailCoordinator + * - if an email confirmation to and admin is required, just put the email address for the admin person + * here. */ public void addUserToGroupLessons(HttpServletRequest request, HttpServletResponse response) throws IOException { try { @@ -181,8 +200,8 @@ boolean serverToServerEnable = Configuration.getAsBoolean(ConfigurationKeys.ENABLE_SERVER_REGISTRATION); if (!serverToServerEnable) { String msg = "Server to server registration is not enabled"; - logger.error(msg); - response.sendError(response.SC_METHOD_NOT_ALLOWED, msg); + logger.error(msg); + response.sendError(response.SC_METHOD_NOT_ALLOWED, msg); return; } String method = request.getParameter(CentralConstants.PARAM_METHOD); @@ -205,12 +224,12 @@ logger.error(msg); response.sendError(response.SC_BAD_REQUEST, "Parameters missing"); } - + // authenticate external server ExtServerOrgMap extServer = integrationService.getExtServerOrgMap(serverId); Authenticator.authenticate(extServer, datetime, username, method, hashValue); - - //create new password + + // create new password String password = RandomPasswordGenerator.nextPassword(8); String hashedPassword = HashUtil.sha1(password); @@ -220,206 +239,234 @@ logger.debug("Adding prefix to username:" + username); } - //get user from the DB if exists, create it otherwise - ExtUserUseridMap userMap = integrationService.getImplicitExtUserUseridMap(extServer, username, hashedPassword, - firstName, lastName, email); + // get user from the DB if exists, create it otherwise + ExtUserUseridMap userMap = integrationService.getImplicitExtUserUseridMap(extServer, username, + hashedPassword, firstName, lastName, email); User user = userMap.getUser(); - + HashSet lessonsToJoin = new HashSet(); HashSet organisationsToJoin = new HashSet(); - + if (StringUtils.isNotBlank(groupName)) { // gets organisation from DB if exists, throws exception otherwise Organisation org = getOrganisationByName(groupName); organisationsToJoin.add(org); lessonsToJoin.addAll(org.getLessons()); } - + if (StringUtils.isNotBlank(lessonId)) { Long lessonIdLong = Long.parseLong(lessonId); Lesson lesson = lessonService.getLesson(lessonIdLong); organisationsToJoin.add(lesson.getOrganisation()); lessonsToJoin.add(lesson); } - - //add to all required organisations + + // add to all required organisations List learnerRole = new ArrayList(); learnerRole.add(Role.ROLE_LEARNER.toString()); for (Organisation organisationToJoin : organisationsToJoin) { - userManagementService.setRolesForUserOrganisation(user, organisationToJoin.getOrganisationId(), learnerRole); + userManagementService.setRolesForUserOrganisation(user, organisationToJoin.getOrganisationId(), + learnerRole); } - + // add to all required lessons (checks for duplicates) for (Lesson lesson : lessonsToJoin) { boolean isAdded = lessonService.addLearner(lesson.getLessonId(), user.getUserId()); if (isAdded) { - logger.debug("Added user:" + user.getLogin() + " to lesson:" + lesson.getLessonName() + " as a learner"); + logger.debug("Added user:" + user.getLogin() + " to lesson:" + lesson.getLessonName() + + " as a learner"); } } - - //join user to all lessons in the group + + // join user to all lessons in the group if ("1".equals(isJoinLesson)) { for (Lesson lesson : lessonsToJoin) { - - LearnerProgress learnerProgress = learnerProgressDAO.getLearnerProgressByLearner(user.getUserId(), lesson.getLessonId()); + + LearnerProgress learnerProgress = learnerProgressDAO.getLearnerProgressByLearner(user.getUserId(), + lesson.getLessonId()); if (learnerProgress == null) { - logger.debug("The learner:" + user.getLogin() + " is joining the lesson:" + lesson.getLessonId()); + logger.debug("The learner:" + user.getLogin() + " is joining the lesson:" + + lesson.getLessonId()); learnerService.joinLesson(user.getUserId(), lesson.getLessonId()); - } else {//don't join to lessons which user is a part of already but make sure time limit is reset + } else {// don't join to lessons which user is a part of already but make sure time limit is reset resetUserTimeLimit(lesson, user); } } - } - - //send email to participant + } + + // send email to participant if ("1".equals(isEmailParticipant)) { boolean isHtmlFormat = false; - - eventNotificationService.sendMessage(user.getUserId().longValue(), DeliveryMethodMail.getInstance(), + + eventNotificationService.sendMessage(null, user.getUserId(), + IEventNotificationService.DELIVERY_METHOD_MAIL, messageService.getMessage("register.user.email.subject"), messageService.getMessage("register.user.email.body", new Object[] { username, password }), isHtmlFormat); } - - //send email to coordinator + + // send email to coordinator if (StringUtils.isNotBlank(isEmailCoordinator)) { boolean isHtmlFormat = false; - + List coordinators = userManagementService.getAllUsersWithEmail(isEmailCoordinator); if ((coordinators == null) || (coordinators.size() == 0)) { throw new RuntimeException("There are no coordinators with email: " + isEmailCoordinator); } User coordinator = coordinators.get(0); - + String registeredUserName = firstName + " " + lastName + " (" + username + ")"; - eventNotificationService.sendMessage(coordinator.getUserId().longValue(), DeliveryMethodMail.getInstance(), - messageService.getMessage("notify.coordinator.register.user.email.subject"), - messageService.getMessage("notify.coordinator.register.user.email.body", new Object[] { registeredUserName }), - isHtmlFormat); + eventNotificationService.sendMessage(null, coordinator.getUserId(), + IEventNotificationService.DELIVERY_METHOD_MAIL, messageService + .getMessage("notify.coordinator.register.user.email.subject"), messageService + .getMessage("notify.coordinator.register.user.email.body", + new Object[] { registeredUserName }), isHtmlFormat); } - + writeAJAXOKResponse(response); - + } catch (Exception e) { logger.error(e.getMessage()); writeAJAXResponse(response, "ERROR: " + e.getMessage()); } } - + /** - * Remove user from group lessons. + * Remove user from group lessons. * * External server call must follow the next format: - * http://<>/lams/central/Register.do?method=removeUserFromGroup&serverId=%serverId%&datetime=%datetime% + * http://<>/lams/central/Register.do?method=removeUserFromGroup + * &serverId=%serverId%&datetime=%datetime% * &hashValue=%hashValue%&courseId=%courseId%&username=%username%&isRemoveFromAllCourses=%isRemoveFromAllCourses% * * Here are the parameters explanation: - * @param method=removeUserFromGroup - selfexplanatory. - * @param serverId - this is a string of characters we'll provide to you - * @param datetime - a character string with the date and time you make this request (format example 2011100608:15:10) - * @param hashValue - The hash value is generated using the SHA1 algorithm on the following (all in lower case) [ datetime + username + method + serverId + serverKey ] - * @param courseId - courseId is essentially a unique identifier for your Functional Speciality (note this is not the name of the Functional Speciality but its unique id) - * @param username - this is your WV Central ID - * @param usePrefix - if set to 1 - force the addition of the server integration prefix to usernames - * @param isRemoveFromAllCourses - if set to 1 -then ignores courseId parameter and removes from all courses + * + * @param method + * =removeUserFromGroup - selfexplanatory. + * @param serverId + * - this is a string of characters we'll provide to you + * @param datetime + * - a character string with the date and time you make this request (format example 2011100608:15:10) + * @param hashValue + * - The hash value is generated using the SHA1 algorithm on the following (all in lower case) [ datetime + * + username + method + serverId + serverKey ] + * @param courseId + * - courseId is essentially a unique identifier for your Functional Speciality (note this is not the + * name of the Functional Speciality but its unique id) + * @param username + * - this is your WV Central ID + * @param usePrefix + * - if set to 1 - force the addition of the server integration prefix to usernames + * @param isRemoveFromAllCourses + * - if set to 1 -then ignores courseId parameter and removes from all courses */ public void removeUserFromGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { - // Check if Server registration is available + // Check if Server registration is available boolean serverToServerEnable = Configuration.getAsBoolean(ConfigurationKeys.ENABLE_SERVER_REGISTRATION); if (!serverToServerEnable) { String msg = "Server to server registration is not enabled"; - logger.error(msg); - response.sendError(response.SC_METHOD_NOT_ALLOWED, msg); + logger.error(msg); + response.sendError(response.SC_METHOD_NOT_ALLOWED, msg); return; } - String method = request.getParameter(CentralConstants.PARAM_METHOD); + String method = request.getParameter(CentralConstants.PARAM_METHOD); String serverId = request.getParameter(CentralConstants.PARAM_SERVER_ID); String datetime = request.getParameter(CentralConstants.PARAM_DATE_TIME); String hashValue = request.getParameter(CentralConstants.PARAM_HASH_VALUE); String groupName = request.getParameter(CentralConstants.PARAM_COURSE_ID); String username = request.getParameter(CentralConstants.PARAM_USERNAME); String isRemoveFromAllCourses = request.getParameter("isRemoveFromAllCourses"); - String usePrefix = request.getParameter("usePrefix"); + String usePrefix = request.getParameter("usePrefix"); if (serverId == null || datetime == null || hashValue == null || username == null) { String msg = "Parameters missing"; logger.error(msg); response.sendError(response.SC_BAD_REQUEST, "Parameters missing"); } - + // authenticate external server ExtServerOrgMap extServer = integrationService.getExtServerOrgMap(serverId); Authenticator.authenticate(extServer, datetime, username, method, hashValue); - // check whether we need to use a prefix for users - if ("1".equals(usePrefix)) { - username = extServer.getPrefix() + "_" + username.trim(); - logger.debug("Adding prefix to username:" + username); - } + // check whether we need to use a prefix for users + if ("1".equals(usePrefix)) { + username = extServer.getPrefix() + "_" + username.trim(); + logger.debug("Adding prefix to username:" + username); + } - //get user from the DB if exists, throws exception otherwise + // get user from the DB if exists, throws exception otherwise ExtUserUseridMap userMap = getExtUserUseridMap(extServer, username); User user = userMap.getUser(); ArrayList lessons = new ArrayList(); if ("1".equals(isRemoveFromAllCourses)) { Set userOrganisations = user.getUserOrganisations(); - - //create list of organisationDtos in order to be able to delete userOrganisations afterwards + + // create list of organisationDtos in order to be able to delete userOrganisations afterwards List organisationDtos = new ArrayList(); for (UserOrganisation userOrganisation : userOrganisations) { Organisation organisation = userOrganisation.getOrganisation(); OrganisationDTO organisationDto = organisation.getOrganisationDTO(); organisationDtos.add(organisationDto); lessons.addAll(organisation.getLessons()); } - + for (OrganisationDTO organisationDto : organisationDtos) { removeGroupMembership(user, organisationDto.getOrganisationID()); } } else { Organisation organisation = getOrganisationByName(groupName); removeGroupMembership(user, organisation.getOrganisationId()); - + lessons.addAll(organisation.getLessons()); } // remove user from lessons removeUserFromLessons(user, lessons); - + writeAJAXOKResponse(response); - + } catch (Exception e) { writeAJAXResponse(response, "ERROR: " + e.getMessage()); } } - + /** - * Resets user's time limit for all lessons in a group with scheduledToCloseForIndividuals setting on. - * In case lesson's time limit is not individual it does nothing. + * Resets user's time limit for all lessons in a group with scheduledToCloseForIndividuals setting on. In case + * lesson's time limit is not individual it does nothing. * * External server call must follow the next format: - * http://<>/lams/central/Register.do?method=resetUserTimeLimit&serverId=%serverId%&datetime=%datetime% - * &hashValue=%hashValue%&courseId=%courseId%&username=%username% + * http://<>/lams/central/Register.do?method=resetUserTimeLimit + * &serverId=%serverId%&datetime=%datetime% &hashValue=%hashValue%&courseId=%courseId%&username=%username% * * Here are the parameters explanation: - * @param method=resetUserTimeLimit - selfexplanatory. - * @param serverId - this is a string of characters we'll provide to you - * @param datetime - a character string with the date and time you make this request (format example 2011100608:15:10) - * @param hashValue - The hash value is generated using the SHA1 algorithm on the following (all in lower case) [ datetime + username + method + serverId + serverKey ] - * @param courseId - courseId is essentially a unique identifier for your Functional Speciality (note this is not the name of the Functional Speciality but its unique id) - * @param username - this is your WV Central ID - * @param usePrefix - if set to 1 - force the addition of the server integration prefix to usernames + * + * @param method + * =resetUserTimeLimit - selfexplanatory. + * @param serverId + * - this is a string of characters we'll provide to you + * @param datetime + * - a character string with the date and time you make this request (format example 2011100608:15:10) + * @param hashValue + * - The hash value is generated using the SHA1 algorithm on the following (all in lower case) [ datetime + * + username + method + serverId + serverKey ] + * @param courseId + * - courseId is essentially a unique identifier for your Functional Speciality (note this is not the + * name of the Functional Speciality but its unique id) + * @param username + * - this is your WV Central ID + * @param usePrefix + * - if set to 1 - force the addition of the server integration prefix to usernames */ public void resetUserTimeLimit(HttpServletRequest request, HttpServletResponse response) throws IOException { try { // Check if Server registration is available boolean serverToServerEnable = Configuration.getAsBoolean(ConfigurationKeys.ENABLE_SERVER_REGISTRATION); if (!serverToServerEnable) { String msg = "Server to server registration is not enabled"; - logger.error(msg); - response.sendError(response.SC_METHOD_NOT_ALLOWED, msg); + logger.error(msg); + response.sendError(response.SC_METHOD_NOT_ALLOWED, msg); return; } @@ -429,29 +476,29 @@ String hashValue = request.getParameter(CentralConstants.PARAM_HASH_VALUE); String courseId = request.getParameter(CentralConstants.PARAM_COURSE_ID); String username = request.getParameter(CentralConstants.PARAM_USERNAME); - String usePrefix = request.getParameter("usePrefix"); + String usePrefix = request.getParameter("usePrefix"); if (serverId == null || datetime == null || hashValue == null || username == null || courseId == null) { String msg = "Parameters missing"; logger.error(msg); response.sendError(response.SC_BAD_REQUEST, "Parameters missing"); } - + // authenticate external server ExtServerOrgMap extServer = integrationService.getExtServerOrgMap(serverId); Authenticator.authenticate(extServer, datetime, username, method, hashValue); - // check whether we need to use a prefix for users - if ("1".equals(usePrefix)) { - username = extServer.getPrefix() + "_" + username.trim(); - logger.debug("Adding prefix to username:" + username); - } + // check whether we need to use a prefix for users + if ("1".equals(usePrefix)) { + username = extServer.getPrefix() + "_" + username.trim(); + logger.debug("Adding prefix to username:" + username); + } - //get user from the DB if exists, throws exception otherwise + // get user from the DB if exists, throws exception otherwise ExtUserUseridMap userMap = getExtUserUseridMap(extServer, username); User user = userMap.getUser(); - //get organisation from DB if exists, throws exception otherwise + // get organisation from DB if exists, throws exception otherwise Organisation org = getOrganisationByName(courseId); // reset time limit @@ -460,15 +507,15 @@ resetUserTimeLimit(lesson, user); } } - + writeAJAXOKResponse(response); - + } catch (Exception e) { logger.error(e.getMessage()); writeAJAXResponse(response, "ERROR: " + e.getMessage()); } } - + /** * resetUserTimeLimit * @@ -490,8 +537,9 @@ } } } - - private ExtUserUseridMap getExtUserUseridMap(ExtServerOrgMap serverMap, String extUsername) throws UserInfoFetchException { + + private ExtUserUseridMap getExtUserUseridMap(ExtServerOrgMap serverMap, String extUsername) + throws UserInfoFetchException { Map properties = new HashMap(); properties.put("extServerOrgMap.sid", serverMap.getSid()); properties.put("extUsername", extUsername); @@ -503,8 +551,8 @@ return (ExtUserUseridMap) list.get(0); } } - - // newer method which accepts course name, a parent org id, a flag for whether user should get + + // newer method which accepts course name, a parent org id, a flag for whether user should get // 'teacher' roles, and a flag for whether to use a prefix in the org's name private Organisation getOrganisationByName(String name) { Map properties = new HashMap(); @@ -518,8 +566,8 @@ return organisation; } } - - // newer method which accepts course name, a parent org id, a flag for whether user should get + + // newer method which accepts course name, a parent org id, a flag for whether user should get // 'teacher' roles, and a flag for whether to use a prefix in the org's name private ExtCourseClassMap getExtCourseClassMap(ExtServerOrgMap serverMap, ExtUserUseridMap userMap, String extCourseId, Boolean isTeacher) { @@ -534,43 +582,43 @@ return map; } } - + private void removeGroupMembership(User user, Integer organisationId) { UserOrganisation userOrganisation = userManagementService.getUserOrganisation(user.getUserId(), organisationId); - + Set userOrganisations = user.getUserOrganisations(); userOrganisations.remove(userOrganisation); userManagementService.save(user); - - //userOrganisation and UserOrganisationRoles will be deleted by Hibernate automatically. + + // userOrganisation and UserOrganisationRoles will be deleted by Hibernate automatically. } - + private void removeUserFromLessons(User user, Collection lessons) { for (Lesson lesson : lessons) { LessonClass grouping = lesson.getLessonClass(); Group group = grouping.getLearnersGroup(); - + boolean isSuccefullyRemoved = group.getUsers().remove(user); if (isSuccefullyRemoved) { logger.debug("Removed user:" + user.getLogin() + " from lesson:" + lesson.getLessonName()); } } } - + protected void writeAJAXResponse(HttpServletResponse response, String output) throws IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); if (output.length() > 0) { out.println(output); } - + out.flush(); out.close(); } protected void writeAJAXOKResponse(HttpServletResponse response) throws IOException { writeAJAXResponse(response, "OK"); } - + } Index: lams_central/web/emailuser.jsp =================================================================== diff -u --- lams_central/web/emailuser.jsp (revision 0) +++ lams_central/web/emailuser.jsp (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -0,0 +1,119 @@ + + +<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=utf-8"%> + +<%@ taglib uri="tags-lams" prefix="lams"%> +<%@ taglib uri="tags-html" prefix="html"%> +<%@ taglib uri="tags-fmt" prefix="fmt"%> +<%@ taglib uri="tags-core" prefix="c"%> + + + + <fmt:message key="title.admin.window" /> + + + + + + + + + + + + +
+
+

+ +

+ + +
+ + +
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
${user.firstName} ${user.lastName} <${user.email}>
disabled="disabled" > +
+
+ +
+ + + + + + + + + +
+
+
+
+ +
Index: lams_common/.classpath =================================================================== diff -u -r76aaa4283f0c9c4b95cae2104bdf453c02ee7721 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_common/.classpath (.../.classpath) (revision 76aaa4283f0c9c4b95cae2104bdf453c02ee7721) +++ lams_common/.classpath (.../.classpath) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -41,4 +41,5 @@ + Index: lams_common/src/java/org/lamsfoundation/lams/events/AbstractDeliveryMethod.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_common/src/java/org/lamsfoundation/lams/events/AbstractDeliveryMethod.java (.../AbstractDeliveryMethod.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_common/src/java/org/lamsfoundation/lams/events/AbstractDeliveryMethod.java (.../AbstractDeliveryMethod.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -6,79 +6,92 @@ /** * Provides methods to notify users of an event. + * * @author Marcin Cieslak - * + * */ public abstract class AbstractDeliveryMethod { - /** - * Short name for the delivery method - */ - protected final String signature; + /** + * Short name for the delivery method + */ + protected final String signature; - /** - * Short description of the delivery method. - */ - protected final String description; + /** + * Short description of the delivery method. + */ + protected final String description; - /** - * Unique identifier of the delivery method. - */ - protected final short id; + /** + * Unique identifier of the delivery method. + */ + protected final short id; - /** - * Maximum time for the message to be send. - */ - protected long sendTimeout = Long.MAX_VALUE; + /** + * Maximum time for the message to be send. + */ + protected long sendTimeout = Long.MAX_VALUE; - /** - * Standard constructor. - * @param id ID of the delivery method - * @param signature signature of the delivery method - * @param description short description of the delivery method - * @throws InvalidParameterException if signature is blank - */ - protected AbstractDeliveryMethod(short id, String signature, String description) throws InvalidParameterException { - if (StringUtils.isEmpty(signature)) { - throw new InvalidParameterException("Signature can not be blank."); - } - this.signature = signature; - this.description = description; - this.id = id; + /** + * Standard constructor. + * + * @param id + * ID of the delivery method + * @param signature + * signature of the delivery method + * @param description + * short description of the delivery method + * @throws InvalidParameterException + * if signature is blank + */ + protected AbstractDeliveryMethod(short id, String signature, String description) throws InvalidParameterException { + if (StringUtils.isEmpty(signature)) { + throw new InvalidParameterException("Signature must not be blank."); } + this.signature = signature; + this.description = description; + this.id = id; + } - /** - * Sends the message to the user. - * @param userId ID of the user - * @param subject subject of the message - * @param message text of the message - * @param isHtmlFormat whether the message is of HTML content-type or plain text - * @return null if the operation was successful; error message if it failed - * @throws InvalidParameterException - */ - protected abstract String send(Long userId, String subject, String message, boolean isHtmlFormat) throws InvalidParameterException; + /** + * Sends the message to the user. + * + * @param toUserId + * ID of the user + * @param subject + * subject of the message + * @param message + * text of the message + * @param isHtmlFormat + * whether the message is of HTML content-type or plain text + * @return null if the operation was successful; error message if it failed + * @throws InvalidParameterException + */ + protected abstract String send(Integer fromUserId, Integer toUserId, String subject, String message, + boolean isHtmlFormat) throws InvalidParameterException; - public String getSignature() { - return signature; - } + public String getSignature() { + return signature; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - @Override - public boolean equals(Object o) { - return o instanceof AbstractDeliveryMethod && ((AbstractDeliveryMethod) o).signature.equalsIgnoreCase(signature); - } + @Override + public boolean equals(Object o) { + return (o instanceof AbstractDeliveryMethod) + && ((AbstractDeliveryMethod) o).signature.equalsIgnoreCase(signature); + } - public short getId() { - return id; - } + public short getId() { + return id; + } - public long getSendTimeout() { - return sendTimeout; - } + public long getSendTimeout() { + return sendTimeout; + } - public void setSendTimeout(long sendTimeout) { - this.sendTimeout = sendTimeout; - } + public void setSendTimeout(long sendTimeout) { + this.sendTimeout = sendTimeout; + } } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/events/DeliveryMethodMail.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_common/src/java/org/lamsfoundation/lams/events/DeliveryMethodMail.java (.../DeliveryMethodMail.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_common/src/java/org/lamsfoundation/lams/events/DeliveryMethodMail.java (.../DeliveryMethodMail.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -2,13 +2,17 @@ import java.io.UnsupportedEncodingException; import java.security.InvalidParameterException; +import java.util.Properties; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import org.apache.commons.lang.StringUtils; +import org.apache.commons.validator.EmailValidator; +import org.apache.log4j.Logger; import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.util.Configuration; +import org.lamsfoundation.lams.util.ConfigurationKeys; import org.lamsfoundation.lams.util.Emailer; /** @@ -20,27 +24,45 @@ public class DeliveryMethodMail extends AbstractDeliveryMethod { private static DeliveryMethodMail instance; + protected static final EmailValidator emailValidator = EmailValidator.getInstance(); + private static final Logger log = Logger.getLogger(DeliveryMethodMail.class); protected DeliveryMethodMail() { super((short) 1, "MAIL", "Messages will be send by Mail"); } @Override - public String send(Long userId, String subject, String message, boolean isHtmlFormat) throws InvalidParameterException { - if (userId == null) { - return "User ID should not be null."; + public String send(Integer fromUserId, Integer toUserId, String subject, String message, boolean isHtmlFormat) + throws InvalidParameterException { + if (toUserId == null) { + log.error("Target user ID must not be null."); } try { - User user = (User) EventNotificationService.getInstance().getUserManagementService().findById(User.class, - userId.intValue()); - if (user == null) { - return "User with the provided ID was not found."; + User toUser = (User) EventNotificationService.getInstance().getUserManagementService() + .findById(User.class, toUserId); + if (toUser == null) { + log.error("Target user with ID " + toUserId + " was not found."); } - String email = user.getEmail(); - if (StringUtils.isBlank(email)) { - return "User's e-mail address is blank."; + String toEmail = toUser.getEmail(); + if (!DeliveryMethodMail.emailValidator.isValid(toEmail)) { + return "Target user's e-mail address is invalid."; } - sendFromSupportEmail(subject, email, message, isHtmlFormat); + + if (fromUserId == null) { + Emailer.sendFromSupportEmail(subject, toEmail, message, isHtmlFormat); + } else { + User fromUser = (User) EventNotificationService.getInstance().getUserManagementService() + .findById(User.class, toUserId); + if (fromUser == null) { + log.error("Source user with ID " + toUserId + " was not found."); + } + String fromEmail = fromUser.getEmail(); + if (!DeliveryMethodMail.emailValidator.isValid(fromEmail)) { + return "Source user's e-mail address is invalid."; + } + + Emailer.send(subject, toEmail, fromEmail, message, isHtmlFormat, new Properties()); + } return null; } catch (Exception e) { return e.toString(); @@ -55,27 +77,6 @@ } /** - * Sends an email sourced from admin. Copied from Emailer class. - * - * @param subject - * subject of the message - * @param to - * address to send - * @param body - * text of the message - * @param isHtmlFormat - * whether the message is of HTML content-type or plain text - * @throws AddressException - * if address was incorrect - * @throws MessagingException - * if the operation failed - */ - public void sendFromSupportEmail(String subject, String to, String body, boolean isHtmlFormat) throws AddressException, - MessagingException, UnsupportedEncodingException { - Emailer.sendFromSupportEmail(subject, to, body, isHtmlFormat); - } - - /** * Sends an email to the address provided by the admin. * * @param subject @@ -85,16 +86,20 @@ * * @param isHtmlFormat * whether the message is of HTML content-type or plain text + * @throws UnsupportedEncodingException * @throws AddressException * if address was incorrect * @throws MessagingException * if the operation failed */ void notifyAdmin(String subject, String body, boolean isHtmlFormat) throws AddressException, - MessagingException, UnsupportedEncodingException { - String adminEmail = Configuration.get("LamsSupportEmail"); - if (!StringUtils.isEmpty(adminEmail)) { - sendFromSupportEmail(subject, adminEmail, body, isHtmlFormat); + UnsupportedEncodingException, MessagingException { + String adminEmail = Configuration.get(ConfigurationKeys.LAMS_ADMIN_EMAIL); + if (StringUtils.isEmpty(adminEmail)) { + DeliveryMethodMail.log.warn("Could not notify admin as his email is blank. The subject: " + subject + + ". The message: " + body); + } else { + Emailer.sendFromSupportEmail(subject, adminEmail, body, isHtmlFormat); } } } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/events/Event.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_common/src/java/org/lamsfoundation/lams/events/Event.java (.../Event.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_common/src/java/org/lamsfoundation/lams/events/Event.java (.../Event.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -14,481 +14,489 @@ * * @hibernate.class table="lams_events" * @author Marcin Cieslak - * + * */ public class Event { - //--------- persistent fields ------------- - /** - * Unique ID for Hibernate needs. - */ - private Long uid; + // --------- persistent fields ------------- + /** + * Unique ID for Hibernate needs. + */ + private Long uid; - /** - * Name of the event. - */ - protected String name; + /** + * Name of the event. + */ + protected String name; - /** - * Scope of the event. - * For events that are common for the whole LAMS environment, - * {@link EventNotificationService#CORE_EVENTS_SCOPE} should be used. - * For tools their signature should be used. - */ - protected String scope; + /** + * Scope of the event. For events that are common for the whole LAMS environment, + * {@link EventNotificationService#CORE_EVENTS_SCOPE} should be used. For tools their signature should be used. + */ + protected String scope; - /** - * Identifier for a session in which the event is valid. - * or events that are common for the whole LAMS environment null can be used. - * For tools their content ID should be used. - */ - protected Long eventSessionId; + /** + * Identifier for a session in which the event is valid. or events that are common for the whole LAMS environment + * null can be used. For tools their content ID should be used. + */ + protected Long eventSessionId; - /** - * Was the event triggered (did it happen). - */ - protected Boolean triggered = false; + /** + * Was the event triggered (did it happen). + */ + protected Boolean triggered = false; - /** - * Set of users that are subscribed to this event, along with the required data. - */ - protected Set subscriptions = new HashSet(); + /** + * Set of users that are subscribed to this event, along with the required data. + */ + protected Set subscriptions = new HashSet(); - /** - * Default message that will be send when the event is triggered and no other message is or was provided. - */ - protected String defaultMessage; + /** + * Default message that will be send when the event is triggered and no other message is or was provided. + */ + protected String defaultMessage; - /** - * Default subject of the message that will be send when the event is triggered and no other message is or was provided. - */ - protected String defaultSubject; + /** + * Default subject of the message that will be send when the event is triggered and no other message is or was + * provided. + */ + protected String defaultSubject; - /** - * Message that will be send when the event is triggered. - */ - protected String message; + /** + * Message that will be send when the event is triggered. + */ + protected String message; - /** - * Subject of the message that will be send when the event is triggered. - */ - protected String subject; - - /** - * Boolean indicates whether the message should be sent as text/html content or regular text/plain one - */ - protected boolean htmlFormat; + /** + * Subject of the message that will be send when the event is triggered. + */ + protected String subject; - /** - * If sending notifications fails, this property holds the time of this failure. - */ - protected Date failTime; + /** + * Boolean indicates whether the message should be sent as text/html content or regular text/plain one + */ + protected boolean htmlFormat; - // -------------- non-persistent fields -------------- - /** - * Label that identifies the event. - */ - protected String fullSignature; + /** + * If sending notifications fails, this property holds the time of this failure. + */ + protected Date failTime; - /** - * Used for event instance management in EventNotificationService. - */ - protected int referenceCounter; + // -------------- non-persistent fields -------------- + /** + * Label that identifies the event. + */ + protected String fullSignature; - /** - * Thread that notifies users of the event. - * Since sending messages to multiple users can take some time, - * another thread is responsible for that, so the main one does not get blocked. - */ - protected Thread notificationThread; + /** + * Used for event instance management in EventNotificationService. + */ + protected int referenceCounter; - /** - * Should the event be deleted from the database. - */ - protected boolean deleted; + /** + * Thread that notifies users of the event. Since sending messages to multiple users can take some time, another + * thread is responsible for that, so the main one does not get blocked. + */ + protected Thread notificationThread; - public Event() { + /** + * Should the event be deleted from the database. + */ + protected boolean deleted; - } + public Event() { - /** - * Standard constructor used by EventNotificationService. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @param defaultSubject subject of the message to send - * @param defaultMessage body of the message to send - * @throws InvalidParameterException if scope is null or name is blank - */ - public Event(String scope, String name, Long sessionId, String defaultSubject, String defaultMessage, - boolean isHtmlContentType) - throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Event scope can not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Event name can not be blank."); - } - this.scope = scope; - this.name = name; - eventSessionId = sessionId; - this.defaultSubject = defaultSubject; - this.defaultMessage = defaultMessage; - this.htmlFormat = isHtmlContentType; - fullSignature = createFullSignature(scope, name, sessionId); - } + } - /** - * Build a string that identifies the event. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @return event signature of the event - * @throws InvalidParameterException if scope is null or name is blank - */ - protected static String createFullSignature(String scope, String name, Long sessionId) throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - return scope + '_' + name + (sessionId == null ? "" : "_" + sessionId); + /** + * Standard constructor used by EventNotificationService. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @param defaultSubject + * subject of the message to send + * @param defaultMessage + * body of the message to send + * @throws InvalidParameterException + * if scope is null or name is blank + */ + public Event(String scope, String name, Long sessionId, String defaultSubject, String defaultMessage, + boolean isHtmlContentType) throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Event scope can not be null."); } - - @Override - public Object clone() { - Event clone = new Event(scope, name, eventSessionId, defaultSubject, defaultMessage, htmlFormat); - for (Subscription subscription : getSubscriptions()) { - clone.getSubscriptions().add((Subscription) subscription.clone()); - } - return clone; + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Event name can not be blank."); } + this.scope = scope; + this.name = name; + eventSessionId = sessionId; + this.defaultSubject = defaultSubject; + this.defaultMessage = defaultMessage; + this.htmlFormat = isHtmlContentType; + fullSignature = Event.createFullSignature(scope, name, sessionId); + } - /** - * Full signature is compared. - */ - @Override - public boolean equals(Object o) { - return o instanceof Event && ((Event) o).getFullSignature().equalsIgnoreCase(getFullSignature()) - || o instanceof CharSequence && ((CharSequence) o).toString().equalsIgnoreCase(getFullSignature()); + /** + * Build a string that identifies the event. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @return event signature of the event + * @throws InvalidParameterException + * if scope is null or name is blank + */ + protected static String createFullSignature(String scope, String name, Long sessionId) + throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } - - @Override - public int hashCode() { - return getFullSignature().hashCode(); + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); } + return scope + '_' + name + (sessionId == null ? "" : "_" + sessionId); + } - /** - * @hibernate.property column="default_message" - * @return - */ - protected String getDefaultMessage() { - return defaultMessage; + @Override + public Object clone() { + Event clone = new Event(scope, name, eventSessionId, defaultSubject, defaultMessage, htmlFormat); + for (Subscription subscription : getSubscriptions()) { + clone.getSubscriptions().add((Subscription) subscription.clone()); } + return clone; + } - /** - * @hibernate.property column="default_subject" - * @return - */ - protected String getDefaultSubject() { - return defaultSubject; - } + /** + * Full signature is compared. + */ + @Override + public boolean equals(Object o) { + return ((o instanceof Event) && ((Event) o).getFullSignature().equalsIgnoreCase(getFullSignature())) + || ((o instanceof CharSequence) && ((CharSequence) o).toString().equalsIgnoreCase(getFullSignature())); + } - protected String getFullSignature() { - if (fullSignature == null) { - fullSignature = createFullSignature(getScope(), getName(), getEventSessionId()); - } - return fullSignature; - } + @Override + public int hashCode() { + return getFullSignature().hashCode(); + } - /** - * @hibernate.property column="name" length="128" - * @return - */ - protected String getName() { - return name; - } + /** + * @hibernate.property column="default_message" + * @return + */ + protected String getDefaultMessage() { + return defaultMessage; + } - /** - * @hibernate.property column="scope" length="128" - * @return - */ - protected String getScope() { - return scope; - } + /** + * @hibernate.property column="default_subject" + * @return + */ + protected String getDefaultSubject() { + return defaultSubject; + } - /** - * @hibernate.property column="event_session_id" - * @return - */ - protected Long getEventSessionId() { - return eventSessionId; + protected String getFullSignature() { + if (fullSignature == null) { + fullSignature = Event.createFullSignature(getScope(), getName(), getEventSessionId()); } + return fullSignature; + } - /** - * - * @hibernate.set cascade="all-delete-orphan" order-by="last_operation_time desc" outer-join="true" - * @hibernate.collection-key column="event_uid" - * @hibernate.collection-one-to-many class="org.lamsfoundation.lams.events.Subscription" - * - * @return - */ - protected Set getSubscriptions() { - return subscriptions; - } + /** + * @hibernate.property column="name" length="128" + * @return + */ + protected String getName() { + return name; + } - /** - * @hibernate.id column="uid" generator-class="native" - */ - protected Long getUid() { - return uid; - } + /** + * @hibernate.property column="scope" length="128" + * @return + */ + protected String getScope() { + return scope; + } - /** - * @hibernate.property column="triggered" - * @return - */ - protected boolean isTriggered() { - return triggered; - } + /** + * @hibernate.property column="event_session_id" + * @return + */ + protected Long getEventSessionId() { + return eventSessionId; + } - /** - * See {@link IEventNotificationService#triggerForSingleUser(String, String, Long, Long)} - */ - protected boolean triggerForSingleUser(Long userId, String subject, String message) throws InvalidParameterException { - if (userId == null) { - throw new InvalidParameterException("User ID can not be null."); - } + /** + * + * @hibernate.set cascade="all-delete-orphan" order-by="last_operation_time desc" outer-join="true" + * @hibernate.collection-key column="event_uid" + * @hibernate.collection-one-to-many class="org.lamsfoundation.lams.events.Subscription" + * + * @return + */ + protected Set getSubscriptions() { + return subscriptions; + } - List subscriptionList = new ArrayList(getSubscriptions()); - for (int index = 0; index < subscriptionList.size(); index++) { - Subscription subscription = subscriptionList.get(index); - if (subscription.getUserId().equals(userId) && subscription.isEligibleForNotification()) { - subscription.notifyUser(subject, message, this.isHtmlFormat()); - return subscription.getLastOperationSuccessful(); - } - } - return false; - } + /** + * @hibernate.id column="uid" generator-class="native" + */ + protected Long getUid() { + return uid; + } - protected void setDefaultMessage(String defaultMessage) { - this.defaultMessage = defaultMessage; - } + /** + * @hibernate.property column="triggered" + * @return + */ + protected boolean isTriggered() { + return triggered; + } - protected void setDefaultSubject(String defaultSubject) { - this.defaultSubject = defaultSubject; + /** + * See {@link IEventNotificationService#triggerForSingleUser(String, String, Long, Long)} + */ + protected boolean triggerForSingleUser(Integer userId, String subject, String message) + throws InvalidParameterException { + if (userId == null) { + throw new InvalidParameterException("User ID can not be null."); } - protected void setName(String name) { - this.name = name; + List subscriptionList = new ArrayList(getSubscriptions()); + for (int index = 0; index < subscriptionList.size(); index++) { + Subscription subscription = subscriptionList.get(index); + if (subscription.getUserId().equals(userId) && subscription.isEligibleForNotification()) { + subscription.notifyUser(subject, message, this.isHtmlFormat()); + return subscription.getLastOperationSuccessful(); + } } + return false; + } - protected void setScope(String scope) { - this.scope = scope; - } + protected void setDefaultMessage(String defaultMessage) { + this.defaultMessage = defaultMessage; + } - protected void setEventSessionId(Long sessionId) { - eventSessionId = sessionId; - } + protected void setDefaultSubject(String defaultSubject) { + this.defaultSubject = defaultSubject; + } - protected void setSubscriptions(Set subscriptions) { - this.subscriptions = subscriptions; - } + protected void setName(String name) { + this.name = name; + } - protected void setTriggered(boolean triggered) { - this.triggered = triggered; - } + protected void setScope(String scope) { + this.scope = scope; + } - protected void setUid(Long uid) { - this.uid = uid; - } + protected void setEventSessionId(Long sessionId) { + eventSessionId = sessionId; + } - /** - * See {@link IEventNotificationService#subscribe(String, String, Long, Long, AbstractDeliveryMethod, Long) + protected void setSubscriptions(Set subscriptions) { + this.subscriptions = subscriptions; + } + + protected void setTriggered(boolean triggered) { + this.triggered = triggered; + } + + protected void setUid(Long uid) { + this.uid = uid; + } + + /** + * See {@link IEventNotificationService#subscribe(String, String, Long, Long, AbstractDeliveryMethod, Long) * - */ - protected boolean subscribe(Long userId, AbstractDeliveryMethod deliveryMethod, Long periodicity) - throws InvalidParameterException { - if (userId == null) { - throw new InvalidParameterException("User ID can not be null."); + */ + protected boolean subscribe(Integer userId, AbstractDeliveryMethod deliveryMethod, Long periodicity) + throws InvalidParameterException { + if (userId == null) { + throw new InvalidParameterException("User ID can not be null."); + } + if (deliveryMethod == null) { + throw new InvalidParameterException("Delivery method can not be null."); + } + boolean substriptionFound = false; + Subscription toSubscribe = new Subscription(userId, deliveryMethod, periodicity); + List subscriptionList = new ArrayList(getSubscriptions()); + for (int index = 0; index < subscriptionList.size(); index++) { + Subscription subscription = subscriptionList.get(index); + if (subscription.equals(toSubscribe)) { + substriptionFound = true; + if (!subscription.getPeriodicity().equals(periodicity)) { + subscription.setPeriodicity(periodicity); } - if (deliveryMethod == null) { - throw new InvalidParameterException("Delivery method can not be null."); - } - boolean substriptionFound = false; - Subscription toSubscribe = new Subscription(userId, deliveryMethod, periodicity); - List subscriptionList = new ArrayList(getSubscriptions()); - for (int index = 0; index < subscriptionList.size(); index++) { - Subscription subscription = subscriptionList.get(index); - if (subscription.equals(toSubscribe)) { - substriptionFound = true; - if (!subscription.getPeriodicity().equals(periodicity)) { - subscription.setPeriodicity(periodicity); - } - } - } - if (!substriptionFound) { - getSubscriptions().add(new Subscription(userId, deliveryMethod, periodicity)); - return true; - } - return false; - + } } + if (!substriptionFound) { + getSubscriptions().add(new Subscription(userId, deliveryMethod, periodicity)); + return true; + } + return false; - /** - * See {@link IEventNotificationService#trigger(String, String, Long, String, String) - */ - protected void trigger(String subject, String message) { - if (notificationThread == null || !notificationThread.isAlive()) { - triggered = true; + } - if (subject != null && subject.equals(getDefaultSubject())) { - setSubject(null); - } - else { - setSubject(subject); - } + /** + * See {@link IEventNotificationService#trigger(String, String, Long, String, String) + */ + protected void trigger(String subject, String message) { + if ((notificationThread == null) || !notificationThread.isAlive()) { + triggered = true; - if (message != null && message.equals(getDefaultMessage())) { - setMessage(null); - } - else { - setMessage(message); - } + if ((subject != null) && subject.equals(getDefaultSubject())) { + setSubject(null); + } else { + setSubject(subject); + } - final String subjectToSend = getSubject() == null ? getDefaultSubject() : getSubject(); - final String messageToSend = getMessage() == null ? getDefaultMessage() : getMessage(); - final boolean isHtmlContentType = isHtmlFormat(); - final Event finalRef = this; - notificationThread = new Thread(new Runnable() { - public void run() { - List subscriptionList = new ArrayList(getSubscriptions()); - Event eventFailCopy = null; - for (int index = 0; index < subscriptionList.size(); index++) { - Subscription subscription = subscriptionList.get(index); - if (getFailTime() != null || subscription.isEligibleForNotification()) { - subscription.notifyUser(subjectToSend, messageToSend, isHtmlContentType); - if (subscription.getLastOperationSuccessful()) { - if (getFailTime() != null) { - getSubscriptions().remove(subscription); - } - } - else if (getFailTime() == null) { - if (eventFailCopy == null) { - eventFailCopy = (Event) finalRef.clone(); - eventFailCopy.referenceCounter++; - eventFailCopy.getSubscriptions().clear(); - } - eventFailCopy.subscribe(subscription.getUserId(), subscription.getDeliveryMethod(), subscription - .getPeriodicity()); - } - } - } - EventNotificationService.getInstance().saveEvent(finalRef); + if ((message != null) && message.equals(getDefaultMessage())) { + setMessage(null); + } else { + setMessage(message); + } - /* - * if any of the notifications failed, - * a copy of the event is created in order to repeat the attempt later - */ - if (eventFailCopy != null && !eventFailCopy.getSubscriptions().isEmpty()) { - eventFailCopy.setFailTime(new Date()); - eventFailCopy.setDefaultSubject(subjectToSend); - eventFailCopy.setDefaultMessage(messageToSend); - eventFailCopy.setTriggered(true); - EventNotificationService.getInstance().saveEvent(eventFailCopy); - } - } - }, "LAMS_" + getFullSignature() + "_notification_thread"); - notificationThread.start(); - } - } - - /** - * See {@link IEventNotificationService#unsubscribe(String, String, Long, Long) - */ - protected boolean unsubscribe(Long userId) throws InvalidParameterException { - if (userId == null) { - throw new InvalidParameterException("User ID can not be null."); - } - List subscriptionList = new ArrayList(getSubscriptions()); - boolean subscriptionFound = false; - for (int index = 0; index < subscriptionList.size(); index++) { + final String subjectToSend = getSubject() == null ? getDefaultSubject() : getSubject(); + final String messageToSend = getMessage() == null ? getDefaultMessage() : getMessage(); + final boolean isHtmlContentType = isHtmlFormat(); + final Event finalRef = this; + notificationThread = new Thread(new Runnable() { + @Override + public void run() { + List subscriptionList = new ArrayList(getSubscriptions()); + Event eventFailCopy = null; + for (int index = 0; index < subscriptionList.size(); index++) { Subscription subscription = subscriptionList.get(index); - if (subscription.getUserId().equals(userId)) { - getSubscriptions().remove(subscription); - subscriptionFound = true; + if ((getFailTime() != null) || subscription.isEligibleForNotification()) { + subscription.notifyUser(subjectToSend, messageToSend, isHtmlContentType); + if (subscription.getLastOperationSuccessful()) { + if (getFailTime() != null) { + getSubscriptions().remove(subscription); + } + } else if (getFailTime() == null) { + if (eventFailCopy == null) { + eventFailCopy = (Event) finalRef.clone(); + eventFailCopy.referenceCounter++; + eventFailCopy.getSubscriptions().clear(); + } + eventFailCopy.subscribe(subscription.getUserId(), subscription.getDeliveryMethod(), + subscription.getPeriodicity()); + } } - } - return subscriptionFound; - } + } + EventNotificationService.getInstance().saveEvent(finalRef); - /** - * See {@link IEventNotificationService#unsubscribe(String, String, Long, Long, AbstractDeliveryMethod) - */ - protected boolean unsubscribe(Long userId, AbstractDeliveryMethod deliveryMethod) throws InvalidParameterException { - if (userId == null) { - throw new InvalidParameterException("User ID can not be null."); + /* + * if any of the notifications failed, + * a copy of the event is created in order to repeat the attempt later + */ + if ((eventFailCopy != null) && !eventFailCopy.getSubscriptions().isEmpty()) { + eventFailCopy.setFailTime(new Date()); + eventFailCopy.setDefaultSubject(subjectToSend); + eventFailCopy.setDefaultMessage(messageToSend); + eventFailCopy.setTriggered(true); + EventNotificationService.getInstance().saveEvent(eventFailCopy); + } } - if (deliveryMethod == null) { - throw new InvalidParameterException("Delivery method can not be null."); - } - List subscriptionList = new ArrayList(getSubscriptions()); - for (int index = 0; index < subscriptionList.size(); index++) { - Subscription subscription = subscriptionList.get(index); - if (subscription.getUserId().equals(userId) && subscription.getDeliveryMethod().equals(deliveryMethod)) { - getSubscriptions().remove(subscription); - return true; - } - } - return false; + }, "LAMS_" + getFullSignature() + "_notification_thread"); + notificationThread.start(); } + } - /** - * @hibernate.property column="fail_time" - * @return - */ - protected Date getFailTime() { - return failTime; + /** + * See {@link IEventNotificationService#unsubscribe(String, String, Long, Long) + */ + protected boolean unsubscribe(Integer userId) throws InvalidParameterException { + if (userId == null) { + throw new InvalidParameterException("User ID can not be null."); } - - protected void setFailTime(Date failTime) { - this.failTime = failTime; + List subscriptionList = new ArrayList(getSubscriptions()); + boolean subscriptionFound = false; + for (int index = 0; index < subscriptionList.size(); index++) { + Subscription subscription = subscriptionList.get(index); + if (subscription.getUserId().equals(userId)) { + getSubscriptions().remove(subscription); + subscriptionFound = true; + } } + return subscriptionFound; + } - /** - * @hibernate.property column="message" - * @return - */ - protected String getMessage() { - return message; + /** + * See {@link IEventNotificationService#unsubscribe(String, String, Long, Long, AbstractDeliveryMethod) + */ + protected boolean unsubscribe(Integer userId, AbstractDeliveryMethod deliveryMethod) throws InvalidParameterException { + if (userId == null) { + throw new InvalidParameterException("User ID can not be null."); } - - protected void setMessage(String message) { - this.message = message; + if (deliveryMethod == null) { + throw new InvalidParameterException("Delivery method can not be null."); } - - /** - * @hibernate.property column="subject" - * @return - */ - protected String getSubject() { - return subject; + List subscriptionList = new ArrayList(getSubscriptions()); + for (int index = 0; index < subscriptionList.size(); index++) { + Subscription subscription = subscriptionList.get(index); + if (subscription.getUserId().equals(userId) && subscription.getDeliveryMethod().equals(deliveryMethod)) { + getSubscriptions().remove(subscription); + return true; + } } + return false; + } - protected void setSubject(String subject) { - this.subject = subject; - } - - /** - * @hibernate.property column="html_format" length="1" - * @return - */ - protected boolean isHtmlFormat() { - return htmlFormat; - } + /** + * @hibernate.property column="fail_time" + * @return + */ + protected Date getFailTime() { + return failTime; + } - protected void setHtmlFormat(boolean isHtmlContentType) { - this.htmlFormat = isHtmlContentType; - } + protected void setFailTime(Date failTime) { + this.failTime = failTime; + } + + /** + * @hibernate.property column="message" + * @return + */ + protected String getMessage() { + return message; + } + + protected void setMessage(String message) { + this.message = message; + } + + /** + * @hibernate.property column="subject" + * @return + */ + protected String getSubject() { + return subject; + } + + protected void setSubject(String subject) { + this.subject = subject; + } + + /** + * @hibernate.property column="html_format" length="1" + * @return + */ + protected boolean isHtmlFormat() { + return htmlFormat; + } + + protected void setHtmlFormat(boolean isHtmlContentType) { + this.htmlFormat = isHtmlContentType; + } } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/events/EventNotificationService.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_common/src/java/org/lamsfoundation/lams/events/EventNotificationService.java (.../EventNotificationService.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_common/src/java/org/lamsfoundation/lams/events/EventNotificationService.java (.../EventNotificationService.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -18,581 +18,574 @@ /** * Provides tools for managing events and notifing users. + * * @author Marcin Cieslak - * + * */ class EventNotificationService implements IEventNotificationService { - /** - * The only instance of this class, since it is a singleton. - */ - private static EventNotificationService instance; + /** + * The only instance of this class, since it is a singleton. + */ + private static EventNotificationService instance; - /** - * Scope for events that were created after {@link #sendMessage(Long, AbstractDeliveryMethod, String, String)} failed. - */ - protected static final String SINGLE_MESSAGE_SCOPE = "SINGLE_MESSAGE"; + /** + * Contains message delivery methods that are available for programmers. + */ + protected final static Set availableDeliveryMethods = new HashSet(2); - /** - * Contains message delivery methods that are available for programmers. - */ - protected final static Set availableDeliveryMethods = new HashSet(2); + /** + * Contains events that are currently in use. Prevents multiple loading of an event from the database. + */ + protected final static Set eventPool = new HashSet(); - /** - * Contains events that are currently in use. - * Prevents multiple loading of an event from the database. - */ - protected final static Set eventPool = new HashSet(); + protected static final Logger log = Logger.getLogger(EventNotificationService.class); - protected static final Logger log = Logger.getLogger(EventNotificationService.class); + /** + * How often the attempts to resend messages should be taken (in miliseconds). Currently - every hour. + */ + private static final long RESEND_FREQUENCY = 60 * 60 * 1000; - /** - * How often the attempts to resend messages should be taken (in miliseconds). Currently - every hour. - */ - private static final long RESEND_FREQUENCY = 60 * 60 * 1000; + /** + * Interface to contact the database. + */ + protected EventDAO eventDAO; - /** - * Interface to contact the database. - */ - protected EventDAO eventDAO; + /** + * Interface to receive contact details of the users. + */ + protected IUserManagementService userManagementService; - /** - * Interface to receive contact details of the users. - */ - protected IUserManagementService userManagementService; + protected MessageService messageService; - protected MessageService messageService; + /** + * Quartz scheduler used for resending messages. + */ + private Scheduler scheduler; + /** + * Name of the Quartz job that resends messages. + */ + private final static String RESEND_MESSAGES_JOB_NAME = "Resend Messages Job"; + /** + * Name of the Quartz trigger that resends messages. + */ + private final static String RESEND_MESSAGES_TRIGGER_NAME = "Resend Messages Job trigger"; - /** - * Quartz scheduler used for resending messages. - */ - private Scheduler scheduler; - /** - * Name of the Quartz job that resends messages. - */ - private final static String RESEND_MESSAGES_JOB_NAME = "Resend Messages Job"; - /** - * Name of the Quartz trigger that resends messages. - */ - private final static String RESEND_MESSAGES_TRIGGER_NAME = "Resend Messages Job trigger"; - - /** - * Default constructor. Should be called only once, since this class in a singleton. - * @param scheduler scheduler injected by Spring - */ - public EventNotificationService(Scheduler scheduler) { - if (EventNotificationService.instance == null) { - EventNotificationService.instance = this; - this.scheduler = scheduler; - EventNotificationService.availableDeliveryMethods.add(IEventNotificationService.DELIVERY_METHOD_MAIL); - try { - JobDetail resendMessagesJobDetail = getScheduler().getJobDetail( - EventNotificationService.RESEND_MESSAGES_JOB_NAME, Scheduler.DEFAULT_GROUP); - if (resendMessagesJobDetail == null) { - resendMessagesJobDetail = new JobDetail(EventNotificationService.RESEND_MESSAGES_JOB_NAME, - Scheduler.DEFAULT_GROUP, ResendMessagesJob.class); - resendMessagesJobDetail.setDescription(""); - Trigger resendMessageTrigger = new SimpleTrigger(EventNotificationService.RESEND_MESSAGES_TRIGGER_NAME, - Scheduler.DEFAULT_GROUP, SimpleTrigger.REPEAT_INDEFINITELY, EventNotificationService.RESEND_FREQUENCY); - getScheduler().scheduleJob(resendMessagesJobDetail, resendMessageTrigger); - } - getScheduler().start(); - } - catch (SchedulerException e) { - EventNotificationService.log.error(e.getMessage()); - } + /** + * Default constructor. Should be called only once, since this class in a singleton. + * + * @param scheduler + * scheduler injected by Spring + */ + public EventNotificationService(Scheduler scheduler) { + if (EventNotificationService.instance == null) { + EventNotificationService.instance = this; + this.scheduler = scheduler; + EventNotificationService.availableDeliveryMethods.add(IEventNotificationService.DELIVERY_METHOD_MAIL); + try { + JobDetail resendMessagesJobDetail = getScheduler().getJobDetail( + EventNotificationService.RESEND_MESSAGES_JOB_NAME, Scheduler.DEFAULT_GROUP); + if (resendMessagesJobDetail == null) { + resendMessagesJobDetail = new JobDetail(EventNotificationService.RESEND_MESSAGES_JOB_NAME, + Scheduler.DEFAULT_GROUP, ResendMessagesJob.class); + resendMessagesJobDetail.setDescription(""); + Trigger resendMessageTrigger = new SimpleTrigger( + EventNotificationService.RESEND_MESSAGES_TRIGGER_NAME, Scheduler.DEFAULT_GROUP, + SimpleTrigger.REPEAT_INDEFINITELY, EventNotificationService.RESEND_FREQUENCY); + getScheduler().scheduleJob(resendMessagesJobDetail, resendMessageTrigger); } + getScheduler().start(); + } catch (SchedulerException e) { + EventNotificationService.log.error(e.getMessage()); + } } + } - /** - * Gets the only existing instance of the class. - * @return instance of this class - */ - public static EventNotificationService getInstance() { - return EventNotificationService.instance; - } + /** + * Gets the only existing instance of the class. + * + * @return instance of this class + */ + public static EventNotificationService getInstance() { + return EventNotificationService.instance; + } - /** - * Allows to plug-in a delivery method. - * @param deliveryMethod delivery method to add - * @return true if the delivery method with the same ID did not exist and the given delivery method was added successfuly - */ - public boolean addDeliveryMethod(AbstractDeliveryMethod deliveryMethod) { - return EventNotificationService.availableDeliveryMethods.add(deliveryMethod); - } + /** + * Allows to plug-in a delivery method. + * + * @param deliveryMethod + * delivery method to add + * @return true if the delivery method with the same ID did not exist and the given delivery method was + * added successfuly + */ + public boolean addDeliveryMethod(AbstractDeliveryMethod deliveryMethod) { + return EventNotificationService.availableDeliveryMethods.add(deliveryMethod); + } - @Override - public boolean createEvent(String scope, String name, Long eventSessionId, String defaultSubject, + @Override + public boolean createEvent(String scope, String name, Long eventSessionId, String defaultSubject, String defaultMessage, boolean isHtmlFormat) throws InvalidParameterException { - Event event = getEvent(scope, name, eventSessionId); - if (event != null) { - saveEvent(event); - return false; - } - event = new Event(scope, name, eventSessionId, defaultSubject, defaultMessage, isHtmlFormat); - event.referenceCounter++; - saveEvent(event); - return true; + Event event = getEvent(scope, name, eventSessionId); + if (event != null) { + saveEvent(event); + return false; } + event = new Event(scope, name, eventSessionId, defaultSubject, defaultMessage, isHtmlFormat); + event.referenceCounter++; + saveEvent(event); + return true; + } - @Override - public boolean deleteEvent(String scope, String name, Long eventSessionId) throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - Event event = getEvent(scope, name, eventSessionId); - if (event == null) { - return false; - } - else { - event.deleted = true; - saveEvent(event); - return true; - } + @Override + public boolean deleteEvent(String scope, String name, Long eventSessionId) throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } - - @Override - public boolean eventExists(String scope, String name, Long eventSessionId) throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - Event event = getEvent(scope, name, eventSessionId); - if (event == null) { - return false; - } - else { - saveEvent(event); - return true; - } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); } - - @Override - public Set getAvailableDeliveryMethods() { - return EventNotificationService.availableDeliveryMethods; + Event event = getEvent(scope, name, eventSessionId); + if (event == null) { + return false; + } else { + event.deleted = true; + saveEvent(event); + return true; } + } - public EventDAO getEventDAO() { - return eventDAO; + @Override + public boolean eventExists(String scope, String name, Long eventSessionId) throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); + } + Event event = getEvent(scope, name, eventSessionId); + if (event == null) { + return false; + } else { + saveEvent(event); + return true; + } + } - @Override - public boolean isSubscribed(String scope, String name, Long eventSessionId, Long userId) throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); + @Override + public Set getAvailableDeliveryMethods() { + return EventNotificationService.availableDeliveryMethods; + } + + public EventDAO getEventDAO() { + return eventDAO; + } + + @Override + public boolean isSubscribed(String scope, String name, Long eventSessionId, Long userId) + throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); + } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); + } + if (userId == null) { + throw new InvalidParameterException("User ID should not be null."); + } + Event event = getEvent(scope, name, eventSessionId); + boolean isSubscribed = false; + if (event != null) { + for (Subscription subscription : event.getSubscriptions()) { + if (subscription.getUserId().equals(userId)) { + isSubscribed = true; + break; } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - if (userId == null) { - throw new InvalidParameterException("User ID should not be null."); - } - Event event = getEvent(scope, name, eventSessionId); - boolean isSubscribed = false; - if (event != null) { - for (Subscription subscription : event.getSubscriptions()) { - if (subscription.getUserId().equals(userId)) { - isSubscribed = true; - break; - } - } - saveEvent(event); - } - return isSubscribed; + } + saveEvent(event); } + return isSubscribed; + } - @Override - public boolean sendMessage(Long userId, AbstractDeliveryMethod deliveryMethod, String subject, String message, boolean isHtmlFormat) - throws InvalidParameterException { - Event eventFailCopy = new Event(EventNotificationService.SINGLE_MESSAGE_SCOPE, - String.valueOf(System.currentTimeMillis()), null, subject, message, isHtmlFormat); - String result = deliveryMethod.send(userId, subject, message, isHtmlFormat); - if (result != null) { - EventNotificationService.log.warn(messageService.getMessage("mail.error.occurred.while.sending.message", - new Object[] { result })); - eventFailCopy.subscribe(userId, deliveryMethod, null); - } + @Override + public boolean sendMessage(Integer fromUserId, Integer toUserId, AbstractDeliveryMethod deliveryMethod, + String subject, String message, boolean isHtmlFormat) throws InvalidParameterException { + Event eventFailCopy = new Event(IEventNotificationService.SINGLE_MESSAGE_SCOPE, String.valueOf(System + .currentTimeMillis()), null, subject, message, isHtmlFormat); + String result = deliveryMethod.send(fromUserId, toUserId, subject, message, isHtmlFormat); + if (result != null) { + EventNotificationService.log.warn("Error occured while sending message: " + result); + eventFailCopy.subscribe(toUserId, deliveryMethod, null); + } - if (!eventFailCopy.subscriptions.isEmpty()) { - eventFailCopy.setFailTime(new Date()); - eventFailCopy.referenceCounter++; - saveEvent(eventFailCopy); - return false; - } - return true; + if (!eventFailCopy.subscriptions.isEmpty()) { + eventFailCopy.setFailTime(new Date()); + eventFailCopy.referenceCounter++; + saveEvent(eventFailCopy); + return false; } + return true; + } - @Override - public boolean sendMessage(final Long[] userId, final AbstractDeliveryMethod deliveryMethod, final String subject, - final String message, final boolean isHtmlFormat) throws InvalidParameterException { - if (userId == null) { - throw new InvalidParameterException("User IDs array should not be null."); - } - if (deliveryMethod == null) { - throw new InvalidParameterException("Delivery method should not be null."); - } - if (userId.length > 0) { - if (userId.length == 1) { - return sendMessage(userId[0], deliveryMethod, subject, message, isHtmlFormat); + @Override + public boolean sendMessage(final Integer fromUserId, final Integer[] toUserIds, + final AbstractDeliveryMethod deliveryMethod, final String subject, final String message, + final boolean isHtmlFormat) throws InvalidParameterException { + if (toUserIds == null) { + throw new InvalidParameterException("User IDs array must not be null."); + } + if (deliveryMethod == null) { + throw new InvalidParameterException("Delivery method must not be null."); + } + if (toUserIds.length > 0) { + if (toUserIds.length == 1) { + return sendMessage(fromUserId, toUserIds[0], deliveryMethod, subject, message, isHtmlFormat); + } else { + final Event event = new Event(IEventNotificationService.SINGLE_MESSAGE_SCOPE, String.valueOf(System + .currentTimeMillis()), null, subject, message, isHtmlFormat); + event.referenceCounter++; + event.notificationThread = new Thread(new Runnable() { + @Override + public void run() { + for (Integer id : toUserIds) { + String result = deliveryMethod.send(fromUserId, id, subject, message, isHtmlFormat); + if (result != null) { + EventNotificationService.log.warn("Error occured while sending message: " + result); + event.subscribe(id, deliveryMethod, null); + } } - else { - final Event event = new Event(EventNotificationService.SINGLE_MESSAGE_SCOPE, String.valueOf(System - .currentTimeMillis()), null, subject, message, isHtmlFormat); - event.referenceCounter++; - event.notificationThread = new Thread(new Runnable() { - public void run() { - for (Long id : userId) { - String result = deliveryMethod.send(id, subject, message, isHtmlFormat); - if (result != null) { - EventNotificationService.log.warn(messageService.getMessage( - "mail.error.occurred.while.sending.message", - new Object[] { result })); - event.subscribe(id, deliveryMethod, null); - } - } - if (!event.subscriptions.isEmpty()) { - event.setFailTime(new Date()); - event.setTriggered(true); - saveEvent(event); - } - } - }, "LAMS_single_message_send_thread"); - event.notificationThread.start(); - + if (!event.subscriptions.isEmpty()) { + event.setFailTime(new Date()); + event.setTriggered(true); + saveEvent(event); } - } - return true; - } + } + }, "LAMS_single_message_send_thread"); + event.notificationThread.start(); - public void setEventDAO(EventDAO eventDAO) { - this.eventDAO = eventDAO; + } } + return true; + } - public void setUserManagementService(IUserManagementService userManagementService) { - this.userManagementService = userManagementService; + public void setEventDAO(EventDAO eventDAO) { + this.eventDAO = eventDAO; + } + + public void setUserManagementService(IUserManagementService userManagementService) { + this.userManagementService = userManagementService; + } + + @Override + public boolean subscribe(String scope, String name, Long eventSessionId, Integer userId, + AbstractDeliveryMethod deliveryMethod, Long periodicity) throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); + } + if (userId == null) { + throw new InvalidParameterException("User ID should not be null."); + } + if (deliveryMethod == null) { + throw new InvalidParameterException("Delivery method should not be null."); + } + Event event = getEvent(scope, name, eventSessionId); + if (event == null) { + throw new InvalidParameterException("An event with the given parameters does not exist."); + } + boolean newSubscription = true; + try { + newSubscription = event.subscribe(userId, deliveryMethod, periodicity); + } catch (Exception e) { + EventNotificationService.log.error(e); + } + saveEvent(event); + return newSubscription; - @Override - public boolean subscribe(String scope, String name, Long eventSessionId, Long userId, AbstractDeliveryMethod deliveryMethod, - Long periodicity) throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - if (userId == null) { - throw new InvalidParameterException("User ID should not be null."); - } - if (deliveryMethod == null) { - throw new InvalidParameterException("Delivery method should not be null."); - } - Event event = getEvent(scope, name, eventSessionId); - if (event == null) { - throw new InvalidParameterException("An event with the given parameters does not exist."); - } - boolean newSubscription = true; - try { - newSubscription = event.subscribe(userId, deliveryMethod, periodicity); - } - catch (Exception e) { - EventNotificationService.log.error(e.getMessage()); - } - saveEvent(event); - return newSubscription; + } + @Override + public boolean trigger(String scope, String name, Long eventSessionId) throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); + } + Event event = getEvent(scope, name, eventSessionId); + if (event == null) { + throw new InvalidParameterException("An event with the given parameters does not exist."); + } + try { + event.trigger(event.getDefaultSubject(), event.getDefaultMessage()); + } catch (Exception e) { + EventNotificationService.log.error(e.getMessage()); + } + return true; + } - @Override - public boolean trigger(String scope, String name, Long eventSessionId) throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - Event event = getEvent(scope, name, eventSessionId); - if (event == null) { - throw new InvalidParameterException("An event with the given parameters does not exist."); - } - try { - event.trigger(event.getDefaultSubject(), event.getDefaultMessage()); - } - catch (Exception e) { - EventNotificationService.log.error(e.getMessage()); - } - return true; + @Override + public boolean trigger(String scope, String name, Long eventSessionId, Object[] parameterValues) + throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); + } + Event event = getEvent(scope, name, eventSessionId); + if (event == null) { + throw new InvalidParameterException("An event with the given parameters does not exist."); + } + String body = event.getDefaultMessage(); + if ((parameterValues != null) && (parameterValues.length > 0)) { + for (int index = 0; index < parameterValues.length; index++) { + Object value = parameterValues[index]; + String replacement = value == null ? "" : value.toString(); + body = body.replace("{" + index + "}", replacement); + } + } + try { + event.trigger(event.getDefaultSubject(), body); + } catch (Exception e) { + EventNotificationService.log.error(e.getMessage()); + } + return true; + } - @Override - public boolean trigger(String scope, String name, Long eventSessionId, Object[] parameterValues) - throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - Event event = getEvent(scope, name, eventSessionId); - if (event == null) { - throw new InvalidParameterException("An event with the given parameters does not exist."); - } - String body = event.getDefaultMessage(); - if (parameterValues != null && parameterValues.length > 0) { - for (int index = 0; index < parameterValues.length; index++) { - Object value = parameterValues[index]; - String replacement = value == null ? "" : value.toString(); - body = body.replace("{" + index + "}", replacement); - } - } - try { - event.trigger(event.getDefaultSubject(), body); - } - catch (Exception e) { - EventNotificationService.log.error(e.getMessage()); - } - return true; + @Override + public boolean trigger(String scope, String name, Long eventSessionId, String title, String message) + throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); + } + Event event = getEvent(scope, name, eventSessionId); + if (event == null) { + throw new InvalidParameterException("An event with the given parameters does not exist."); + } + try { + event.trigger(title, message); + } catch (Exception e) { + EventNotificationService.log.error(e.getMessage()); + } + return true; + } - @Override - public boolean trigger(String scope, String name, Long eventSessionId, String title, String message) - throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - Event event = getEvent(scope, name, eventSessionId); - if (event == null) { - throw new InvalidParameterException("An event with the given parameters does not exist."); - } - try { - event.trigger(title, message); - } - catch (Exception e) { - EventNotificationService.log.error(e.getMessage()); - } - return true; + @Override + public boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Integer userId) + throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); + } + if (userId == null) { + throw new InvalidParameterException("User ID should not be null."); + } + Event event = getEvent(scope, name, eventSessionId); + if (event == null) { + throw new InvalidParameterException("An event with the given parameters does not exist."); + } + boolean notificationSuccessful = false; + try { + notificationSuccessful = event.triggerForSingleUser(userId, event.getDefaultSubject(), + event.getDefaultMessage()); + } catch (Exception e) { + EventNotificationService.log.error(e.getMessage()); + } + saveEvent(event); + return notificationSuccessful; + } - @Override - public boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Long userId) - throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - if (userId == null) { - throw new InvalidParameterException("User ID should not be null."); - } - Event event = getEvent(scope, name, eventSessionId); - if (event == null) { - throw new InvalidParameterException("An event with the given parameters does not exist."); - } - boolean notificationSuccessful = false; - try { - notificationSuccessful = event.triggerForSingleUser(userId, event.getDefaultSubject(), event.getDefaultMessage()); - } - catch (Exception e) { - EventNotificationService.log.error(e.getMessage()); - } - saveEvent(event); - return notificationSuccessful; + @Override + public boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Integer userId, + Object[] parameterValues) throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); + } + if (userId == null) { + throw new InvalidParameterException("User ID should not be null."); + } + Event event = getEvent(scope, name, eventSessionId); + if (event == null) { + throw new InvalidParameterException("An event with the given parameters does not exist."); + } + String body = event.getDefaultMessage(); + if ((parameterValues != null) && (parameterValues.length > 0)) { + for (int index = 0; index < parameterValues.length; index++) { + Object value = parameterValues[index]; + String replacement = value == null ? "" : value.toString(); + body = body.replace("{" + index + "}", replacement); + } + } + boolean notificationSuccessful = false; + try { + notificationSuccessful = event.triggerForSingleUser(userId, event.getDefaultSubject(), body); + } catch (Exception e) { + EventNotificationService.log.error(e.getMessage()); + } + saveEvent(event); + return notificationSuccessful; + } - @Override - public boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Long userId, Object[] parameterValues) - throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - if (userId == null) { - throw new InvalidParameterException("User ID should not be null."); - } - Event event = getEvent(scope, name, eventSessionId); - if (event == null) { - throw new InvalidParameterException("An event with the given parameters does not exist."); - } - String body = event.getDefaultMessage(); - if (parameterValues != null && parameterValues.length > 0) { - for (int index = 0; index < parameterValues.length; index++) { - Object value = parameterValues[index]; - String replacement = value == null ? "" : value.toString(); - body = body.replace("{" + index + "}", replacement); - } - } - boolean notificationSuccessful = false; - try { - notificationSuccessful = event.triggerForSingleUser(userId, event.getDefaultSubject(), body); - } - catch (Exception e) { - EventNotificationService.log.error(e.getMessage()); - } - saveEvent(event); - return notificationSuccessful; + @Override + public boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Integer userId, String subject, + String message) throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); + } + if (userId == null) { + throw new InvalidParameterException("User ID should not be null."); + } + Event event = getEvent(scope, name, eventSessionId); + if (event == null) { + throw new InvalidParameterException("An event with the given parameters does not exist."); + } + boolean notificationSuccessful = false; + try { + notificationSuccessful = event.triggerForSingleUser(userId, subject, message); + } catch (Exception e) { - @Override - public boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Long userId, String subject, - String message) throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - if (userId == null) { - throw new InvalidParameterException("User ID should not be null."); - } - Event event = getEvent(scope, name, eventSessionId); - if (event == null) { - throw new InvalidParameterException("An event with the given parameters does not exist."); - } - boolean notificationSuccessful = false; - try { - notificationSuccessful = event.triggerForSingleUser(userId, subject, message); - } - catch (Exception e) { + EventNotificationService.log.error(e.getMessage()); + } finally { + saveEvent(event); + } + return notificationSuccessful; + } - EventNotificationService.log.error(e.getMessage()); - } - finally { - saveEvent(event); - } - return notificationSuccessful; + @Override + public boolean unsubscribe(String scope, String name, Long eventSessionId, Integer userId) + throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); + } + if (userId == null) { + throw new InvalidParameterException("User ID should not be null."); + } + Event event = getEvent(scope, name, eventSessionId); + if (event == null) { + throw new InvalidParameterException("An event with the given parameters does not exist."); + } + boolean subscriptionFound = false; + try { + subscriptionFound = event.unsubscribe(userId); + } catch (Exception e) { - @Override - public boolean unsubscribe(String scope, String name, Long eventSessionId, Long userId) throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - if (userId == null) { - throw new InvalidParameterException("User ID should not be null."); - } - Event event = getEvent(scope, name, eventSessionId); - if (event == null) { - throw new InvalidParameterException("An event with the given parameters does not exist."); - } - boolean subscriptionFound = false; - try { - subscriptionFound = event.unsubscribe(userId); - } - catch (Exception e) { + EventNotificationService.log.error(e.getMessage()); + } finally { + saveEvent(event); + } + return subscriptionFound; + } - EventNotificationService.log.error(e.getMessage()); - } - finally { - saveEvent(event); - } - return subscriptionFound; + @Override + public boolean unsubscribe(String scope, String name, Long eventSessionId, Integer userId, + AbstractDeliveryMethod deliveryMethod) throws InvalidParameterException { + if (scope == null) { + throw new InvalidParameterException("Scope should not be null."); } + if (StringUtils.isEmpty(name)) { + throw new InvalidParameterException("Name should not be blank."); + } + if (userId == null) { + throw new InvalidParameterException("User ID should not be null."); + } + if (deliveryMethod == null) { + throw new InvalidParameterException("Delivery nethod should not be null."); + } + Event event = getEvent(scope, name, eventSessionId); + if (event == null) { + throw new InvalidParameterException("An event with the given parameters does not exist."); + } + boolean subscriptionFound = false; + try { + subscriptionFound = event.unsubscribe(userId, deliveryMethod); + } catch (Exception e) { - @Override - public boolean unsubscribe(String scope, String name, Long eventSessionId, Long userId, AbstractDeliveryMethod deliveryMethod) - throws InvalidParameterException { - if (scope == null) { - throw new InvalidParameterException("Scope should not be null."); - } - if (StringUtils.isEmpty(name)) { - throw new InvalidParameterException("Name should not be blank."); - } - if (userId == null) { - throw new InvalidParameterException("User ID should not be null."); - } - if (deliveryMethod == null) { - throw new InvalidParameterException("Delivery nethod should not be null."); - } - Event event = getEvent(scope, name, eventSessionId); - if (event == null) { - throw new InvalidParameterException("An event with the given parameters does not exist."); - } - boolean subscriptionFound = false; - try { - subscriptionFound = event.unsubscribe(userId, deliveryMethod); - } - catch (Exception e) { - - EventNotificationService.log.error(e.getMessage()); - } - finally { - saveEvent(event); - } - return subscriptionFound; + EventNotificationService.log.error(e.getMessage()); + } finally { + saveEvent(event); } + return subscriptionFound; + } - /** - * Gets the event, either from the database or the event pool. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @return event if it exists and it is not deleted; null if it does not exist - */ - protected Event getEvent(String scope, String name, Long eventSessionId) { - String fullSignature = Event.createFullSignature(scope, name, eventSessionId); + /** + * Gets the event, either from the database or the event pool. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @return event if it exists and it is not deleted; null if it does not exist + */ + protected Event getEvent(String scope, String name, Long eventSessionId) { + String fullSignature = Event.createFullSignature(scope, name, eventSessionId); - for (Event event : EventNotificationService.eventPool) { - if (event.equals(fullSignature)) { - if (event.deleted) { - return null; - } - event.referenceCounter++; - return event; - } + for (Event event : EventNotificationService.eventPool) { + if (event.equals(fullSignature)) { + if (event.deleted) { + return null; } - - Event result = getEventDAO().getEvent(scope, name, eventSessionId); - if (result == null) { - return null; - } - result.referenceCounter++; - EventNotificationService.eventPool.add(result); - return result; + event.referenceCounter++; + return event; + } } - protected IUserManagementService getUserManagementService() { - return userManagementService; + Event result = getEventDAO().getEvent(scope, name, eventSessionId); + if (result == null) { + return null; } + result.referenceCounter++; + EventNotificationService.eventPool.add(result); + return result; + } - /** - * Saves the event into the database - * @param event event to be saved - */ - protected void saveEvent(Event event) { - event.referenceCounter--; - if (event.referenceCounter <= 0) { - EventNotificationService.eventPool.remove(event); - if (event.deleted) { - getEventDAO().deleteEvent(event); - } - else { - getEventDAO().saveEvent(event); - } - } - } + protected IUserManagementService getUserManagementService() { + return userManagementService; + } - private Scheduler getScheduler() { - return scheduler; + /** + * Saves the event into the database + * + * @param event + * event to be saved + */ + protected void saveEvent(Event event) { + event.referenceCounter--; + if (event.referenceCounter <= 0) { + EventNotificationService.eventPool.remove(event); + if (event.deleted) { + getEventDAO().deleteEvent(event); + } else { + getEventDAO().saveEvent(event); + } } + } - public void setMessageService(MessageService messageService) { - this.messageService = messageService; - } + private Scheduler getScheduler() { + return scheduler; + } - protected MessageService getMessageService() { - return messageService; - } + public void setMessageService(MessageService messageService) { + this.messageService = messageService; + } + + protected MessageService getMessageService() { + return messageService; + } } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/events/IEventNotificationService.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_common/src/java/org/lamsfoundation/lams/events/IEventNotificationService.java (.../IEventNotificationService.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_common/src/java/org/lamsfoundation/lams/events/IEventNotificationService.java (.../IEventNotificationService.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -5,224 +5,345 @@ /** * Provides tools for managing events and notifing users. + * * @author Marcin Cieslak - * + * */ public interface IEventNotificationService { - /** - * Scope for the events that are common for the whole LAMS environment. - */ - public static final String CORE_EVENTS_SCOPE = "CORE"; + /** + * Scope for the events that are common for the whole LAMS environment. + */ + public static final String CORE_EVENTS_SCOPE = "CORE"; - /** - * User should be notified only once. Used when subscribing a user to an event. - */ - public static final long PERIODICITY_SINGLE = 0; + /** + * Scope for events that were created after {@link #sendMessage(Long, AbstractDeliveryMethod, String, String)} + * failed. + */ + public static final String SINGLE_MESSAGE_SCOPE = "SINGLE_MESSAGE"; - /** - * User should be notified daily. Used when subscribing a user to an event. - */ - public static final long PERIODICITY_DAILY = 24 * 60 * 60; + /** + * User should be notified only once. Used when subscribing a user to an event. + */ + public static final long PERIODICITY_SINGLE = 0; - /** - * User should be notified weekly. Used when subscribing a user to an event. - */ - public static final long PERIODICITY_WEEKLY = IEventNotificationService.PERIODICITY_DAILY * 7; + /** + * User should be notified daily. Used when subscribing a user to an event. + */ + public static final long PERIODICITY_DAILY = 24 * 60 * 60; - /** - * User should be notified monthly. Used when subscribing a user to an event. - */ - public static final long PERIODICITY_MONTHLY = IEventNotificationService.PERIODICITY_WEEKLY * 4; + /** + * User should be notified weekly. Used when subscribing a user to an event. + */ + public static final long PERIODICITY_WEEKLY = IEventNotificationService.PERIODICITY_DAILY * 7; - /** - * Allows sending mail to users using the configured SMTP server. - * Currently it is the only delivery method available. - */ - public static final AbstractDeliveryMethod DELIVERY_METHOD_MAIL = DeliveryMethodMail.getInstance(); + /** + * User should be notified monthly. Used when subscribing a user to an event. + */ + public static final long PERIODICITY_MONTHLY = IEventNotificationService.PERIODICITY_WEEKLY * 4; - /** - * Creates an event and saves it into the database. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @param defaultSubject subject of the message send to users; it can be altered when triggering the event - * @param defaultMessage body of the message send to users; it can be altered when triggering the event - * @param isHtmlFormat whether the message is of HTML content-type or plain text - * @return true if the event did not exist and was correctly created - * @throws InvalidParameterException if scope was null or name was blank - */ - public abstract boolean createEvent(String scope, String name, Long eventSessionId, String defaultSubject, - String defaultMessage, boolean isHtmlFormat) throws InvalidParameterException; + /** + * Allows sending mail to users using the configured SMTP server. Currently it is the only delivery method + * available. + */ + public static final AbstractDeliveryMethod DELIVERY_METHOD_MAIL = DeliveryMethodMail.getInstance(); - /** - * Deletes an event. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @return true if the event existed and was deleted - * @throws InvalidParameterException if scope was null or name was blank - */ - public abstract boolean deleteEvent(String scope, String name, Long eventSessionId) throws InvalidParameterException;; + /** + * Creates an event and saves it into the database. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @param defaultSubject + * subject of the message send to users; it can be altered when triggering the event + * @param defaultMessage + * body of the message send to users; it can be altered when triggering the event + * @param isHtmlFormat + * whether the message is of HTML content-type or plain text + * @return true if the event did not exist and was correctly created + * @throws InvalidParameterException + * if scope was null or name was blank + */ + public abstract boolean createEvent(String scope, String name, Long eventSessionId, String defaultSubject, + String defaultMessage, boolean isHtmlFormat) throws InvalidParameterException; - /** - * Checks if event with the given parameters exists in the database. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @return true if the event exists - * @throws InvalidParameterException if scope was null or name was blank - */ - public abstract boolean eventExists(String scope, String name, Long eventSessionId) throws InvalidParameterException; + /** + * Deletes an event. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @return true if the event existed and was deleted + * @throws InvalidParameterException + * if scope was null or name was blank + */ + public abstract boolean deleteEvent(String scope, String name, Long eventSessionId) + throws InvalidParameterException;; - /** - * Gets the available delivery methods that can be used when subscribing an user to an event. - * @return set of available delivery methods in the system - */ - public abstract Set getAvailableDeliveryMethods(); + /** + * Checks if event with the given parameters exists in the database. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @return true if the event exists + * @throws InvalidParameterException + * if scope was null or name was blank + */ + public abstract boolean eventExists(String scope, String name, Long eventSessionId) + throws InvalidParameterException; - /** - * Checks if an user is subscribed to the given event. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @param userId ID of the user - * @return true if the event exists and the user is subscribed (with at least one delivery method) to the event - * @throws InvalidParameterException if scope or user ID were null, name was blank or event does not exist - */ - public abstract boolean isSubscribed(String scope, String name, Long eventSessionId, Long userId) - throws InvalidParameterException; + /** + * Gets the available delivery methods that can be used when subscribing an user to an event. + * + * @return set of available delivery methods in the system + */ + public abstract Set getAvailableDeliveryMethods(); - /** - * Sends a single message to the given users.If it fails, an event is created for the needs of the resending mechanism. - * @param userId ID of users to send the message to - * @param deliveryMethod method of messaged delivery to use - * @param subject subject of the message to send - * @param message body of the message to send - * @param isHtmlFormat whether the message is of HTML content-type or plain text - * @return true if the message was succefully send to the user - * @throws InvalidParameterException if userId or delivery method are null - */ - public abstract boolean sendMessage(Long userId, AbstractDeliveryMethod deliveryMethod, String subject, String message, boolean isHtmlFormat) - throws InvalidParameterException; + /** + * Checks if an user is subscribed to the given event. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @param userId + * ID of the user + * @return true if the event exists and the user is subscribed (with at least one delivery method) to + * the event + * @throws InvalidParameterException + * if scope or user ID were null, name was blank or event does not exist + */ + public abstract boolean isSubscribed(String scope, String name, Long eventSessionId, Long userId) + throws InvalidParameterException; - /** - * - * Sends a single message to the given user. If it fails, an event is created for the needs of the resending mechanism. - * @param userId IDs of users to send the message to - * @param deliveryMethod method of messaged delivery to use - * @param subject subject of the message to send - * @param message body of the message to send - * @param isHtmlFormat whether the message is of HTML content-type or plain text - * @return true if the message was succefully send to all the users; as in the current implementation a separate thread is used for sending messages, this method always returns true - * @throws InvalidParameterException if userId array or delivery method are null - */ - public abstract boolean sendMessage(Long[] userId, AbstractDeliveryMethod deliveryMethod, String subject, String message, boolean isHtmlFormat) - throws InvalidParameterException; + /** + * Sends a single message to the given users.If it fails, an event is created for the needs of the resending + * mechanism. + * + * @param toUserId + * ID of users to send the message to + * @param deliveryMethod + * method of messaged delivery to use + * @param subject + * subject of the message to send + * @param message + * body of the message to send + * @param isHtmlFormat + * whether the message is of HTML content-type or plain text + * @return true if the message was succefully send to the user + * @throws InvalidParameterException + * if userId or delivery method are null + */ + public abstract boolean sendMessage(Integer fromUserId, Integer toUserId, AbstractDeliveryMethod deliveryMethod, + String subject, String message, boolean isHtmlFormat) throws InvalidParameterException; - /** - * Registeres an user for notification of the event. - * If a subscription with given user ID and delivery method already exists, - * only periodicity is updated. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @param userId ID of the user - * @param deliveryMethod method of messaged delivery to use - * @param periodicity how often the user should be notified (in seconds) - * @throws InvalidParameterException if scope, userId or delivery method are null, or name is blank - */ - public abstract boolean subscribe(String scope, String name, Long eventSessionId, Long userId, - AbstractDeliveryMethod deliveryMethod, Long periodicity) throws InvalidParameterException; + /** + * + * Sends a single message to the given user. If it fails, an event is created for the needs of the resending + * mechanism. + * + * @param toUserIds + * IDs of users to send the message to + * @param deliveryMethod + * method of messaged delivery to use + * @param subject + * subject of the message to send + * @param message + * body of the message to send + * @param isHtmlFormat + * whether the message is of HTML content-type or plain text + * @return true if the message was succefully send to all the users; as in the current implementation a + * separate thread is used for sending messages, this method always returns true + * @throws InvalidParameterException + * if userId array or delivery method are null + */ + public abstract boolean sendMessage(Integer fromUserId, Integer[] toUserIds, AbstractDeliveryMethod deliveryMethod, + String subject, String message, boolean isHtmlFormat) throws InvalidParameterException; - /** - * Triggers the event with the default (or previously set) subject and message. Each subscribed user is notified. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @throws InvalidParameterException if scope is null or name is blank - */ - public abstract boolean trigger(String scope, String name, Long eventSessionId) throws InvalidParameterException; + /** + * Registeres an user for notification of the event. If a subscription with given user ID and delivery method + * already exists, only periodicity is updated. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @param userId + * ID of the user + * @param deliveryMethod + * method of messaged delivery to use + * @param periodicity + * how often the user should be notified (in seconds) + * @throws InvalidParameterException + * if scope, userId or delivery method are null, or name is blank + */ + public abstract boolean subscribe(String scope, String name, Long eventSessionId, Integer userId, + AbstractDeliveryMethod deliveryMethod, Long periodicity) throws InvalidParameterException; - /** - * Triggers the event with the default subject and message, modifying placeholders ({0}, {1}, {2}...) in the message body with the parameterValues. Each subscribed user is notified. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @param parameterValues values that should replace placeholders in the message body; for each object its text representation is acquired by toString() method; then, the first string replaces {0} tag, second one the {1} tag and so on. - * @throws InvalidParameterException if scope is null or name is blank - */ - public abstract boolean trigger(String scope, String name, Long eventSessionId, Object[] parameterValues) - throws InvalidParameterException; + /** + * Triggers the event with the default (or previously set) subject and message. Each subscribed user is notified. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @throws InvalidParameterException + * if scope is null or name is blank + */ + public abstract boolean trigger(String scope, String name, Long eventSessionId) throws InvalidParameterException; - /** - * Triggers the event with given subject and message. Each subscribed user is notified. Default message and subject are overridden. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @param subject subject of the message to send - * @param message body of the message to send - * @throws InvalidParameterException if scope is null or name is blank - */ - public abstract boolean trigger(String scope, String name, Long eventSessionId, String subject, String message) - throws InvalidParameterException; + /** + * Triggers the event with the default subject and message, modifying placeholders ({0}, {1}, {2}...) + * in the message body with the parameterValues. Each subscribed user is notified. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @param parameterValues + * values that should replace placeholders in the message body; for each object its text representation + * is acquired by toString() method; then, the first string replaces {0} tag, + * second one the {1} tag and so on. + * @throws InvalidParameterException + * if scope is null or name is blank + */ + public abstract boolean trigger(String scope, String name, Long eventSessionId, Object[] parameterValues) + throws InvalidParameterException; - /** - * Notifies only a single user of the event using the default subject and message. Does not set the event as "triggered". - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @param userId ID of the user - * @throws InvalidParameterException if scope or userId are null or name is blank - */ - public abstract boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Long userId) - throws InvalidParameterException; + /** + * Triggers the event with given subject and message. Each subscribed user is notified. Default message and subject + * are overridden. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @param subject + * subject of the message to send + * @param message + * body of the message to send + * @throws InvalidParameterException + * if scope is null or name is blank + */ + public abstract boolean trigger(String scope, String name, Long eventSessionId, String subject, String message) + throws InvalidParameterException; - /** - * Notifies only a single user of the event using the default subject and message, modifying placeholders ({0}, {1}, {2}...) in the message body with the parameterValues. Does not set the event as "triggered". - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @param userId ID of the user - * @param parameterValues values that should replace placeholders in the message body; for each object its text representation is acquired by toString() method; then, the first string replaces {0} tag, second one the {1} tag and so on. - * @throws InvalidParameterException if scope or userId are null or name is blank - */ - public boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Long userId, Object[] parameterValues) - throws InvalidParameterException; + /** + * Notifies only a single user of the event using the default subject and message. Does not set the event as + * "triggered". + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @param userId + * ID of the user + * @throws InvalidParameterException + * if scope or userId are null or name is blank + */ + public abstract boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Integer userId) + throws InvalidParameterException; - /** - * Notifies only a single user of the event using the given subject and message. Does not set the event as "triggered". Default subject and message are NOT overridden. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @param userId ID of the user - * @param subject subject of the message to send - * @param message body of the message to send - * @throws InvalidParameterException if scope or userId are null or name is blank - */ - public abstract boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Long userId, String subject, - String message) throws InvalidParameterException; + /** + * Notifies only a single user of the event using the default subject and message, modifying placeholders ( + * {0}, {1}, {2}...) in the message body with the parameterValues. Does not set the event + * as "triggered". + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @param userId + * ID of the user + * @param parameterValues + * values that should replace placeholders in the message body; for each object its text representation + * is acquired by toString() method; then, the first string replaces {0} tag, + * second one the {1} tag and so on. + * @throws InvalidParameterException + * if scope or userId are null or name is blank + */ + public boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Integer userId, + Object[] parameterValues) throws InvalidParameterException; - /** - * Unregister an user from notification of the event. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @param userId ID of the user - * @throws InvalidParameterException if scope or userId are null or name is blank - */ - public abstract boolean unsubscribe(String scope, String name, Long eventSessionId, Long userId) - throws InvalidParameterException; + /** + * Notifies only a single user of the event using the given subject and message. Does not set the event as + * "triggered". Default subject and message are NOT overridden. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @param userId + * ID of the user + * @param subject + * subject of the message to send + * @param message + * body of the message to send + * @throws InvalidParameterException + * if scope or userId are null or name is blank + */ + public abstract boolean triggerForSingleUser(String scope, String name, Long eventSessionId, Integer userId, + String subject, String message) throws InvalidParameterException; - /** - * Unregister delivery method of the user from notification of the event. - * @param scope scope of the event - * @param name name of the event - * @param eventSessionId session ID of the event - * @param userId ID of the user - * @param deliveryMethod delivery method which should be unregistered - * @throws InvalidParameterException if scope, userId or delivery method are null or name is blank - */ - public abstract boolean unsubscribe(String scope, String name, Long eventSessionId, Long userId, - AbstractDeliveryMethod deliveryMethod) throws InvalidParameterException; + /** + * Unregister an user from notification of the event. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @param userId + * ID of the user + * @throws InvalidParameterException + * if scope or userId are null or name is blank + */ + public abstract boolean unsubscribe(String scope, String name, Long eventSessionId, Integer userId) + throws InvalidParameterException; + + /** + * Unregister delivery method of the user from notification of the event. + * + * @param scope + * scope of the event + * @param name + * name of the event + * @param eventSessionId + * session ID of the event + * @param userId + * ID of the user + * @param deliveryMethod + * delivery method which should be unregistered + * @throws InvalidParameterException + * if scope, userId or delivery method are null or name is blank + */ + public abstract boolean unsubscribe(String scope, String name, Long eventSessionId, Integer userId, + AbstractDeliveryMethod deliveryMethod) throws InvalidParameterException; } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/events/ResendMessagesJob.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_common/src/java/org/lamsfoundation/lams/events/ResendMessagesJob.java (.../ResendMessagesJob.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_common/src/java/org/lamsfoundation/lams/events/ResendMessagesJob.java (.../ResendMessagesJob.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -9,66 +9,67 @@ import org.springframework.scheduling.quartz.QuartzJobBean; /** - * Quartz job for resending messages. - * This job is scheduled from the start-up and periodically attempts to resend failed and marked for resending messages. + * Quartz job for resending messages. This job is scheduled from the start-up and periodically attempts to resend failed + * and marked for resending messages. + * * @author Administrator - * + * */ public class ResendMessagesJob extends QuartzJobBean { - /** - * Period after which the thread gives up on attempting to resend messages. Currently - 2 days. - */ - private static final long RESEND_TIME_LIMIT = 2 * 24 * 60 * 60 * 1000; + /** + * Period after which the thread gives up on attempting to resend messages. Currently - 2 days. + */ + private static final long RESEND_TIME_LIMIT = 2 * 24 * 60 * 60 * 1000; - private static final EventNotificationService notificationService = EventNotificationService.getInstance(); + private static final EventNotificationService notificationService = EventNotificationService.getInstance(); - private static final MessageService messageService = ResendMessagesJob.notificationService.getMessageService(); + private static final MessageService messageService = ResendMessagesJob.notificationService.getMessageService(); - @Override - protected void executeInternal(JobExecutionContext context) throws JobExecutionException { - try { - EventNotificationService.log.debug("Event notification service is running a resend messages thread..."); - List events = ResendMessagesJob.notificationService.getEventDAO().getEventsToResend(); - for (Event event : events) { - event.referenceCounter++; - if (event.getFailTime() != null) { - event.trigger(event.getSubject(), event.getMessage()); - event.notificationThread.join(); - if (event.getSubscriptions().isEmpty()) { - event.deleted = true; - } - else if (System.currentTimeMillis() - event.getFailTime().getTime() >= ResendMessagesJob.RESEND_TIME_LIMIT) { - event.deleted = true; - StringBuilder body = new StringBuilder(ResendMessagesJob.messageService - .getMessage("mail.resend.abandon.body1")).append(event.getDefaultMessage()).append( - ResendMessagesJob.messageService.getMessage("mail.resend.abandon.body2")); - for (Subscription subscription : event.getSubscriptions()) { - User user = (User) EventNotificationService.getInstance().getUserManagementService().findById( - User.class, subscription.getUserId().intValue()); - body.append(user.getLogin()).append('\n'); - } - ((DeliveryMethodMail) IEventNotificationService.DELIVERY_METHOD_MAIL).notifyAdmin( - ResendMessagesJob.messageService.getMessage("mail.resend.abandon.subject"), - body.toString(), event.isHtmlFormat()); - } - } - else { - for (Subscription subscription : event.getSubscriptions()) { - if (subscription.getLastOperationTime() != null - && System.currentTimeMillis() - subscription.getLastOperationTime().getTime() > subscription - .getPeriodicity()) { - String subject = event.getSubject() == null ? event.getDefaultSubject() : event.getSubject(); - String message = event.getMessage() == null ? event.getDefaultMessage() : event.getMessage(); - boolean isHtmlFormat = event.isHtmlFormat(); - subscription.notifyUser(subject, message, isHtmlFormat); - } - } - } - ResendMessagesJob.notificationService.saveEvent(event); + @Override + protected void executeInternal(JobExecutionContext context) throws JobExecutionException { + try { + EventNotificationService.log.debug("Event notification service is running a resend messages thread..."); + List events = ResendMessagesJob.notificationService.getEventDAO().getEventsToResend(); + for (Event event : events) { + event.referenceCounter++; + if (event.getFailTime() != null) { + event.trigger(event.getSubject(), event.getMessage()); + event.notificationThread.join(); + if (event.getSubscriptions().isEmpty()) { + event.deleted = true; + } else if (System.currentTimeMillis() - event.getFailTime().getTime() >= ResendMessagesJob.RESEND_TIME_LIMIT) { + event.deleted = true; + StringBuilder body = new StringBuilder( + ResendMessagesJob.messageService.getMessage("mail.resend.abandon.body1")).append( + event.getDefaultMessage()).append( + ResendMessagesJob.messageService.getMessage("mail.resend.abandon.body2")); + for (Subscription subscription : event.getSubscriptions()) { + User user = (User) EventNotificationService.getInstance().getUserManagementService() + .findById(User.class, subscription.getUserId()); + body.append(user.getLogin()).append('\n'); } + ((DeliveryMethodMail) IEventNotificationService.DELIVERY_METHOD_MAIL).notifyAdmin( + ResendMessagesJob.messageService.getMessage("mail.resend.abandon.subject"), + body.toString(), event.isHtmlFormat()); + } + } else { + for (Subscription subscription : event.getSubscriptions()) { + if ((subscription.getLastOperationTime() != null) + && (System.currentTimeMillis() - subscription.getLastOperationTime().getTime() > subscription + .getPeriodicity())) { + String subject = event.getSubject() == null ? event.getDefaultSubject() : event + .getSubject(); + String message = event.getMessage() == null ? event.getDefaultMessage() : event + .getMessage(); + boolean isHtmlFormat = event.isHtmlFormat(); + subscription.notifyUser(subject, message, isHtmlFormat); + } + } } - catch (Exception e) { - throw new JobExecutionException(e.getMessage()); - } + ResendMessagesJob.notificationService.saveEvent(event); + } + } catch (Exception e) { + throw new JobExecutionException(e.getMessage()); } + } } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/events/Subscription.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_common/src/java/org/lamsfoundation/lams/events/Subscription.java (.../Subscription.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_common/src/java/org/lamsfoundation/lams/events/Subscription.java (.../Subscription.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -6,216 +6,220 @@ import org.apache.commons.lang.builder.HashCodeBuilder; /** - * Subscription for an event notification. - * This class binds an user to an event and stores some information on the notification attempts. + * Subscription for an event notification. This class binds an user to an event and stores some information on the + * notification attempts. * * @hibernate.class table="lams_event_subscriptions" * @author Marcin Cieslak - * + * */ class Subscription { - //------ persistent fields ------- - /** - * Unique ID for Hibernate needs. - */ - private Long uid; + // ------ persistent fields ------- + /** + * Unique ID for Hibernate needs. + */ + private Long uid; - /** - * ID of the subscribed user - */ - protected Long userId; - - protected Event event; + /** + * ID of the subscribed user + */ + protected Integer userId; - /** - * ID of the delivery method used to send a message for this subscription. - */ - protected Short deliveryMethodId; + protected Event event; - /** - * How often should the message be resend - */ - protected Long periodicity; + /** + * ID of the delivery method used to send a message for this subscription. + */ + protected Short deliveryMethodId; - /** - * Time of the notification attempt - */ - protected Date lastOperationTime; + /** + * How often should the message be resend + */ + protected Long periodicity; - /** - * Message returned by a delivery methond during the last notification attempt - */ - protected String lastOperationMessage; + /** + * Time of the notification attempt + */ + protected Date lastOperationTime; - // --------- non-persitent fields ---------- - /** - * Delivery method used to send a message. - */ - protected AbstractDeliveryMethod deliveryMethod; + /** + * Message returned by a delivery methond during the last notification attempt + */ + protected String lastOperationMessage; - /** - * For Hibernate usage. - */ - public Subscription() { + // --------- non-persitent fields ---------- + /** + * Delivery method used to send a message. + */ + protected AbstractDeliveryMethod deliveryMethod; - } + /** + * For Hibernate usage. + */ + public Subscription() { - /** - * Standard consctructor used by Events. - * @param userId - * @param deliveryMethod - * @param periodicity - */ - protected Subscription(Long userId, AbstractDeliveryMethod deliveryMethod, Long periodicity) { - if (deliveryMethod == null) { - throw new InvalidParameterException("Delivery method can not be null."); - } - this.userId = userId; - this.deliveryMethod = deliveryMethod; - setPeriodicity(periodicity); - deliveryMethodId = deliveryMethod.getId(); + } + + /** + * Standard consctructor used by Events. + * + * @param userId + * @param deliveryMethod + * @param periodicity + */ + protected Subscription(Integer userId, AbstractDeliveryMethod deliveryMethod, Long periodicity) { + if (deliveryMethod == null) { + throw new InvalidParameterException("Delivery method can not be null."); } + this.userId = userId; + this.deliveryMethod = deliveryMethod; + setPeriodicity(periodicity); + deliveryMethodId = deliveryMethod.getId(); + } - /** - * Only user ID and delivery method count. - */ - @Override - public boolean equals(Object o) { - if (!(o instanceof Subscription)) { - return false; - } - Subscription other = (Subscription) o; - return other.getUserId().equals(getUserId()) && other.getDeliveryMethod().equals(getDeliveryMethod()); + /** + * Only user ID and delivery method count. + */ + @Override + public boolean equals(Object o) { + if (!(o instanceof Subscription)) { + return false; } + Subscription other = (Subscription) o; + return other.getUserId().equals(getUserId()) && other.getDeliveryMethod().equals(getDeliveryMethod()); + } - protected AbstractDeliveryMethod getDeliveryMethod() { - if (deliveryMethod == null) { - for (AbstractDeliveryMethod delivery : EventNotificationService.getInstance().getAvailableDeliveryMethods()) { - if (delivery.getId() == deliveryMethodId) { - deliveryMethod = delivery; - } - } + protected AbstractDeliveryMethod getDeliveryMethod() { + if (deliveryMethod == null) { + for (AbstractDeliveryMethod delivery : EventNotificationService.getInstance().getAvailableDeliveryMethods()) { + if (delivery.getId() == deliveryMethodId) { + deliveryMethod = delivery; } - return deliveryMethod; + } } + return deliveryMethod; + } - /** - * @hibernate.property column="last_operation_message" - * @return - */ - protected String getLastOperationMessage() { - return lastOperationMessage; - } + /** + * @hibernate.property column="last_operation_message" + * @return + */ + protected String getLastOperationMessage() { + return lastOperationMessage; + } - protected boolean getLastOperationSuccessful() { - return lastOperationMessage == null; - } + protected boolean getLastOperationSuccessful() { + return lastOperationMessage == null; + } - /** - * @hibernate.property column="periodicity" - * @return - */ - protected Long getPeriodicity() { - return periodicity; - } + /** + * @hibernate.property column="periodicity" + * @return + */ + protected Long getPeriodicity() { + return periodicity; + } - /** - * @hibernate.property column="user_id" - * @return - */ - protected Long getUserId() { - return userId; - } + /** + * @hibernate.property column="user_id" + * @return + */ + protected Integer getUserId() { + return userId; + } - /** - * @hibernate.many-to-one - * @hibernate.column name="event_uid" - * @return - */ - public Event getEvent() { - return event; - } + /** + * @hibernate.many-to-one + * @hibernate.column name="event_uid" + * @return + */ + public Event getEvent() { + return event; + } - public void setEvent(Event event) { - this.event = event; - } + public void setEvent(Event event) { + this.event = event; + } - @Override - public int hashCode() { - return new HashCodeBuilder().append(getUserId()).append(getDeliveryMethod()).toHashCode(); - } + @Override + public int hashCode() { + return new HashCodeBuilder().append(getUserId()).append(getDeliveryMethod()).toHashCode(); + } - /** - * States if a message should be send to the user or rather this subscription should be skipped. - * @return if the message should be send - */ - protected boolean isEligibleForNotification() { - return !getLastOperationSuccessful() || lastOperationTime == null - || System.currentTimeMillis() - lastOperationTime.getTime() > periodicity; - } + /** + * States if a message should be send to the user or rather this subscription should be skipped. + * + * @return if the message should be send + */ + protected boolean isEligibleForNotification() { + return !getLastOperationSuccessful() || lastOperationTime == null + || System.currentTimeMillis() - lastOperationTime.getTime() > periodicity; + } - /** - * Sends the message to the user. - * Properties storing information of the last notification attempt are updated. - * @param subject subject of the message; null if not applicable - * @param message message to send - * @param isHtmlFormat + /** + * Sends the message to the user. Properties storing information of the last notification attempt are updated. + * + * @param subject + * subject of the message; null if not applicable + * @param message + * message to send + * @param isHtmlFormat * whether the message is of HTML content-type or plain text - */ - protected void notifyUser(String subject, String message, boolean isHtmlFormat) { - lastOperationTime = new Date(); - lastOperationMessage = deliveryMethod.send(userId, subject, message, isHtmlFormat); - } + */ + protected void notifyUser(String subject, String message, boolean isHtmlFormat) { + lastOperationTime = new Date(); + lastOperationMessage = deliveryMethod.send(null, userId, subject, message, isHtmlFormat); + } - protected void setPeriodicity(Long periodicity) { - this.periodicity = periodicity == null ? IEventNotificationService.PERIODICITY_SINGLE : periodicity; - } + protected void setPeriodicity(Long periodicity) { + this.periodicity = periodicity == null ? IEventNotificationService.PERIODICITY_SINGLE : periodicity; + } - /** - * @hibernate.property column="delivery_method_id" - * @return - */ - protected Short getDeliveryMethodId() { - return deliveryMethodId; - } + /** + * @hibernate.property column="delivery_method_id" + * @return + */ + protected Short getDeliveryMethodId() { + return deliveryMethodId; + } - /** - * @hibernate.property column="last_operation_time" - * @return - */ - protected Date getLastOperationTime() { - return lastOperationTime; - } + /** + * @hibernate.property column="last_operation_time" + * @return + */ + protected Date getLastOperationTime() { + return lastOperationTime; + } - protected void setDeliveryMethodId(Short deliveryMethodId) { - this.deliveryMethodId = deliveryMethodId; - } + protected void setDeliveryMethodId(Short deliveryMethodId) { + this.deliveryMethodId = deliveryMethodId; + } - protected void setLastOperationTime(Date lastOperationTime) { - this.lastOperationTime = lastOperationTime; - } + protected void setLastOperationTime(Date lastOperationTime) { + this.lastOperationTime = lastOperationTime; + } - protected void setUserId(Long userId) { - this.userId = userId; - } + protected void setUserId(Integer userId) { + this.userId = userId; + } - /** - * @hibernate.id column="uid" generator-class="native" - */ - private Long getUid() { - return uid; - } + /** + * @hibernate.id column="uid" generator-class="native" + */ + private Long getUid() { + return uid; + } - private void setUid(Long uid) { - this.uid = uid; - } + private void setUid(Long uid) { + this.uid = uid; + } - @Override - public Object clone() { - return new Subscription(userId, deliveryMethod, periodicity); - } + @Override + public Object clone() { + return new Subscription(userId, deliveryMethod, periodicity); + } - protected void setLastOperationMessage(String lastOperationMessage) { - this.lastOperationMessage = lastOperationMessage; - } + protected void setLastOperationMessage(String lastOperationMessage) { + this.lastOperationMessage = lastOperationMessage; + } } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/util/Emailer.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_common/src/java/org/lamsfoundation/lams/util/Emailer.java (.../Emailer.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_common/src/java/org/lamsfoundation/lams/util/Emailer.java (.../Emailer.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -3,17 +3,14 @@ import java.io.UnsupportedEncodingException; import java.util.Properties; -import javax.mail.Authenticator; +import javax.mail.Message.RecipientType; import javax.mail.MessagingException; -import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; -import javax.mail.Message.RecipientType; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; -import org.apache.log4j.Logger; import org.masukomi.aspirin.core.MailQue; /** @@ -22,10 +19,6 @@ * @author lfoxton */ public class Emailer { - - public Emailer() { - } - /** * Sends an email sourced from support email * @@ -42,7 +35,7 @@ throws AddressException, MessagingException, UnsupportedEncodingException { String supportEmail = Configuration.get(ConfigurationKeys.LAMS_ADMIN_EMAIL); Properties properties = new Properties(); - send(subject, to, supportEmail, body, isHtmlFormat, properties); + Emailer.send(subject, to, supportEmail, body, isHtmlFormat, properties); } /** @@ -91,7 +84,7 @@ public static void send(String subject, String to, String from, String body, boolean isHtmlFormat, Properties mailServerConfig) throws AddressException, MessagingException, UnsupportedEncodingException { - send(subject, to, "", from, "", body, isHtmlFormat, mailServerConfig); + Emailer.send(subject, to, "", from, "", body, isHtmlFormat, mailServerConfig); } @@ -117,7 +110,7 @@ boolean isHtmlFormat, Properties mailServerConfig) throws AddressException, MessagingException, UnsupportedEncodingException { - Session session = getMailSession(mailServerConfig); + Session session = Emailer.getMailSession(mailServerConfig); boolean useInternalSMTPServer = Boolean.parseBoolean(Configuration .get(ConfigurationKeys.USE_INTERNAL_SMTP_SERVER)); @@ -126,7 +119,7 @@ message.addRecipient(RecipientType.TO, new InternetAddress(to, toPerson)); message.setSubject(subject, "UTF-8"); message.setText(body, "UTF-8"); - String contentType = (isHtmlFormat) ? "text/html; charset=UTF-8" : "text/plain; charset=UTF-8"; + String contentType = (isHtmlFormat) ? "text/html;charset=UTF-8" : "text/plain;charset=UTF-8"; message.addHeader("Content-Type", contentType); if (useInternalSMTPServer) { @@ -136,7 +129,5 @@ } else { Transport.send(message); } - } - -} +} \ No newline at end of file Index: lams_monitoring/conf/language/lams/ApplicationResources.properties =================================================================== diff -u -r1b117caf4135f53248542cbc97d71aac448f3de9 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_monitoring/conf/language/lams/ApplicationResources.properties (.../ApplicationResources.properties) (revision 1b117caf4135f53248542cbc97d71aac448f3de9) +++ lams_monitoring/conf/language/lams/ApplicationResources.properties (.../ApplicationResources.properties) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -219,6 +219,7 @@ learner.group.sort.button =Sort button.force.complete =Force complete button.view.learner =View learner +button.email =Email button.close =Close button.help =Help button.help.tooltip =Open page with help on this tab @@ -233,8 +234,8 @@ lesson.learners =Learners: lesson.class =Class: lesson.manage =Manage Lesson -button.view.learners =View Learners -button.view.learners.tooltip =Shows all the learners assigned to this lesson +button.view.learners =View/Email Learners +button.view.learners.tooltip =Shows all learners assigned to this lesson and allows to email them button.edit.class =Edit Class button.edit.class.tooltip =Edit the list of learners and monitors assigned to this lesson button.open.im =Open IM Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/quartz/job/EmailScheduleMessageJob.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/quartz/job/EmailScheduleMessageJob.java (.../EmailScheduleMessageJob.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/quartz/job/EmailScheduleMessageJob.java (.../EmailScheduleMessageJob.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -18,16 +18,15 @@ * * http://www.gnu.org/licenses/gpl.txt * **************************************************************** - */ - -/* $Id$ */ + */ + +/* $Id$ */ package org.lamsfoundation.lams.monitoring.quartz.job; import java.util.Collection; import java.util.Map; import org.apache.log4j.Logger; -import org.lamsfoundation.lams.events.DeliveryMethodMail; import org.lamsfoundation.lams.events.IEventNotificationService; import org.lamsfoundation.lams.monitoring.service.IMonitoringService; import org.lamsfoundation.lams.usermanagement.User; @@ -57,7 +56,7 @@ Map properties = context.getJobDetail().getJobDataMap(); String emailBody = (String) properties.get("emailBody"); - //get users to whom send emails + // get users to whom send emails int searchType = (Integer) properties.get("searchType"); Long lessonId = (Long) properties.get(AttributeNames.PARAM_LESSON_ID); Integer orgId = (Integer) properties.get(AttributeNames.PARAM_ORGANISATION_ID); @@ -69,19 +68,22 @@ for (User user : users) { boolean isHtmlFormat = false; - long userId = user.getUserId(); + int userId = user.getUserId(); log.debug("Sending scheduled email to user [" + userId + "]."); - eventNotificationService.sendMessage(userId, DeliveryMethodMail.getInstance(), monitoringService - .getMessageService().getMessage("event.emailnotifications.email.subject", new Object[] {}), - emailBody, isHtmlFormat); + eventNotificationService.sendMessage( + null, + userId, + IEventNotificationService.DELIVERY_METHOD_MAIL, + monitoringService.getMessageService().getMessage("event.emailnotifications.email.subject", + new Object[] {}), emailBody, isHtmlFormat); } } private IEventNotificationService getEventNotificationService(JobExecutionContext context) throws JobExecutionException { try { final String CONTEXT_NAME = "context.central"; - + SchedulerContext sc = context.getScheduler().getContext(); ApplicationContext cxt = (ApplicationContext) sc.get(CONTEXT_NAME); return (IEventNotificationService) cxt.getBean("eventNotificationService"); Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/EmailNotificationsAction.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/EmailNotificationsAction.java (.../EmailNotificationsAction.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/EmailNotificationsAction.java (.../EmailNotificationsAction.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -231,11 +231,11 @@ boolean isSuccessfullySent = true; String[] userIdStrs = request.getParameterValues("userId"); for (String userIdStr : userIdStrs) { - long userId = Long.parseLong(userIdStr); + int userId = Integer.parseInt(userIdStr); boolean isHtmlFormat = false; - isSuccessfullySent &= eventNotificationService.sendMessage( + isSuccessfullySent &= eventNotificationService.sendMessage(null, userId, - DeliveryMethodMail.getInstance(), + IEventNotificationService.DELIVERY_METHOD_MAIL, monitoringService.getMessageService().getMessage("event.emailnotifications.email.subject", new Object[] {}), emailBody, isHtmlFormat); } Index: lams_monitoring/web/css/monitorLesson.css =================================================================== diff -u -r1b117caf4135f53248542cbc97d71aac448f3de9 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_monitoring/web/css/monitorLesson.css (.../monitorLesson.css) (revision 1b117caf4135f53248542cbc97d71aac448f3de9) +++ lams_monitoring/web/css/monitorLesson.css (.../monitorLesson.css) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -39,10 +39,16 @@ border: none; } -div.dialogContainer { +.dialogContainer { display: none; } +.dialogContainer iframe { + width: 100%; + height: 100%; + border: none; +} + .dialogList { overflow: auto; border: thin solid black; @@ -151,6 +157,10 @@ border: none; } +#emailDialog { + width: 100%; +} + /********** SEQUENCE TAB STYLES **********/ div#sequenceCanvas { text-align: center; Index: lams_monitoring/web/includes/javascript/monitorLesson.js =================================================================== diff -u -r02163efabf3b7e31a55e3b7b348ed55dafa6afe6 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_monitoring/web/includes/javascript/monitorLesson.js (.../monitorLesson.js) (revision 02163efabf3b7e31a55e3b7b348ed55dafa6afe6) +++ lams_monitoring/web/includes/javascript/monitorLesson.js (.../monitorLesson.js) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -163,7 +163,23 @@ }); $('#classMonitorSortButton').click(function(){ sortDialogList('classMonitor'); - }); + }); + + // sets up dialog for emailing learners + $('#emailDialog').dialog({ + 'autoOpen' : false, + 'height' : 530, + 'width' : 700, + 'modal' : true, + 'resizable' : false, + 'show' : 'fold', + 'hide' : 'fold', + 'open' : function(){ + $('#emailFrame').attr('src', LAMS_URL + 'emailUser.do?method=composeMail&lessonID=' + + lessonId + + '&userID=' + $(this).dialog('option', 'userId')); + } + }); } @@ -182,7 +198,7 @@ 'classOnly' : true }, success : function(response) { - showLearnerGroupDialog(null, LESSON_GROUP_DIALOG_CLASS_LABEL, response); + showLearnerGroupDialog(null, LESSON_GROUP_DIALOG_CLASS_LABEL, response, false, false, true); } }); } @@ -391,6 +407,10 @@ } +function closeEmailDialog(){ + $('#emailFrame').attr('src', null); + $('#emailDialog').dialog('close'); +} //********** SEQUENCE TAB FUNCTIONS ********** @@ -455,6 +475,21 @@ } }, { + 'text' : EMAIL_BUTTON_LABEL, + 'id' : 'learnerGroupDialogEmailButton', + 'class' : 'learnerGroupDialogSelectableButton', + 'click' : function() { + var selectedLearner = $('#learnerGroupList div.dialogListItemSelected'); + if (selectedLearner.length == 1) { + $('#emailDialog').dialog('option',{ + 'title' : 'Email user', + 'userId' : selectedLearner.attr('userId') + }) + .dialog('open'); + } + } + }, + { 'text' : CLOSE_BUTTON_LABEL, 'id' : 'learnerGroupDialogCloseButton', 'click' : function() { @@ -1251,7 +1286,7 @@ /** * Show a dialog with user list and optional Force Complete and View Learner buttons. */ -function showLearnerGroupDialog(activityId, dialogTitle, learners, allowForceComplete, allowView) { +function showLearnerGroupDialog(activityId, dialogTitle, learners, allowForceComplete, allowView, allowEmail) { var learnerGroupList = $('#learnerGroupList').empty(); var learnerGroupDialog = $('#learnerGroupDialog'); @@ -1265,7 +1300,7 @@ .text(getLearnerDisplayName(learner)) .appendTo(learnerGroupList); - if (allowForceComplete || allowView) { + if (allowForceComplete || allowView || allowEmail) { learnerDiv.click(function(){ // select a learner $(this).addClass('dialogListItemSelected') @@ -1290,6 +1325,8 @@ .css('display', allowForceComplete ? 'inline' : 'none'); $('button#learnerGroupDialogViewButton') .css('display', allowView ? 'inline' : 'none'); + $('button#learnerGroupDialogEmailButton') + .css('display', allowEmail ? 'inline' : 'none'); learnerGroupDialog .dialog('option', Index: lams_monitoring/web/monitor.jsp =================================================================== diff -u -r02163efabf3b7e31a55e3b7b348ed55dafa6afe6 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_monitoring/web/monitor.jsp (.../monitor.jsp) (revision 02163efabf3b7e31a55e3b7b348ed55dafa6afe6) +++ lams_monitoring/web/monitor.jsp (.../monitor.jsp) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -39,6 +39,7 @@ var LEARNER_GROUP_SHOW_LABEL = ''; var LEARNER_GROUP_LIST_TITLE_LABEL = ''; var VIEW_LEARNER_BUTTON_LABEL = ''; + var EMAIL_BUTTON_LABEL = ''; var CLOSE_BUTTON_LABEL = ''; var LEARNER_FINISHED_COUNT_LABEL = ''; var LEARNER_FINISHED_DIALOG_TITLE_LABEL = ''; @@ -395,6 +396,10 @@ +
+ +
+
Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/LearningAction.java =================================================================== diff -u -rc6afe89bc17f0901eeb6e5872333113b7462bada -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/LearningAction.java (.../LearningAction.java) (revision c6afe89bc17f0901eeb6e5872333113b7462bada) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/LearningAction.java (.../LearningAction.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -52,6 +52,7 @@ import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.lamsfoundation.lams.events.DeliveryMethodMail; +import org.lamsfoundation.lams.events.IEventNotificationService; import org.lamsfoundation.lams.learning.web.bean.ActivityPositionDTO; import org.lamsfoundation.lams.learning.web.util.LearningWebUtil; import org.lamsfoundation.lams.notebook.model.NotebookEntry; @@ -739,14 +740,14 @@ if (assessment.isNotifyTeachersOnAttemptCompletion()) { List monitoringUsers = service.getMonitorsByToolSessionId(toolSessionId); if (monitoringUsers != null && !monitoringUsers.isEmpty()) { - Long[] monitoringUsersIds = new Long[monitoringUsers.size()]; + Integer[] monitoringUsersIds = new Integer[monitoringUsers.size()]; for (int i = 0; i < monitoringUsersIds.length; i++) { - monitoringUsersIds[i] = monitoringUsers.get(i).getUserId().longValue(); + monitoringUsersIds[i] = monitoringUsers.get(i).getUserId(); } AssessmentUser assessmentUser = getCurrentUser(service, toolSessionId); String fullName = assessmentUser.getLastName() + " " + assessmentUser.getFirstName(); - service.getEventNotificationService().sendMessage(monitoringUsersIds, - DeliveryMethodMail.getInstance(), + service.getEventNotificationService().sendMessage(null, monitoringUsersIds, + IEventNotificationService.DELIVERY_METHOD_MAIL, service.getLocalisedMessage("event.learner.completes.attempt.subject", null), service.getLocalisedMessage("event.learner.completes.attempt.body", new Object[] { fullName }), isHtmlFormat); Index: lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/web/action/LearningAction.java =================================================================== diff -u -r8aded0b18a5a7712622ae56f38923fa297449977 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/web/action/LearningAction.java (.../LearningAction.java) (revision 8aded0b18a5a7712622ae56f38923fa297449977) +++ lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/web/action/LearningAction.java (.../LearningAction.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -54,6 +54,7 @@ import org.apache.struts.action.ActionMessages; import org.apache.struts.upload.FormFile; import org.lamsfoundation.lams.events.DeliveryMethodMail; +import org.lamsfoundation.lams.events.IEventNotificationService; import org.lamsfoundation.lams.learning.web.bean.ActivityPositionDTO; import org.lamsfoundation.lams.learning.web.util.LearningWebUtil; import org.lamsfoundation.lams.notebook.model.NotebookEntry; @@ -248,12 +249,12 @@ List monitoringUsers = service.getMonitorsByToolSessionId(sessionId); if (monitoringUsers != null && !monitoringUsers.isEmpty()) { - Long[] monitoringUsersIds = new Long[monitoringUsers.size()]; + Integer[] monitoringUsersIds = new Integer[monitoringUsers.size()]; for (int i = 0; i < monitoringUsersIds.length; i++) { - monitoringUsersIds[i] = monitoringUsers.get(i).getUserId().longValue(); + monitoringUsersIds[i] = monitoringUsers.get(i).getUserId(); } String fullName = dacoUser.getLastName() + " " + dacoUser.getFirstName(); - service.getEventNotificationService().sendMessage(monitoringUsersIds, DeliveryMethodMail.getInstance(), + service.getEventNotificationService().sendMessage(null, monitoringUsersIds, IEventNotificationService.DELIVERY_METHOD_MAIL, service.getLocalisedMessage("event.learnerentry.subject", null), service.getLocalisedMessage("event.learnerentry.body", new Object[] { fullName }), isHtmlFormat); @@ -509,13 +510,13 @@ List monitoringUsers = service.getMonitorsByToolSessionId(sessionId); if (monitoringUsers != null && !monitoringUsers.isEmpty()) { - Long[] monitoringUsersIds = new Long[monitoringUsers.size()]; + Integer[] monitoringUsersIds = new Integer[monitoringUsers.size()]; for (int i = 0; i < monitoringUsersIds.length; i++) { - monitoringUsersIds[i] = monitoringUsers.get(i).getUserId().longValue(); + monitoringUsersIds[i] = monitoringUsers.get(i).getUserId(); } String fullName = user.getLastName() + " " + user.getFirstName(); - service.getEventNotificationService().sendMessage(monitoringUsersIds, - DeliveryMethodMail.getInstance(), + service.getEventNotificationService().sendMessage(null, monitoringUsersIds, + IEventNotificationService.DELIVERY_METHOD_MAIL, service.getLocalisedMessage("event.recordsubmit.subject", null), service.getLocalisedMessage("event.recordsubmit.body", new Object[] { fullName }), isHtmlFormat); Index: lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java =================================================================== diff -u -r4fb3d978934e94b0008c9ff0bcdd53258298b1cf -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java (.../ForumService.java) (revision 4fb3d978934e94b0008c9ff0bcdd53258298b1cf) +++ lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java (.../ForumService.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -534,10 +534,10 @@ Forum forum = session.getForum(); boolean notifyLearnersOnMarkRelease = getEventNotificationService().eventExists(ForumConstants.TOOL_SIGNATURE, ForumConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, forum.getContentId()); - Map notificationMessages = null; + Map notificationMessages = null; Object[] notificationMessageParameters = null; if (notifyLearnersOnMarkRelease) { - notificationMessages = new TreeMap(); + notificationMessages = new TreeMap(); notificationMessageParameters = new Object[3]; } @@ -557,15 +557,15 @@ notificationMessageParameters[2] = report.getMark(); notificationMessage.append(getLocalisedMessage("event.mark.release.mark", notificationMessageParameters)); - notificationMessages.put(user.getUserId(), notificationMessage); + notificationMessages.put(user.getUserId().intValue(), notificationMessage); } } messageDao.saveOrUpdate(msg); } if (notifyLearnersOnMarkRelease) { notificationMessageParameters = new Object[1]; - for (Long userID : notificationMessages.keySet()) { + for (Integer userID : notificationMessages.keySet()) { notificationMessageParameters[0] = notificationMessages.get(userID).toString(); getEventNotificationService().triggerForSingleUser(ForumConstants.TOOL_SIGNATURE, ForumConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, forum.getContentId(), userID, @@ -1413,13 +1413,13 @@ if (forum.isNotifyLearnersOnForumPosting()) { List learners = lessonService.getLearnersHaveAttemptedActivity(activity); if (learners != null && !learners.isEmpty()) { - ArrayList learnerIds = new ArrayList(); + ArrayList learnerIds = new ArrayList(); for (User learner : learners) { - learnerIds.add(learner.getUserId().longValue()); + learnerIds.add(learner.getUserId()); } - getEventNotificationService().sendMessage(learnerIds.toArray(new Long[0]), - DeliveryMethodMail.getInstance(), + getEventNotificationService().sendMessage(null, learnerIds.toArray(new Integer[0]), + IEventNotificationService.DELIVERY_METHOD_MAIL, getLocalisedMessage("event.newposting.subject", new Object[] { forum.getTitle() }), getLocalisedMessage("event.newposting.body", new Object[] { fullName, message.getBody() }), isHtmlFormat); @@ -1429,13 +1429,13 @@ if (forum.isNotifyTeachersOnForumPosting()) { List monitoringUsers = lessonService.getMonitorsByToolSessionId(sessionId); if (monitoringUsers != null && !monitoringUsers.isEmpty()) { - ArrayList monitoringUsersIds = new ArrayList(); + ArrayList monitoringUsersIds = new ArrayList(); for (User monitoringUser : monitoringUsers) { - monitoringUsersIds.add(monitoringUser.getUserId().longValue()); + monitoringUsersIds.add(monitoringUser.getUserId()); } - getEventNotificationService().sendMessage(monitoringUsersIds.toArray(new Long[0]), - DeliveryMethodMail.getInstance(), + getEventNotificationService().sendMessage(null, monitoringUsersIds.toArray(new Integer[0]), + IEventNotificationService.DELIVERY_METHOD_MAIL, getLocalisedMessage("event.newposting.subject", new Object[] { forum.getTitle() }), getLocalisedMessage("event.newposting.body", new Object[] { fullName, message.getBody() }), isHtmlFormat); Index: lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/web/actions/LearningAction.java =================================================================== diff -u -r8aded0b18a5a7712622ae56f38923fa297449977 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/web/actions/LearningAction.java (.../LearningAction.java) (revision 8aded0b18a5a7712622ae56f38923fa297449977) +++ lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/web/actions/LearningAction.java (.../LearningAction.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -137,9 +137,9 @@ return updateMessageHideFlag(mapping, form, request, response); } if (param.equals("rateMessage")) { - return rateMessage(mapping, form, request, response); + return rateMessage(mapping, form, request, response); } - + // ================ Reflection ======================= if (param.equals("newReflection")) { return newReflection(mapping, form, request, response); @@ -201,7 +201,7 @@ // get session from shared session. HttpSession ss = SessionManager.getSession(); - + Forum forum = session.getForum(); // lock on finish ForumUser forumUser = getCurrentUser(request, sessionId); @@ -237,7 +237,7 @@ ActivityPositionDTO activityPosition = LearningWebUtil.putActivityPositionInRequestByToolSessionId(sessionId, request, getServlet().getServletContext()); sessionMap.put(AttributeNames.ATTR_ACTIVITY_POSITION, activityPosition); - + // Should we show the reflection or not? We shouldn't show it when the screen is accessed // from the Monitoring Summary screen, but we should when accessed from the Learner Progress screen. // Need to constantly past this value on, rather than hiding just the once, as the View Forum @@ -278,12 +278,13 @@ if (!forum.isAllowNewTopic()) { // add the number post the learner has made for each topic. for (MessageDTO messageDTO : rootTopics) { - int numOfPosts = forumService.getNumOfPostsByTopic(forumUser.getUserId(), messageDTO.getMessage().getUid()); + int numOfPosts = forumService.getNumOfPostsByTopic(forumUser.getUserId(), messageDTO.getMessage() + .getUid()); messageDTO.setNumOfPosts(numOfPosts); } } request.setAttribute(ForumConstants.AUTHORING_TOPICS_LIST, rootTopics); - + // update new messages number for (MessageDTO messageDTO : rootTopics) { int numOfNewPosts = forumService.getNewMessagesNum(messageDTO.getMessage(), forumUser.getUid()); @@ -292,32 +293,31 @@ if (forum.isNotifyLearnersOnMarkRelease()) { boolean isHtmlFormat = false; - + forumService.getEventNotificationService().createEvent(ForumConstants.TOOL_SIGNATURE, ForumConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, forum.getContentId(), forumService.getLocalisedMessage("event.mark.release.subject", null), - forumService.getLocalisedMessage("event.mark.release.body", null), - isHtmlFormat); + forumService.getLocalisedMessage("event.mark.release.body", null), isHtmlFormat); + UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); forumService.getEventNotificationService().subscribe(ForumConstants.TOOL_SIGNATURE, - ForumConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, forum.getContentId(), - forumUser.getUserId().longValue(), IEventNotificationService.DELIVERY_METHOD_MAIL, - IEventNotificationService.PERIODICITY_SINGLE); + ForumConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, forum.getContentId(), user.getUserID(), + IEventNotificationService.DELIVERY_METHOD_MAIL, IEventNotificationService.PERIODICITY_SINGLE); } - + // check if there is submission deadline Date submissionDeadline = forum.getSubmissionDeadline(); if (submissionDeadline != null) { - sessionMap.put(ForumConstants.ATTR_SUBMISSION_DEADLINE, forum.getSubmissionDeadline()); - UserDTO learnerDto = (UserDTO) ss.getAttribute(AttributeNames.USER); - TimeZone learnerTimeZone = learnerDto.getTimeZone(); - Date tzSubmissionDeadline = DateUtil.convertToTimeZoneFromDefault(learnerTimeZone, submissionDeadline); - Date currentLearnerDate = DateUtil.convertToTimeZoneFromDefault(learnerTimeZone, new Date()); - - //calculate whether submission deadline has passed, and if so forward to "runOffline" - if (currentLearnerDate.after(tzSubmissionDeadline)) { - return mapping.findForward("runOffline"); - } + sessionMap.put(ForumConstants.ATTR_SUBMISSION_DEADLINE, forum.getSubmissionDeadline()); + UserDTO learnerDto = (UserDTO) ss.getAttribute(AttributeNames.USER); + TimeZone learnerTimeZone = learnerDto.getTimeZone(); + Date tzSubmissionDeadline = DateUtil.convertToTimeZoneFromDefault(learnerTimeZone, submissionDeadline); + Date currentLearnerDate = DateUtil.convertToTimeZoneFromDefault(learnerTimeZone, new Date()); + + // calculate whether submission deadline has passed, and if so forward to "runOffline" + if (currentLearnerDate.after(tzSubmissionDeadline)) { + return mapping.findForward("runOffline"); + } } return mapping.findForward("success"); @@ -559,7 +559,7 @@ MessageDTO last = rootTopics.get(rootTopics.size() - 1); maxSeq = last.getMessage().getSequenceId() + 1; } - message.setSequenceId(maxSeq); + message.setSequenceId(maxSeq); ForumUser forumUser = getCurrentUser(request, sessionId); message.setCreatedBy(forumUser); message.setModifiedBy(forumUser); @@ -576,15 +576,15 @@ forumService.saveTimestamp(message.getUid(), forumUser); - //update new messages number + // update new messages number for (MessageDTO messageDTO : rootTopics) { int numOfNewPosts = forumService.getNewMessagesNum(messageDTO.getMessage(), forumUser.getUid()); messageDTO.setNewPostingsNum(numOfNewPosts); } - + // notify learners and teachers forumService.sendNotificationsOnNewPosting(forumId, sessionId, message); - + return mapping.findForward("success"); } @@ -606,7 +606,7 @@ Long parentId = WebUtil.readLongParam(request, ForumConstants.ATTR_PARENT_TOPIC_ID); sessionMap.put(ForumConstants.ATTR_PARENT_TOPIC_ID, parentId); - + // get parent topic, it can decide default subject of reply. MessageDTO topic = getTopic(parentId); if (topic != null && topic.getMessage() != null) { @@ -623,7 +623,7 @@ msgForm.getMessage().setSubject(reTitle); } } - + // Should we show the reflection or not? We shouldn't show it when the View Forum screen is accessed // from the Monitoring Summary screen, but we should when accessed from the Learner Progress screen. // Need to constantly past this value on, rather than hiding just the once, as the View Forum @@ -696,7 +696,7 @@ // Saving or updating user timestamp forumService.saveTimestamp(rootTopicId, forumUser); - + // notify learners and teachers Long forumId = (Long) sessionMap.get(ForumConstants.FORUM_ID); forumService.sendNotificationsOnNewPosting(forumId, sessionId, message); @@ -744,8 +744,7 @@ /** * Delete attachment from topic. This method only reset attachment information in memory. The finally update will - * happen in updateTopic method. So topic can keep this attachment if user choose "Cancel" edit - * topic. + * happen in updateTopic method. So topic can keep this attachment if user choose "Cancel" edit topic. * * @param mapping * @param form @@ -862,7 +861,7 @@ // check if the user has permission to hide posts. // ForumToolSession toolSession = forumService // .getSessionBySessionId(sessionId); - // + // // Forum forum = toolSession.getForum(); // ForumUser currentUser = getCurrentUser(request,sessionId); // ForumUser forumCreatedBy = forum.getCreatedBy(); @@ -880,12 +879,12 @@ List msgDtoList = forumService.getTopicThread(rootTopicId); updateMesssageFlag(msgDtoList); request.setAttribute(ForumConstants.AUTHORING_TOPIC_THREAD, msgDtoList); - request.setAttribute(ForumConstants.ATTR_SESSION_MAP_ID, WebUtil.readStrParam(request, - ForumConstants.ATTR_SESSION_MAP_ID)); + request.setAttribute(ForumConstants.ATTR_SESSION_MAP_ID, + WebUtil.readStrParam(request, ForumConstants.ATTR_SESSION_MAP_ID)); return mapping.findForward("success"); } - + /** * Rates postings submitted by other learners. * @@ -945,8 +944,8 @@ if (numOfPostsInTopic < forum.getMinimumReply()) { // create error ActionMessages errors = new ActionMessages(); - errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.less.mini.post", forum - .getMinimumReply())); + errors.add(ActionMessages.GLOBAL_MESSAGE, + new ActionMessage("error.less.mini.post", forum.getMinimumReply())); saveErrors(request, errors); // get all root topic to display on init page @@ -962,8 +961,8 @@ } /** - * This method will set flag in message DTO: - *
  • If this topic is created by current login user, then set Author mark true.
  • + * This method will set flag in message DTO:
  • If this topic is created by current login user, then set Author + * mark true.
  • * * @param msgDtoList */ Index: lams_tool_images/src/java/org/lamsfoundation/lams/tool/imageGallery/web/action/LearningAction.java =================================================================== diff -u -r8aded0b18a5a7712622ae56f38923fa297449977 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_tool_images/src/java/org/lamsfoundation/lams/tool/imageGallery/web/action/LearningAction.java (.../LearningAction.java) (revision 8aded0b18a5a7712622ae56f38923fa297449977) +++ lams_tool_images/src/java/org/lamsfoundation/lams/tool/imageGallery/web/action/LearningAction.java (.../LearningAction.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -49,6 +49,7 @@ import org.apache.struts.config.ForwardConfig; import org.apache.struts.upload.FormFile; import org.lamsfoundation.lams.events.DeliveryMethodMail; +import org.lamsfoundation.lams.events.IEventNotificationService; import org.lamsfoundation.lams.learning.web.bean.ActivityPositionDTO; import org.lamsfoundation.lams.learning.web.util.LearningWebUtil; import org.lamsfoundation.lams.notebook.model.NotebookEntry; @@ -170,8 +171,8 @@ if (mode != null && mode.isTeacher()) { // monitoring mode - user is specified in URL // imageGalleryUser may be null if the user was force completed. - imageGalleryUser = getSpecifiedUser(service, sessionId, WebUtil.readIntParam(request, - AttributeNames.PARAM_USER_ID, false)); + imageGalleryUser = getSpecifiedUser(service, sessionId, + WebUtil.readIntParam(request, AttributeNames.PARAM_USER_ID, false)); } else { imageGalleryUser = getCurrentUser(service, sessionId); } @@ -199,8 +200,8 @@ sessionMap.put(ImageGalleryConstants.ATTR_RESOURCE_INSTRUCTION, imageGallery.getInstructions()); sessionMap.put(ImageGalleryConstants.ATTR_FINISH_LOCK, lock); sessionMap.put(ImageGalleryConstants.ATTR_LOCK_ON_FINISH, imageGallery.getLockWhenFinished()); - sessionMap.put(ImageGalleryConstants.ATTR_USER_FINISHED, imageGalleryUser != null - && imageGalleryUser.isSessionFinished()); + sessionMap.put(ImageGalleryConstants.ATTR_USER_FINISHED, + imageGalleryUser != null && imageGalleryUser.isSessionFinished()); sessionMap.put(AttributeNames.PARAM_TOOL_SESSION_ID, sessionId); sessionMap.put(AttributeNames.ATTR_MODE, mode); @@ -213,11 +214,11 @@ .getConfigItem(ImageGalleryConfigItem.KEY_MEDIUM_IMAGE_DIMENSIONS); ImageGalleryConfigItem thumbnailImageDimensionsKey = service .getConfigItem(ImageGalleryConfigItem.KEY_THUMBNAIL_IMAGE_DIMENSIONS); - sessionMap.put(ImageGalleryConstants.ATTR_MEDIUM_IMAGE_DIMENSIONS, Integer.parseInt(mediumImageDimensionsKey - .getConfigValue())); - sessionMap.put(ImageGalleryConstants.ATTR_THUMBNAIL_IMAGE_DIMENSIONS, Integer - .parseInt(thumbnailImageDimensionsKey.getConfigValue())); - + sessionMap.put(ImageGalleryConstants.ATTR_MEDIUM_IMAGE_DIMENSIONS, + Integer.parseInt(mediumImageDimensionsKey.getConfigValue())); + sessionMap.put(ImageGalleryConstants.ATTR_THUMBNAIL_IMAGE_DIMENSIONS, + Integer.parseInt(thumbnailImageDimensionsKey.getConfigValue())); + // add define later support if (imageGallery.isDefineLater()) { return mapping.findForward("defineLater"); @@ -231,7 +232,7 @@ ActivityPositionDTO activityPosition = LearningWebUtil.putActivityPositionInRequestByToolSessionId(sessionId, request, getServlet().getServletContext()); sessionMap.put(AttributeNames.ATTR_ACTIVITY_POSITION, activityPosition); - + // add run offline support if (imageGallery.getRunOffline()) { sessionMap.put(ImageGalleryConstants.PARAM_RUN_OFFLINE, true); @@ -416,7 +417,7 @@ return mapping.findForward(ImageGalleryConstants.SUCCESS); } - + /** * Save file or url imageGallery item into database. * @@ -429,16 +430,16 @@ private ActionForward deleteImage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { IImageGalleryService service = getImageGalleryService(); - + Long imageUid = new Long(request.getParameter(ImageGalleryConstants.PARAM_IMAGE_UID)); String sessionMapID = request.getParameter(ImageGalleryConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE); Long sessionId = (Long) sessionMap.get(ImageGalleryConstants.ATTR_TOOL_SESSION_ID); service.deleteImage(sessionId, imageUid); - - // redirect + + // redirect ForwardConfig redirectConfig = mapping.findForwardConfig(ImageGalleryConstants.SUCCESS); ActionRedirect redirect = new ActionRedirect(redirectConfig); redirect.addParameter(AttributeNames.ATTR_MODE, mode); @@ -512,10 +513,11 @@ } sessionMap.put(ImageGalleryConstants.PARAM_IS_VOTED, isVotedForThisImage); } - - //set visibility of "Delete image" button + + // set visibility of "Delete image" button ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE); - boolean isAuthor = !mode.isTeacher() && !image.isCreateByAuthor() && (createdBy != null) && (createdBy.getUserId().equals(imageGalleryUser.getUserId())); + boolean isAuthor = !mode.isTeacher() && !image.isCreateByAuthor() && (createdBy != null) + && (createdBy.getUserId().equals(imageGalleryUser.getUserId())); sessionMap.put(ImageGalleryConstants.PARAM_IS_AUTHOR, isAuthor); request.setAttribute(ImageGalleryConstants.ATTR_SESSION_MAP_ID, sessionMapID); @@ -831,18 +833,18 @@ // notify teachers if (imageGallery.isNotifyTeachersOnImageSumbit()) { final boolean isHtmlFormat = false; - + List monitoringUsers = service.getMonitorsByToolSessionId(sessionId); if (monitoringUsers != null && !monitoringUsers.isEmpty()) { - Long[] monitoringUsersIds = new Long[monitoringUsers.size()]; + Integer[] monitoringUsersIds = new Integer[monitoringUsers.size()]; for (int i = 0; i < monitoringUsersIds.length; i++) { - monitoringUsersIds[i] = monitoringUsers.get(i).getUserId().longValue(); + monitoringUsersIds[i] = monitoringUsers.get(i).getUserId(); } String fullName = imageGalleryUser.getLastName() + " " + imageGalleryUser.getFirstName(); - service.getEventNotificationService().sendMessage(monitoringUsersIds, DeliveryMethodMail.getInstance(), + service.getEventNotificationService().sendMessage(null, monitoringUsersIds, + IEventNotificationService.DELIVERY_METHOD_MAIL, service.getLocalisedMessage("event.imagesubmit.subject", null), - service.getLocalisedMessage("event.imagesubmit.body", new Object[] { fullName }), - isHtmlFormat); + service.getLocalisedMessage("event.imagesubmit.body", new Object[] { fullName }), isHtmlFormat); } } } Index: lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/web/action/LearningAction.java =================================================================== diff -u -r8aded0b18a5a7712622ae56f38923fa297449977 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/web/action/LearningAction.java (.../LearningAction.java) (revision 8aded0b18a5a7712622ae56f38923fa297449977) +++ lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/web/action/LearningAction.java (.../LearningAction.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -49,6 +49,7 @@ import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.lamsfoundation.lams.events.DeliveryMethodMail; +import org.lamsfoundation.lams.events.IEventNotificationService; import org.lamsfoundation.lams.learning.web.bean.ActivityPositionDTO; import org.lamsfoundation.lams.learning.web.util.LearningWebUtil; import org.lamsfoundation.lams.notebook.model.NotebookEntry; @@ -165,8 +166,8 @@ if (mode != null && mode.isTeacher()) { // monitoring mode - user is specified in URL // resourceUser may be null if the user was force completed. - resourceUser = getSpecifiedUser(service, sessionId, WebUtil.readIntParam(request, - AttributeNames.PARAM_USER_ID, false)); + resourceUser = getSpecifiedUser(service, sessionId, + WebUtil.readIntParam(request, AttributeNames.PARAM_USER_ID, false)); } else { resourceUser = getCurrentUser(service, sessionId); } @@ -397,15 +398,16 @@ Resource resource = resSession.getResource(); if (resource.isNotifyTeachersOnAssigmentSumbit()) { final boolean isHtmlFormat = false; - + List monitoringUsers = service.getMonitorsByToolSessionId(sessionId); if (monitoringUsers != null && !monitoringUsers.isEmpty()) { - Long[] monitoringUsersIds = new Long[monitoringUsers.size()]; + Integer[] monitoringUsersIds = new Integer[monitoringUsers.size()]; for (int i = 0; i < monitoringUsersIds.length; i++) { - monitoringUsersIds[i] = monitoringUsers.get(i).getUserId().longValue(); + monitoringUsersIds[i] = monitoringUsers.get(i).getUserId(); } String fullName = resourceUser.getLastName() + " " + resourceUser.getFirstName(); - service.getEventNotificationService().sendMessage(monitoringUsersIds, DeliveryMethodMail.getInstance(), + service.getEventNotificationService().sendMessage(null, monitoringUsersIds, + IEventNotificationService.DELIVERY_METHOD_MAIL, service.getLocalisedMessage("event.assigment.submit.subject", null), service.getLocalisedMessage("event.assigment.submit.body", new Object[] { fullName }), isHtmlFormat); Index: lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java =================================================================== diff -u -racb0851f5348ca7f4d535d181d6b35fcb539272c -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java (.../SubmitFilesService.java) (revision acb0851f5348ca7f4d535d181d6b35fcb539272c) +++ lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java (.../SubmitFilesService.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -819,10 +819,10 @@ SubmitFilesContent content = session.getContent(); boolean notifyLearnersOnMarkRelease = getEventNotificationService().eventExists(SbmtConstants.TOOL_SIGNATURE, SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID()); - Map notificationMessages = null; + Map notificationMessages = null; Object[] notificationMessageParameters = null; if (notifyLearnersOnMarkRelease) { - notificationMessages = new TreeMap(); + notificationMessages = new TreeMap(); notificationMessageParameters = new Object[3]; } while (iter.hasNext()) { @@ -840,14 +840,14 @@ notificationMessageParameters[2] = report.getMarks(); notificationMessage .append(getLocalisedMessage("event.mark.release.mark", notificationMessageParameters)); - notificationMessages.put(user.getUserID().longValue(), notificationMessage); + notificationMessages.put(user.getUserID(), notificationMessage); } submitFilesReportDAO.updateReport(report); } // current there is no false return if (notifyLearnersOnMarkRelease) { notificationMessageParameters = new Object[1]; - for (Long userID : notificationMessages.keySet()) { + for (Integer userID : notificationMessages.keySet()) { notificationMessageParameters[0] = notificationMessages.get(userID).toString(); getEventNotificationService().triggerForSingleUser(SbmtConstants.TOOL_SIGNATURE, SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID(), userID, Index: lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/web/LearnerAction.java =================================================================== diff -u -r8aded0b18a5a7712622ae56f38923fa297449977 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/web/LearnerAction.java (.../LearnerAction.java) (revision 8aded0b18a5a7712622ae56f38923fa297449977) +++ lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/web/LearnerAction.java (.../LearnerAction.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -178,19 +178,19 @@ if (content.isRunOffline()) { return mapping.findForward("runOffline"); } - - //check if there is submission deadline + + // check if there is submission deadline Date submissionDeadline = content.getSubmissionDeadline(); if (submissionDeadline != null) { - //store submission deadline to sessionMap + // store submission deadline to sessionMap sessionMap.put(SbmtConstants.ATTR_SUBMISSION_DEADLINE, submissionDeadline); - + UserDTO learnerDto = (UserDTO) ss.getAttribute(AttributeNames.USER); TimeZone learnerTimeZone = learnerDto.getTimeZone(); Date tzSubmissionDeadline = DateUtil.convertToTimeZoneFromDefault(learnerTimeZone, submissionDeadline); Date currentLearnerDate = DateUtil.convertToTimeZoneFromDefault(learnerTimeZone, new Date()); - - //calculate whether submission deadline has passed, and if so forward to "runOffline" + + // calculate whether submission deadline has passed, and if so forward to "runOffline" if (currentLearnerDate.after(tzSubmissionDeadline)) { return mapping.findForward("runOffline"); } @@ -204,9 +204,8 @@ submitFilesService.getLocalisedMessage("event.mark.release.body", null), isHtmlFormat); submitFilesService.getEventNotificationService().subscribe(SbmtConstants.TOOL_SIGNATURE, - SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID(), - learner.getUserID().longValue(), IEventNotificationService.DELIVERY_METHOD_MAIL, - IEventNotificationService.PERIODICITY_SINGLE); + SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID(), userID, + IEventNotificationService.DELIVERY_METHOD_MAIL, IEventNotificationService.PERIODICITY_SINGLE); } return mapping.findForward(SbmtConstants.SUCCESS); @@ -235,7 +234,7 @@ LearningWebUtil.putActivityPositionInRequestByToolSessionId(sessionID, request, getServlet() .getServletContext()); - + if (validateUploadForm(learnerForm, request)) { // get session from shared session. HttpSession ss = SessionManager.getSession(); @@ -277,13 +276,13 @@ boolean isHtmlFormat = false; List monitoringUsers = submitFilesService.getMonitorsByToolSessionId(sessionID); if (monitoringUsers != null && !monitoringUsers.isEmpty()) { - Long[] monitoringUsersIds = new Long[monitoringUsers.size()]; + Integer[] monitoringUsersIds = new Integer[monitoringUsers.size()]; for (int i = 0; i < monitoringUsersIds.length; i++) { - monitoringUsersIds[i] = monitoringUsers.get(i).getUserId().longValue(); + monitoringUsersIds[i] = monitoringUsers.get(i).getUserId(); } String fullName = learner.getLastName() + " " + learner.getFirstName(); - submitFilesService.getEventNotificationService().sendMessage(monitoringUsersIds, - DeliveryMethodMail.getInstance(), + submitFilesService.getEventNotificationService().sendMessage(null, monitoringUsersIds, + IEventNotificationService.DELIVERY_METHOD_MAIL, submitFilesService.getLocalisedMessage("event.file.submit.subject", null), submitFilesService.getLocalisedMessage("event.file.submit.body", new Object[] { fullName }), isHtmlFormat); @@ -434,8 +433,8 @@ // retrieve notebook reflection entry. ISubmitFilesService submitFilesService = getService(); - NotebookEntry notebookEntry = submitFilesService.getEntry((Long) sessionMap - .get(AttributeNames.PARAM_TOOL_SESSION_ID), CoreNotebookConstants.NOTEBOOK_TOOL, + NotebookEntry notebookEntry = submitFilesService.getEntry( + (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID), CoreNotebookConstants.NOTEBOOK_TOOL, SbmtConstants.TOOL_SIGNATURE, currUser.getUserID()); if (notebookEntry != null) { Index: lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/web/action/LearningAction.java =================================================================== diff -u -r8aded0b18a5a7712622ae56f38923fa297449977 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/web/action/LearningAction.java (.../LearningAction.java) (revision 8aded0b18a5a7712622ae56f38923fa297449977) +++ lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/web/action/LearningAction.java (.../LearningAction.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -49,6 +49,7 @@ import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.lamsfoundation.lams.events.DeliveryMethodMail; +import org.lamsfoundation.lams.events.IEventNotificationService; import org.lamsfoundation.lams.learning.web.bean.ActivityPositionDTO; import org.lamsfoundation.lams.learning.web.util.LearningWebUtil; import org.lamsfoundation.lams.notebook.model.NotebookEntry; @@ -139,20 +140,20 @@ SessionMap sessionMap = new SessionMap(); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); answerForm.setSessionMapID(sessionMap.getSessionID()); - + // save toolContentID into HTTPSession ToolAccessMode mode = WebUtil.readToolAccessModeParam(request, AttributeNames.PARAM_MODE, true); Long sessionId = new Long(request.getParameter(AttributeNames.PARAM_TOOL_SESSION_ID)); // it will be use when runOffline or lock on finish page. request.setAttribute(SurveyConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); - + // get back the survey and question list and display them on page ISurveyService service = getSurveyService(); SurveyUser surveyUser = null; if (mode != null && mode.isTeacher()) { // monitoring mode - user is specified in URL - surveyUser = getSpecifiedUser(service, sessionId, WebUtil.readIntParam(request, - AttributeNames.PARAM_USER_ID, false)); + surveyUser = getSpecifiedUser(service, sessionId, + WebUtil.readIntParam(request, AttributeNames.PARAM_USER_ID, false)); // setting Learner Long userID = WebUtil.readLongParam(request, AttributeNames.PARAM_USER_ID, true); answerForm.setUserID(userID); @@ -178,7 +179,7 @@ // get session from shared session. HttpSession ss = SessionManager.getSession(); - + // basic information sessionMap.put(SurveyConstants.ATTR_TITLE, survey.getTitle()); sessionMap.put(SurveyConstants.ATTR_SURVEY_INSTRUCTION, survey.getInstructions()); @@ -219,20 +220,20 @@ // check if there is submission deadline Date submissionDeadline = survey.getSubmissionDeadline(); if (submissionDeadline != null) { - //store submission deadline to sessionMap + // store submission deadline to sessionMap sessionMap.put(SurveyConstants.ATTR_SUBMISSION_DEADLINE, submissionDeadline); - + UserDTO learnerDto = (UserDTO) ss.getAttribute(AttributeNames.USER); TimeZone learnerTimeZone = learnerDto.getTimeZone(); Date tzSubmissionDeadline = DateUtil.convertToTimeZoneFromDefault(learnerTimeZone, submissionDeadline); Date currentLearnerDate = DateUtil.convertToTimeZoneFromDefault(learnerTimeZone, new Date()); - - //calculate whether submission deadline has passed, and if so forward to "runOffline" + + // calculate whether submission deadline has passed, and if so forward to "runOffline" if (currentLearnerDate.after(tzSubmissionDeadline)) { - return mapping.findForward(SurveyConstants.RUN_OFFLINE); + return mapping.findForward(SurveyConstants.RUN_OFFLINE); } - } - + } + // init survey item list SortedMap surveyItemList = getQuestionList(sessionMap); surveyItemList.clear(); @@ -357,16 +358,16 @@ private ActionForward doSurvey(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ISurveyService service = getSurveyService(); - + AnswerForm answerForm = (AnswerForm) form; Integer questionSeqID = answerForm.getQuestionSeqID(); String sessionMapID = answerForm.getSessionMapID(); SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); - + // validate SortedMap surveyItemMap = getQuestionList(sessionMap); Collection surveyItemList = surveyItemMap.values(); - + SurveyUser surveyLearner = null; Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID); @@ -375,7 +376,7 @@ surveyLearner = service.getUserByIDAndSession(userID, sessionId); request.setAttribute(AttributeNames.PARAM_USER_ID, userID); } - + ActionErrors errors; if (questionSeqID == null || questionSeqID.equals(0)) { errors = getAnswers(request); @@ -404,15 +405,16 @@ UserDTO surveyUser = (UserDTO) ss.getAttribute(AttributeNames.USER); if (survey.isNotifyTeachersOnAnswerSumbit()) { final boolean isHtmlFormat = false; - + List monitoringUsers = service.getMonitorsByToolSessionId(sessionId); if (monitoringUsers != null && !monitoringUsers.isEmpty()) { - Long[] monitoringUsersIds = new Long[monitoringUsers.size()]; + Integer[] monitoringUsersIds = new Integer[monitoringUsers.size()]; for (int i = 0; i < monitoringUsersIds.length; i++) { - monitoringUsersIds[i] = monitoringUsers.get(i).getUserId().longValue(); + monitoringUsersIds[i] = monitoringUsers.get(i).getUserId(); } String fullName = surveyUser.getLastName() + " " + surveyUser.getFirstName(); - service.getEventNotificationService().sendMessage(monitoringUsersIds, DeliveryMethodMail.getInstance(), + service.getEventNotificationService().sendMessage(null, monitoringUsersIds, + IEventNotificationService.DELIVERY_METHOD_MAIL, service.getLocalisedMessage("event.answer.submit.subject", null), service.getLocalisedMessage("event.answer.submit.body", new Object[] { fullName }), isHtmlFormat); @@ -582,7 +584,7 @@ private void validateAnswers(HttpServletRequest request, AnswerDTO question, ActionErrors errors, SurveyAnswer answer) { boolean isAnswerEmpty = (answer.getChoices() == null && StringUtils.isBlank(answer.getAnswerText())); - + // for mandatory questions, answer can not be null. if (!question.isOptional() && isAnswerEmpty) { errors.add(SurveyConstants.ERROR_MSG_KEY + question.getUid(), new ActionMessage( Index: lams_tool_wiki/src/java/org/lamsfoundation/lams/tool/wiki/web/actions/WikiPageAction.java =================================================================== diff -u -r84151d175a3fce3cd3ff1bd4eeccfd7cbef01802 -r1edbb81f16cedfcc1326e4eca6e520b5b48cbddc --- lams_tool_wiki/src/java/org/lamsfoundation/lams/tool/wiki/web/actions/WikiPageAction.java (.../WikiPageAction.java) (revision 84151d175a3fce3cd3ff1bd4eeccfd7cbef01802) +++ lams_tool_wiki/src/java/org/lamsfoundation/lams/tool/wiki/web/actions/WikiPageAction.java (.../WikiPageAction.java) (revision 1edbb81f16cedfcc1326e4eca6e520b5b48cbddc) @@ -513,11 +513,11 @@ if (subscribed) { // unsubscribe the learner to the event notificationService.unsubscribe(WikiConstants.TOOL_SIGNATURE, WikiConstants.EVENT_NOTIFY_LEARNERS, - toolSessionID, user.getUserID().longValue()); + toolSessionID, user.getUserID()); } else { // subscribe the learner to the event notificationService.subscribe(WikiConstants.TOOL_SIGNATURE, WikiConstants.EVENT_NOTIFY_LEARNERS, - toolSessionID, user.getUserID().longValue(), IEventNotificationService.DELIVERY_METHOD_MAIL, + toolSessionID, user.getUserID(), IEventNotificationService.DELIVERY_METHOD_MAIL, IEventNotificationService.PERIODICITY_SINGLE); } @@ -547,9 +547,9 @@ boolean isHtmlFormat = false; List users = wikiService.getMonitorsByToolSessionId(toolSessionID); - Long[] monitoringUsersIds = new Long[users.size()]; + Integer[] monitoringUsersIds = new Integer[users.size()]; for (int i = 0; i < monitoringUsersIds.length; i++) { - monitoringUsersIds[i] = users.get(i).getUserId().longValue(); + monitoringUsersIds[i] = users.get(i).getUserId(); } String relativePath = "/tool/" + WikiConstants.TOOL_SIGNATURE @@ -565,7 +565,7 @@ String body = wikiService.getLocalisedMessage(bodyLangKey, new Object[] { fullName, wikiSession.getSessionName(), link }); - notificationService.sendMessage(monitoringUsersIds, IEventNotificationService.DELIVERY_METHOD_MAIL, + notificationService.sendMessage(null, monitoringUsersIds, IEventNotificationService.DELIVERY_METHOD_MAIL, subject, body, isHtmlFormat); }