Fisheye: Tag 33829c670fd8c90447d62ea3300498a103905e7a refers to a dead (removed) revision in file `lams_central/src/java/org/lamsfoundation/lams/authoring/web/AuthoringConstants.java'. Fisheye: No comparison available. Pass `N' to diff? Index: lams_central/src/java/org/lamsfoundation/lams/rest/LearningDesignRestServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/rest/LearningDesignRestServlet.java (.../LearningDesignRestServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/rest/LearningDesignRestServlet.java (.../LearningDesignRestServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -39,7 +39,7 @@ protected void doPostInternal(ObjectNode requestJSON, UserDTO userDTO, HttpServletResponse response) throws Exception { ObjectNode learningDesignJSON = JsonUtil.optObject(requestJSON, "ld"); - LearningDesign learningDesign = getAuthoringService().saveLearningDesignDetails(learningDesignJSON); + LearningDesign learningDesign = authoringService.saveLearningDesignDetails(learningDesignJSON); ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); ObjectNode.put("learningDesignID", learningDesign.getLearningDesignId()); Index: lams_central/src/java/org/lamsfoundation/lams/rest/RestServlet.java =================================================================== diff -u -r62aaf160878735888d077bf28fac3c1989bb8fbd -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/rest/RestServlet.java (.../RestServlet.java) (revision 62aaf160878735888d077bf28fac3c1989bb8fbd) +++ lams_central/src/java/org/lamsfoundation/lams/rest/RestServlet.java (.../RestServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -24,6 +24,7 @@ import java.io.IOException; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -40,7 +41,6 @@ import org.lamsfoundation.lams.integration.security.AuthenticationException; import org.lamsfoundation.lams.integration.security.Authenticator; import org.lamsfoundation.lams.integration.service.IIntegrationService; -import org.lamsfoundation.lams.integration.service.IntegrationService; import org.lamsfoundation.lams.integration.util.LoginRequestDispatcher; import org.lamsfoundation.lams.tool.dao.IToolDAO; import org.lamsfoundation.lams.tool.service.ILamsCoreToolService; @@ -49,8 +49,8 @@ import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; 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; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -65,11 +65,26 @@ private static final Logger log = Logger.getLogger(RestServlet.class); - private static IToolDAO toolDAO; - private static ILamsCoreToolService lamsCoreToolService; - private static IIntegrationService integrationService; - private static IAuthoringFullService authoringFullService; - private static IUserManagementService userManagementService; + @Autowired + protected IToolDAO toolDAO; + @Autowired + protected ILamsCoreToolService lamsCoreToolService; + @Autowired + protected IIntegrationService integrationService; + @Autowired + protected IAuthoringFullService authoringService; + @Autowired + protected IUserManagementService userManagementService; + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } /** * Checks if the provided auth JSON is valid. @@ -78,7 +93,7 @@ User user = null; try { String serverName = authenticationJSON.get(LoginRequestDispatcher.PARAM_SERVER_ID).asText(); - ExtServer extServer = getIntegrationService().getExtServer(serverName); + ExtServer extServer = integrationService.getExtServer(serverName); String userName = authenticationJSON.get(LoginRequestDispatcher.PARAM_USER_ID).asText(); String method = authenticationJSON.get(LoginRequestDispatcher.PARAM_METHOD).asText().toLowerCase(); String timestamp = authenticationJSON.get(LoginRequestDispatcher.PARAM_TIMESTAMP).asText(); @@ -87,30 +102,22 @@ // Throws AuthenticationException if it fails Authenticator.authenticateLoginRequest(extServer, timestamp, userName, method, null, hash); - ExtUserUseridMap userMap = getIntegrationService().getExtUserUseridMap(extServer, userName); + ExtUserUseridMap userMap = integrationService.getExtUserUseridMap(extServer, userName); user = userMap.getUser(); // get concrete user - user = (User) getUserManagementService().findById(User.class, user.getUserId()); + user = (User) userManagementService.findById(User.class, user.getUserId()); return user.getUserDTO(); } catch (AuthenticationException e) { - RestServlet.log.error("The user was not authenticated", e); + log.error("The user was not authenticated", e); } catch (UserInfoFetchException e) { - RestServlet.log.error("Could not fetch new user information from integration server", e); + log.error("Could not fetch new user information from integration server", e); } catch (UserInfoValidationException e) { - RestServlet.log.error("User data is not valid", e); + log.error("User data is not valid", e); } return null; } - private IIntegrationService getIntegrationService() { - if (RestServlet.integrationService == null) { - RestServlet.integrationService = (IntegrationService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("integrationService"); - } - return RestServlet.integrationService; - } - @Override protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -157,40 +164,4 @@ protected abstract void doPostInternal(ObjectNode requestJSON, UserDTO userDTO, HttpServletResponse response) throws Exception; - - protected final IAuthoringFullService getAuthoringService() { - if (RestServlet.authoringFullService == null) { - WebApplicationContext ctx = WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()); - RestServlet.authoringFullService = (IAuthoringFullService) ctx.getBean("authoringFullService"); - } - return RestServlet.authoringFullService; - } - - protected ILamsCoreToolService getLamsCoreToolService() { - if (RestServlet.lamsCoreToolService == null) { - WebApplicationContext ctx = WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()); - RestServlet.lamsCoreToolService = (ILamsCoreToolService) ctx.getBean("lamsCoreToolService"); - } - return RestServlet.lamsCoreToolService; - } - - protected IToolDAO getToolDAO() { - if (RestServlet.toolDAO == null) { - WebApplicationContext ctx = WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()); - RestServlet.toolDAO = (IToolDAO) ctx.getBean("toolDAO"); - } - return RestServlet.toolDAO; - } - - protected final IUserManagementService getUserManagementService() { - if (RestServlet.userManagementService == null) { - WebApplicationContext ctx = WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()); - RestServlet.userManagementService = (IUserManagementService) ctx.getBean("userManagementService"); - } - return RestServlet.userManagementService; - } } \ No newline at end of file Index: lams_central/src/java/org/lamsfoundation/lams/rest/ToolContentRestServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/rest/ToolContentRestServlet.java (.../ToolContentRestServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/rest/ToolContentRestServlet.java (.../ToolContentRestServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -39,12 +39,12 @@ throws Exception { // find out which Tool to create String toolSignature = JsonUtil.optString(requestJSON, "toolSignature"); - Tool tool = getToolDAO().getToolBySignature(toolSignature); - Long toolContentID = getAuthoringService().insertToolContentID(tool.getToolId()); + Tool tool = toolDAO.getToolBySignature(toolSignature); + Long toolContentID = authoringService.insertToolContentID(tool.getToolId()); ObjectNode toolContentJSON = JsonUtil.optObject(requestJSON, "toolContent"); // Tools' services implement an interface for processing REST requests - ToolRestManager toolRestService = (ToolRestManager) getLamsCoreToolService().findToolService(tool); + ToolRestManager toolRestService = (ToolRestManager) lamsCoreToolService.findToolService(tool); toolRestService.createRestToolContent(userDTO.getUserID(), toolContentID, toolContentJSON); response.setContentType("application/json;charset=utf-8"); Index: lams_central/src/java/org/lamsfoundation/lams/util/CentralConstants.java =================================================================== diff -u -r62aaf160878735888d077bf28fac3c1989bb8fbd -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/util/CentralConstants.java (.../CentralConstants.java) (revision 62aaf160878735888d077bf28fac3c1989bb8fbd) +++ lams_central/src/java/org/lamsfoundation/lams/util/CentralConstants.java (.../CentralConstants.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -152,6 +152,8 @@ public static final String MONITORING_SERVICE_BEAN_NAME = "monitoringService"; public static final String CENTRAL_MESSAGE_SERVICE_BEAN_NAME = "centralMessageService"; + + public static final String TOOL_SERVICE_BEAN_NAME = "lamsToolService"; public static final String ATTR_NODE = "node"; Index: lams_central/src/java/org/lamsfoundation/lams/web/ForgotPasswordServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/ForgotPasswordServlet.java (.../ForgotPasswordServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/web/ForgotPasswordServlet.java (.../ForgotPasswordServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -7,6 +7,7 @@ import javax.mail.MessagingException; import javax.mail.internet.AddressException; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -24,8 +25,8 @@ import org.lamsfoundation.lams.util.Emailer; import org.lamsfoundation.lams.util.FileUtilException; import org.lamsfoundation.lams.util.MessageService; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * Servlet to handle forgot password requests @@ -34,14 +35,15 @@ * new password * * @author lfoxton - * - * - * */ public class ForgotPasswordServlet extends HttpServlet { private static final long serialVersionUID = -4833236166181290760L; - private static Logger log = Logger.getLogger(ForgotPasswordServlet.class); + + @Autowired + protected MessageService centralMessageService; + @Autowired + protected IUserManagementService userManagementService; // states public static String SMTP_SERVER_NOT_SET = "error.support.email.not.set"; @@ -59,6 +61,16 @@ private static String STATE = "&state="; private static String LANGUAGE_KEY = "&languageKey="; private static String EMAIL_SENT = "&emailSent="; + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -118,30 +130,29 @@ if ((SMPTServer == null) || SMPTServer.equals("") || (supportEmail == null) || supportEmail.equals("")) { // Validate SMTP not set up languageKey = ForgotPasswordServlet.SMTP_SERVER_NOT_SET; + } else { - WebApplicationContext ctx = WebApplicationContextUtils - .getRequiredWebApplicationContext(this.getServletContext()); - IUserManagementService userService = (IUserManagementService) ctx.getBean("userManagementService"); - MessageService messageService = (MessageService) ctx.getBean("centralMessageService"); - // get the user by email or login if (!findByEmail) { - if (userService.getUserByLogin(param) != null) { - user = userService.getUserByLogin(param); + if (userManagementService.getUserByLogin(param) != null) { + user = userManagementService.getUserByLogin(param); } else { // validate user is not found languageKey = ForgotPasswordServlet.USER_NOT_FOUND; err = true; } + } else { try { - List users = userService.getAllUsersWithEmail(param); + List users = userManagementService.getAllUsersWithEmail(param); if (users.size() == 1) { user = users.get(0); + } else if (users.size() == 0) { // validate no user with email found languageKey = ForgotPasswordServlet.EMAIL_NOT_FOUND; err = true; + } else { // validate multiple users with email found languageKey = ForgotPasswordServlet.INTERNAL_ERROR; @@ -166,15 +177,15 @@ fp.setRequestDate(new Date()); fp.setUserId(user.getUserId()); fp.setRequestKey(key); - userService.save(fp); + userManagementService.save(fp); // Constructing the body of the email - String body = messageService.getMessage("forgot.password.email.body") + "\n\n" + String body = centralMessageService.getMessage("forgot.password.email.body") + "\n\n" + Configuration.get("ServerURL") + "forgotPasswordChange.jsp?key=" + key; // send the email try { - Emailer.sendFromSupportEmail(messageService.getMessage("forgot.password.email.subject"), + Emailer.sendFromSupportEmail(centralMessageService.getMessage("forgot.password.email.subject"), user.getEmail(), body, isHtmlFormat); languageKey = ForgotPasswordServlet.SUCCESS_REQUEST_EMAIL; success = 1; @@ -213,7 +224,6 @@ } response.sendRedirect(redirectStr); - } /** @@ -232,12 +242,8 @@ return; } - WebApplicationContext ctx = WebApplicationContextUtils - .getRequiredWebApplicationContext(this.getServletContext()); - IUserManagementService userService = (IUserManagementService) ctx.getBean("userManagementService"); + ForgotPasswordRequest fp = userManagementService.getForgotPasswordRequest(key); - ForgotPasswordRequest fp = userService.getForgotPasswordRequest(key); - if (fp == null) { response.sendRedirect( Configuration.get("ServerURL") + "forgotPasswordProc.jsp?" + ForgotPasswordServlet.STATE + 0 @@ -250,17 +256,17 @@ long nowLong = now.getTime(); if (nowLong < cutoffTime) { - User user = (User) userService.findById(User.class, fp.getUserId()); - userService.updatePassword(user.getLogin(), newPassword); - userService.logPasswordChanged(user, user); + User user = (User) userManagementService.findById(User.class, fp.getUserId()); + userManagementService.updatePassword(user.getLogin(), newPassword); + userManagementService.logPasswordChanged(user, user); languageKey = ForgotPasswordServlet.SUCCESS_CHANGE_PASS; success = 1; } else { // validate password request expired languageKey = ForgotPasswordServlet.PASSWORD_REQUEST_EXPIRED; } - userService.delete(fp); + userManagementService.delete(fp); response.sendRedirect(Configuration.get("ServerURL") + "forgotPasswordProc.jsp?" + ForgotPasswordServlet.STATE + success + ForgotPasswordServlet.LANGUAGE_KEY + languageKey); Index: lams_central/src/java/org/lamsfoundation/lams/web/GradebookServlet.java =================================================================== diff -u -r62aaf160878735888d077bf28fac3c1989bb8fbd -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/GradebookServlet.java (.../GradebookServlet.java) (revision 62aaf160878735888d077bf28fac3c1989bb8fbd) +++ lams_central/src/java/org/lamsfoundation/lams/web/GradebookServlet.java (.../GradebookServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -25,6 +25,7 @@ import java.util.Arrays; import java.util.List; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -47,23 +48,35 @@ import org.lamsfoundation.lams.util.CentralConstants; import org.lamsfoundation.lams.util.Configuration; import org.lamsfoundation.lams.util.ConfigurationKeys; -import org.springframework.web.context.support.WebApplicationContextUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * * @author Marcin Cieslak */ @SuppressWarnings("serial") public class GradebookServlet extends HttpServlet { - private static Logger log = Logger.getLogger(GradebookServlet.class); - private static IntegrationService integrationService = null; - private static IUserManagementService userManagementService; + @Autowired + private IntegrationService integrationService; + @Autowired + private IUserManagementService userManagementService; private static final String GRADEBOOK_MONITOR_LESSON_URL = "gradebook/gradebookMonitoring.do?lessonID="; private static final String GRADEBOOK_MONITOR_ORGANISATION_URL = "gradebook/gradebookMonitoring/courseMonitor.do?organisationID="; private static final String GRADEBOOK_LEARNER_ORGANISATION_URL = "gradebook/gradebookLearning/courseLearner.do?organisationID="; + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } /** * The doGet method of the servlet.
@@ -81,8 +94,6 @@ */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - getIntegrationService(); - getUserManagementService(); HttpSession hses = request.getSession(true); String username = request.getParameter(LoginRequestDispatcher.PARAM_USER_ID); @@ -116,7 +127,7 @@ // translate external course ID to internal organisation ID and then get the gradebook for it ExtUserUseridMap userMap = integrationService.getExtUserUseridMap(extServer, username); ExtCourseClassMap orgMap = integrationService.getExtCourseClassMap(extServer, userMap, extCourseId, - courseName, getUserManagementService().getRootOrganisation().getOrganisationId().toString(), + courseName, userManagementService.getRootOrganisation().getOrganisationId().toString(), isTeacher, false); Integer organisationId = orgMap.getOrganisation().getOrganisationId(); @@ -170,22 +181,4 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } - - private IntegrationService getIntegrationService() { - if (integrationService == null) { - integrationService = (IntegrationService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("integrationService"); - } - return integrationService; - } - - protected IUserManagementService getUserManagementService() { - if (userManagementService == null) { - userManagementService = (IUserManagementService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()) - .getBean(CentralConstants.USER_MANAGEMENT_SERVICE_BEAN_NAME); - - } - return userManagementService; - } } \ No newline at end of file Index: lams_central/src/java/org/lamsfoundation/lams/web/LAMSConnectorServlet.java =================================================================== diff -u -rc9ee204be2fbc37ed1fd4c7eb8267bc103d98a24 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/LAMSConnectorServlet.java (.../LAMSConnectorServlet.java) (revision c9ee204be2fbc37ed1fd4c7eb8267bc103d98a24) +++ lams_central/src/java/org/lamsfoundation/lams/web/LAMSConnectorServlet.java (.../LAMSConnectorServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -35,7 +36,6 @@ import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; -import org.lamsfoundation.lams.authoring.web.AuthoringConstants; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; import org.lamsfoundation.lams.util.CommonConstants; import org.lamsfoundation.lams.util.Configuration; @@ -45,8 +45,10 @@ import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.web.session.SessionManager; import org.lamsfoundation.lams.web.util.AttributeNames; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.FileCopyUtils; import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; import org.springframework.web.context.support.WebApplicationContextUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -83,7 +85,18 @@ private String realBaseDir; private String lamsContextPath; - private static MessageService messageService; + @Autowired + private MessageService centralMessageService; + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } /** * Initialize the servlet.
@@ -92,10 +105,6 @@ */ @Override public void init() throws ServletException { - WebApplicationContext ctx = WebApplicationContextUtils - .getRequiredWebApplicationContext(this.getServletContext()); - messageService = (MessageService) ctx.getBean("centralMessageService"); - LAMSConnectorServlet.baseDir = getInitParameter("baseDir"); debug = (new Boolean(getInitParameter("debug"))).booleanValue() && log.isDebugEnabled(); @@ -333,7 +342,7 @@ boolean maxFilesizeExceededMessage = FileValidatorUtil.validateFileSize(uplFile.getSize(), true); if (!maxFilesizeExceededMessage) { //assign fileName an error message to be shown on a client side - fileName = messageService.getMessage("errors.maxfilesize", + fileName = centralMessageService.getMessage("errors.maxfilesize", new Object[] { Configuration.getAsInt(ConfigurationKeys.UPLOAD_FILE_LARGE_MAX_SIZE) }); retVal.append("1"); Index: lams_central/src/java/org/lamsfoundation/lams/web/LAMSUploadServlet.java =================================================================== diff -u -rc9ee204be2fbc37ed1fd4c7eb8267bc103d98a24 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/LAMSUploadServlet.java (.../LAMSUploadServlet.java) (revision c9ee204be2fbc37ed1fd4c7eb8267bc103d98a24) +++ lams_central/src/java/org/lamsfoundation/lams/web/LAMSUploadServlet.java (.../LAMSUploadServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -14,6 +14,7 @@ import java.util.List; import java.util.Map; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -29,9 +30,9 @@ import org.lamsfoundation.lams.util.FileValidatorUtil; import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.util.UploadFileUtil; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.FileCopyUtils; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * Servlet to upload files.
@@ -52,13 +53,17 @@ private static final long serialVersionUID = 7839808388592495717L; private static final Logger log = Logger.getLogger(LAMSUploadServlet.class); - private static MessageService messageService; - + @Autowired + private MessageService centralMessageService; + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ @Override - public void init() { - WebApplicationContext ctx = WebApplicationContextUtils - .getRequiredWebApplicationContext(this.getServletContext()); - messageService = (MessageService) ctx.getBean("centralMessageService"); + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); } /** @@ -118,7 +123,7 @@ // validate file size boolean maxFilesizeExceededMessage = FileValidatorUtil.validateFileSize(uplFile.getSize(), true); if (!maxFilesizeExceededMessage) { - fileName = messageService.getMessage("errors.maxfilesize", + fileName = centralMessageService.getMessage("errors.maxfilesize", new Object[] { Configuration.getAsInt(ConfigurationKeys.UPLOAD_FILE_LARGE_MAX_SIZE) }); // validate file extension Index: lams_central/src/java/org/lamsfoundation/lams/web/LamsStartupServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/LamsStartupServlet.java (.../LamsStartupServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/web/LamsStartupServlet.java (.../LamsStartupServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -13,17 +13,11 @@ import org.lamsfoundation.lams.util.ConfigurationKeys; /** + * A servlet that loads at startup to do some maintainence like removing + * temp directories * * @author lfoxton - * - * A servlet that loads at startup to do some maintainence like removing - * temp directories - * - * - * - * */ - public class LamsStartupServlet extends HttpServlet { private static Logger log = Logger.getLogger(LamsStartupServlet.class); Index: lams_central/src/java/org/lamsfoundation/lams/web/LaunchLearnerUrlServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/LaunchLearnerUrlServlet.java (.../LaunchLearnerUrlServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/web/LaunchLearnerUrlServlet.java (.../LaunchLearnerUrlServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -25,6 +25,7 @@ import java.io.IOException; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -38,28 +39,27 @@ import org.lamsfoundation.lams.util.ConfigurationKeys; import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.web.util.AttributeNames; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * Sends redirect to lams learner. Format: launchlearner.do?lessonID= - * - * - * */ public class LaunchLearnerUrlServlet extends HttpServlet { private static Logger log = Logger.getLogger(LaunchLearnerUrlServlet.class); - private static ILessonService lessonService; - - private ILessonService getLessonService() { - if (lessonService == null) { - WebApplicationContext ctx = WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()); - lessonService = (ILessonService) ctx.getBean("lessonService"); - } - return lessonService; + @Autowired + private ILessonService lessonService; + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); } @Override @@ -90,7 +90,7 @@ return; } - Lesson lesson = lessonId != null ? getLessonService().getLesson(lessonId) : null; + Lesson lesson = lessonId != null ? lessonService.getLesson(lessonId) : null; if (lesson != null) { // return displayMessage(mapping, req, "message.lesson.not.started.cannot.participate"); } Index: lams_central/src/java/org/lamsfoundation/lams/web/LessonOrderServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/LessonOrderServlet.java (.../LessonOrderServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/web/LessonOrderServlet.java (.../LessonOrderServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -29,6 +29,7 @@ import java.util.Iterator; import java.util.List; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -41,8 +42,8 @@ import org.lamsfoundation.lams.usermanagement.UserOrganisationRole; import org.lamsfoundation.lams.usermanagement.service.UserManagementService; import org.lamsfoundation.lams.util.WebUtil; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * Used by main.jsp to persist the ordering of lessonIds when lessons are @@ -52,8 +53,20 @@ * @author jliew */ public class LessonOrderServlet extends HttpServlet { - private static Logger log = Logger.getLogger(LessonOrderServlet.class); + + @Autowired + private UserManagementService userManagementService; + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -63,16 +76,13 @@ Integer orgId = WebUtil.readIntParam(request, "orgId", false); String ids = request.getParameter("ids"); - WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); - UserManagementService service = (UserManagementService) ctx.getBean("userManagementService"); - if (orgId != null && ids != null) { - Organisation org = (Organisation) service.findById(Organisation.class, orgId); + Organisation org = (Organisation) userManagementService.findById(Organisation.class, orgId); if (org != null) { // make sure user has permission to sort org lessons boolean allowSorting = false; - List userOrganisationRoles = service.getUserOrganisationRoles(orgId, + List userOrganisationRoles = userManagementService.getUserOrganisationRoles(orgId, request.getRemoteUser()); for (UserOrganisationRole userOrganisationRole : userOrganisationRoles) { Integer roleId = userOrganisationRole.getRole().getRoleId(); @@ -89,7 +99,7 @@ // make sure we record lesson ids that belong to this org List idList = Arrays.asList(ids.split(",")); - List lessons = service.findByProperty(Lesson.class, "organisation", org); + List lessons = userManagementService.findByProperty(Lesson.class, "organisation", org); for (String id : idList) { try { Long l = new Long(Long.parseLong(id)); @@ -106,7 +116,7 @@ String oldIds = org.getOrderedLessonIds(); String updatedIds = mergeLessonIds((oldIds != null ? oldIds : ""), ids); org.setOrderedLessonIds(updatedIds); - service.save(org); + userManagementService.save(org); } } Index: lams_central/src/java/org/lamsfoundation/lams/web/LoginRequestLtiServlet.java =================================================================== diff -u -r62aaf160878735888d077bf28fac3c1989bb8fbd -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/LoginRequestLtiServlet.java (.../LoginRequestLtiServlet.java) (revision 62aaf160878735888d077bf28fac3c1989bb8fbd) +++ lams_central/src/java/org/lamsfoundation/lams/web/LoginRequestLtiServlet.java (.../LoginRequestLtiServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -25,6 +25,7 @@ import java.net.URLEncoder; import java.util.Enumeration; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -40,15 +41,15 @@ import org.imsglobal.lti.launch.LtiVerificationException; import org.imsglobal.lti.launch.LtiVerificationResult; import org.imsglobal.lti.launch.LtiVerifier; -import org.lamsfoundation.lams.integration.ExtServerLessonMap; import org.lamsfoundation.lams.integration.ExtServer; +import org.lamsfoundation.lams.integration.ExtServerLessonMap; import org.lamsfoundation.lams.integration.service.IntegrationService; import org.lamsfoundation.lams.integration.util.LoginRequestDispatcher; import org.lamsfoundation.lams.integration.util.LtiUtils; -import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; import org.lamsfoundation.lams.util.CentralConstants; import org.lamsfoundation.lams.util.HashUtil; -import org.springframework.web.context.support.WebApplicationContextUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * The LoginRequestLtiServlet handles login request by LTI tool consumers. This servlet checks for the correctly signed by OAuth parameters, @@ -58,21 +59,26 @@ */ @SuppressWarnings("serial") public class LoginRequestLtiServlet extends HttpServlet { - private static Logger log = Logger.getLogger(LoginRequestLtiServlet.class); + + @Autowired + private IntegrationService integrationService = null; - private static IntegrationService integrationService = null; - - private static IUserManagementService userManagementService = null; - private final String DEFAULT_FIRST_NAME = "John"; - private final String DEFAULT_LAST_NAME = "Doe"; + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - initServices(); - String extUsername = request.getParameter(BasicLTIConstants.USER_ID); String roles = request.getParameter(BasicLTIConstants.ROLES); // implicit login params @@ -221,16 +227,4 @@ String country = split.length > 1 ? split[1] : "AU"; return country; } - - private void initServices() { - if (integrationService == null) { - integrationService = (IntegrationService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("integrationService"); - } - - if (userManagementService == null) { - userManagementService = (IUserManagementService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("userManagementService"); - } - } } Index: lams_central/src/java/org/lamsfoundation/lams/web/LoginRequestServlet.java =================================================================== diff -u -r62aaf160878735888d077bf28fac3c1989bb8fbd -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/LoginRequestServlet.java (.../LoginRequestServlet.java) (revision 62aaf160878735888d077bf28fac3c1989bb8fbd) +++ lams_central/src/java/org/lamsfoundation/lams/web/LoginRequestServlet.java (.../LoginRequestServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -23,6 +23,7 @@ import java.io.IOException; import java.net.URLEncoder; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -46,6 +47,8 @@ import org.lamsfoundation.lams.util.CentralConstants; import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.web.util.AttributeNames; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; import org.springframework.web.context.support.WebApplicationContextUtils; /** @@ -56,10 +59,20 @@ */ @SuppressWarnings("serial") public class LoginRequestServlet extends HttpServlet { - private static Logger log = Logger.getLogger(LoginRequestServlet.class); - private static IntegrationService integrationService = null; + @Autowired + private IntegrationService integrationService; + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } /** * The doGet method of the servlet.
@@ -111,14 +124,14 @@ } } - ExtServer extServer = getIntegrationService().getExtServer(serverId); + ExtServer extServer = integrationService.getExtServer(serverId); boolean prefix = (usePrefix == null) ? true : Boolean.parseBoolean(usePrefix); try { ExtUserUseridMap userMap = null; if ((firstName == null) && (lastName == null)) { - userMap = getIntegrationService().getExtUserUseridMap(extServer, extUsername, prefix); + userMap = integrationService.getExtUserUseridMap(extServer, extUsername, prefix); } else { - userMap = getIntegrationService().getImplicitExtUserUseridMap(extServer, extUsername, firstName, + userMap = integrationService.getImplicitExtUserUseridMap(extServer, extUsername, firstName, lastName, locale, country, email, prefix, isUpdateUserDetails); } @@ -144,7 +157,7 @@ if (extCourseId != null) { // check if organisation, ExtCourseClassMap and user roles exist and up-to-date, and if not update them - getIntegrationService().getExtCourseClassMap(extServer, userMap, extCourseId, courseName, method, + integrationService.getExtCourseClassMap(extServer, userMap, extCourseId, courseName, method, prefix); } @@ -207,12 +220,4 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } - - private IntegrationService getIntegrationService() { - if (integrationService == null) { - integrationService = (IntegrationService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("integrationService"); - } - return integrationService; - } } Index: lams_central/src/java/org/lamsfoundation/lams/web/OrganisationGroupServlet.java =================================================================== diff -u -r62aaf160878735888d077bf28fac3c1989bb8fbd -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/OrganisationGroupServlet.java (.../OrganisationGroupServlet.java) (revision 62aaf160878735888d077bf28fac3c1989bb8fbd) +++ lams_central/src/java/org/lamsfoundation/lams/web/OrganisationGroupServlet.java (.../OrganisationGroupServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -27,6 +27,7 @@ import java.util.Set; import java.util.TreeMap; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -50,27 +51,37 @@ import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; import org.lamsfoundation.lams.util.CentralConstants; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; public class OrganisationGroupServlet extends HttpServlet { - private static final Logger log = Logger.getLogger(OrganisationGroupServlet.class); - private static IntegrationService integrationService; - private static IUserManagementService userManagementService; + @Autowired + private IntegrationService integrationService; + @Autowired + private IUserManagementService userManagementService; private static final String METHOD_ADD_GROUPING = "addGrouping"; private static final String METHOD_REMOVE_GROUPING = "removeGrouping"; private static final String METHOD_ADD_GROUP = "addGroup"; private static final String METHOD_REMOVE_GROUP = "removeGroup"; private static final String METHOD_ADD_LEARNERS = "addLearners"; private static final String METHOD_REMOVE_LEARNERS = "removeLearners"; - private static final String PARAM_GROUPING_NAME = "groupingName"; private static final String PARAM_GROUP_NAME = "groupName"; + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } + + @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String serverId = request.getParameter(CentralConstants.PARAM_SERVER_ID); String datetime = request.getParameter(CentralConstants.PARAM_DATE_TIME); @@ -88,68 +99,67 @@ User user = null; Organisation organisation = null; - ExtServer extServer = getService().getExtServer(serverId); + ExtServer extServer = integrationService.getExtServer(serverId); try { // authenticate the request Authenticator.authenticate(extServer, datetime, username, hashValue); // get local user and organisation - ExtUserUseridMap userMap = OrganisationGroupServlet.integrationService.getExtUserUseridMap(extServer, - username); - ExtCourseClassMap orgMap = OrganisationGroupServlet.integrationService.getExtCourseClassMap(extServer, - userMap, courseId, null, LoginRequestDispatcher.METHOD_MONITOR); + ExtUserUseridMap userMap = integrationService.getExtUserUseridMap(extServer, username); + ExtCourseClassMap orgMap = integrationService.getExtCourseClassMap(extServer, userMap, courseId, null, + LoginRequestDispatcher.METHOD_MONITOR); user = userMap.getUser(); organisation = orgMap.getOrganisation(); // check if user is allowed to modify course groups for the given organisation - boolean isGroupSuperuser = getUserManagementService().isUserInRole(user.getUserId(), + boolean isGroupSuperuser = userManagementService.isUserInRole(user.getUserId(), organisation.getOrganisationId(), Role.MONITOR) - || getUserManagementService().isUserInRole(user.getUserId(), organisation.getOrganisationId(), + || userManagementService.isUserInRole(user.getUserId(), organisation.getOrganisationId(), Role.AUTHOR); if (!isGroupSuperuser) { - OrganisationGroupServlet.log.error("User " + user.getUserId() - + " may not perform group actions for course " + organisation.getOrganisationId()); + log.error("User " + user.getUserId() + " may not perform group actions for course " + + organisation.getOrganisationId()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Course group action failed - user may not perform group actions"); return; } } catch (AuthenticationException e) { - OrganisationGroupServlet.log.error(e); + log.error(e); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Course group action failed - authentication error"); return; } catch (UserInfoFetchException e) { - OrganisationGroupServlet.log.error(e); + log.error(e); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Course group action failed - user does not exist"); return; } catch (UserInfoValidationException e) { - OrganisationGroupServlet.log.error(e); + log.error(e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Course group action failed." + e.getMessage()); return; } try { String method = request.getParameter(CentralConstants.PARAM_METHOD); - if (OrganisationGroupServlet.METHOD_ADD_GROUPING.equals(method)) { + if (METHOD_ADD_GROUPING.equals(method)) { addGrouping(request, organisation); - } else if (OrganisationGroupServlet.METHOD_REMOVE_GROUPING.equals(method)) { + } else if (METHOD_REMOVE_GROUPING.equals(method)) { removeGrouping(request, organisation.getOrganisationId()); - } else if (OrganisationGroupServlet.METHOD_ADD_GROUP.equals(method)) { + } else if (METHOD_ADD_GROUP.equals(method)) { addGroup(request, organisation.getOrganisationId()); - } else if (OrganisationGroupServlet.METHOD_REMOVE_GROUP.equals(method)) { + } else if (METHOD_REMOVE_GROUP.equals(method)) { removeGroup(request, organisation.getOrganisationId()); - } else if (OrganisationGroupServlet.METHOD_ADD_LEARNERS.equals(method)) { + } else if (METHOD_ADD_LEARNERS.equals(method)) { addLearners(request, extServer, organisation.getOrganisationId()); - } else if (OrganisationGroupServlet.METHOD_REMOVE_LEARNERS.equals(method)) { + } else if (METHOD_REMOVE_LEARNERS.equals(method)) { removeLearners(request, extServer, organisation.getOrganisationId()); } } catch (ServletException e) { - OrganisationGroupServlet.log.error(e); + log.error(e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Course group action failed: " + e.getMessage()); return; } catch (Exception e) { - OrganisationGroupServlet.log.error(e); + log.error(e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Course group action failed: internal error"); return; @@ -162,7 +172,7 @@ } private void addGrouping(HttpServletRequest request, Organisation organisation) throws ServletException { - String groupingName = request.getParameter(OrganisationGroupServlet.PARAM_GROUPING_NAME); + String groupingName = request.getParameter(PARAM_GROUPING_NAME); if (StringUtils.isBlank(groupingName)) { throw new ServletException("Missing \"" + CentralConstants.ATTR_NAME + "\" parameter"); } @@ -175,23 +185,23 @@ } grouping = new OrganisationGrouping(organisation.getOrganisationId(), groupingName); - getUserManagementService().saveOrganisationGrouping(grouping, null); + userManagementService.saveOrganisationGrouping(grouping, null); Long groupingId = grouping.getGroupingId(); if (groupingId == null) { throw new ServletException("Grouping could not be created"); } - if (OrganisationGroupServlet.log.isDebugEnabled()) { - OrganisationGroupServlet.log.debug("Created course grouping \"" + groupingName + "\" with ID " + groupingId + if (log.isDebugEnabled()) { + log.debug("Created course grouping \"" + groupingName + "\" with ID " + groupingId + " in organisation with ID " + organisation.getOrganisationId()); } } private void removeGrouping(HttpServletRequest request, Integer organisationId) throws ServletException { - String groupingName = request.getParameter(OrganisationGroupServlet.PARAM_GROUPING_NAME); + String groupingName = request.getParameter(PARAM_GROUPING_NAME); if (StringUtils.isBlank(groupingName)) { - throw new ServletException("Missing \"" + OrganisationGroupServlet.PARAM_GROUPING_NAME + "\" parameter"); + throw new ServletException("Missing \"" + PARAM_GROUPING_NAME + "\" parameter"); } OrganisationGrouping grouping = findGrouping(organisationId, groupingName); @@ -200,22 +210,22 @@ return; } - getUserManagementService().delete(grouping); + userManagementService.delete(grouping); - if (OrganisationGroupServlet.log.isDebugEnabled()) { - OrganisationGroupServlet.log.debug( + if (log.isDebugEnabled()) { + log.debug( "Deleted course grouping with ID " + groupingName + " from organisation with ID " + organisationId); } } private void addGroup(HttpServletRequest request, Integer organisationId) throws ServletException { - String groupingName = request.getParameter(OrganisationGroupServlet.PARAM_GROUPING_NAME); + String groupingName = request.getParameter(PARAM_GROUPING_NAME); if (StringUtils.isBlank(groupingName)) { - throw new ServletException("Missing \"" + OrganisationGroupServlet.PARAM_GROUPING_NAME + "\" parameter"); + throw new ServletException("Missing \"" + PARAM_GROUPING_NAME + "\" parameter"); } - String groupName = request.getParameter(OrganisationGroupServlet.PARAM_GROUP_NAME); + String groupName = request.getParameter(PARAM_GROUP_NAME); if (StringUtils.isBlank(groupName)) { - throw new ServletException("Missing \"" + OrganisationGroupServlet.PARAM_GROUP_NAME + "\" parameter"); + throw new ServletException("Missing \"" + PARAM_GROUP_NAME + "\" parameter"); } OrganisationGrouping grouping = findGrouping(organisationId, groupingName); @@ -237,26 +247,26 @@ newGroup.setName(groupName); groups.add(newGroup); - getUserManagementService().saveOrganisationGrouping(grouping, groups); + userManagementService.saveOrganisationGrouping(grouping, groups); Long groupId = newGroup.getGroupId(); if (groupId == null) { throw new ServletException("Group could not be created"); } - if (OrganisationGroupServlet.log.isDebugEnabled()) { - OrganisationGroupServlet.log.debug("Created course group \"" + groupName + "\" with ID " + groupId - + " in organisation with ID " + organisationId); + if (log.isDebugEnabled()) { + log.debug("Created course group \"" + groupName + "\" with ID " + groupId + " in organisation with ID " + + organisationId); } } private void removeGroup(HttpServletRequest request, Integer organisationId) throws ServletException { - String groupingName = request.getParameter(OrganisationGroupServlet.PARAM_GROUPING_NAME); + String groupingName = request.getParameter(PARAM_GROUPING_NAME); if (StringUtils.isBlank(groupingName)) { - throw new ServletException("Missing \"" + OrganisationGroupServlet.PARAM_GROUPING_NAME + "\" parameter"); + throw new ServletException("Missing \"" + PARAM_GROUPING_NAME + "\" parameter"); } - String groupName = request.getParameter(OrganisationGroupServlet.PARAM_GROUP_NAME); + String groupName = request.getParameter(PARAM_GROUP_NAME); if (StringUtils.isBlank(groupName)) { - throw new ServletException("Missing \"" + OrganisationGroupServlet.PARAM_GROUP_NAME + "\" parameter"); + throw new ServletException("Missing \"" + PARAM_GROUP_NAME + "\" parameter"); } OrganisationGrouping grouping = findGrouping(organisationId, groupingName); if (grouping == null) { @@ -271,23 +281,23 @@ Set groups = new HashSet(grouping.getGroups()); groups.remove(group); - getUserManagementService().saveOrganisationGrouping(grouping, groups); + userManagementService.saveOrganisationGrouping(grouping, groups); - if (OrganisationGroupServlet.log.isDebugEnabled()) { - OrganisationGroupServlet.log.debug("Deleted course group with ID " + group.getGroupId() - + " from organisation with ID " + organisationId); + if (log.isDebugEnabled()) { + log.debug("Deleted course group with ID " + group.getGroupId() + " from organisation with ID " + + organisationId); } } private void addLearners(HttpServletRequest request, ExtServer extServer, Integer organisationId) throws ServletException { - String groupingName = request.getParameter(OrganisationGroupServlet.PARAM_GROUPING_NAME); + String groupingName = request.getParameter(PARAM_GROUPING_NAME); if (StringUtils.isBlank(groupingName)) { - throw new ServletException("Missing \"" + OrganisationGroupServlet.PARAM_GROUPING_NAME + "\" parameter"); + throw new ServletException("Missing \"" + PARAM_GROUPING_NAME + "\" parameter"); } - String groupName = request.getParameter(OrganisationGroupServlet.PARAM_GROUP_NAME); + String groupName = request.getParameter(PARAM_GROUP_NAME); if (StringUtils.isBlank(groupName)) { - throw new ServletException("Missing \"" + OrganisationGroupServlet.PARAM_GROUP_NAME + "\" parameter"); + throw new ServletException("Missing \"" + PARAM_GROUP_NAME + "\" parameter"); } String learnerIds = request.getParameter(CentralConstants.PARAM_LEARNER_IDS); if (StringUtils.isBlank(learnerIds)) { @@ -310,8 +320,7 @@ for (String learnerLogin : learnerLoginArray) { User learner = null; try { - ExtUserUseridMap userMap = OrganisationGroupServlet.integrationService.getExtUserUseridMap(extServer, - learnerLogin); + ExtUserUseridMap userMap = integrationService.getExtUserUseridMap(extServer, learnerLogin); learner = userMap.getUser(); } catch (UserInfoFetchException e) { throw new ServletException("Learner with ID \"" + learnerLogin + "\" does not exist"); @@ -327,25 +336,25 @@ } if (learnersAdded) { - getUserManagementService().saveOrganisationGrouping(grouping, grouping.getGroups()); + userManagementService.saveOrganisationGrouping(grouping, grouping.getGroups()); - if (OrganisationGroupServlet.log.isDebugEnabled()) { - OrganisationGroupServlet.log.debug("Added learners " + addedLearnerLogins + " to course group with ID " - + group.getGroupId() + " in organisation with ID " + organisationId); + if (log.isDebugEnabled()) { + log.debug("Added learners " + addedLearnerLogins + " to course group with ID " + group.getGroupId() + + " in organisation with ID " + organisationId); } } return; } private void removeLearners(HttpServletRequest request, ExtServer extServer, Integer organisationId) throws ServletException { - String groupingName = request.getParameter(OrganisationGroupServlet.PARAM_GROUPING_NAME); + String groupingName = request.getParameter(PARAM_GROUPING_NAME); if (StringUtils.isBlank(groupingName)) { - throw new ServletException("Missing \"" + OrganisationGroupServlet.PARAM_GROUPING_NAME + "\" parameter"); + throw new ServletException("Missing \"" + PARAM_GROUPING_NAME + "\" parameter"); } - String groupName = request.getParameter(OrganisationGroupServlet.PARAM_GROUP_NAME); + String groupName = request.getParameter(PARAM_GROUP_NAME); if (StringUtils.isBlank(groupName)) { - throw new ServletException("Missing \"" + OrganisationGroupServlet.PARAM_GROUP_NAME + "\" parameter"); + throw new ServletException("Missing \"" + PARAM_GROUP_NAME + "\" parameter"); } String learnerIds = request.getParameter(CentralConstants.PARAM_LEARNER_IDS); if (StringUtils.isBlank(learnerIds)) { @@ -367,8 +376,7 @@ for (String learnerLogin : learnerLoginArray) { User learner = null; try { - ExtUserUseridMap userMap = OrganisationGroupServlet.integrationService.getExtUserUseridMap(extServer, - learnerLogin); + ExtUserUseridMap userMap = integrationService.getExtUserUseridMap(extServer, learnerLogin); learner = userMap.getUser(); } catch (UserInfoFetchException e) { // if user does not exist, ignore @@ -387,10 +395,10 @@ } if (learnersRemoved) { - getUserManagementService().saveOrganisationGrouping(grouping, grouping.getGroups()); - if (OrganisationGroupServlet.log.isDebugEnabled()) { - OrganisationGroupServlet.log.debug("Removed learners " + removedLearnerLogins + " from group with ID " - + group.getGroupId() + " in organisation with ID " + organisationId); + userManagementService.saveOrganisationGrouping(grouping, grouping.getGroups()); + if (log.isDebugEnabled()) { + log.debug("Removed learners " + removedLearnerLogins + " from group with ID " + group.getGroupId() + + " in organisation with ID " + organisationId); } } return; @@ -401,7 +409,7 @@ Map queryProperties = new TreeMap(); queryProperties.put("organisationId", organisationId); queryProperties.put("name", groupingName); - List result = getUserManagementService().findByProperties(OrganisationGrouping.class, + List result = userManagementService.findByProperties(OrganisationGrouping.class, queryProperties); return (result == null) || result.isEmpty() ? null : result.get(0); } @@ -411,26 +419,8 @@ Map queryProperties = new TreeMap(); queryProperties.put("groupingId", groupingId); queryProperties.put("name", groupName); - List result = getUserManagementService().findByProperties(OrganisationGroup.class, + List result = userManagementService.findByProperties(OrganisationGroup.class, queryProperties); return (result == null) || result.isEmpty() ? null : result.get(0); } - - private IntegrationService getService() { - if (OrganisationGroupServlet.integrationService == null) { - OrganisationGroupServlet.integrationService = (IntegrationService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("integrationService"); - } - return OrganisationGroupServlet.integrationService; - } - - private IUserManagementService getUserManagementService() { - if (OrganisationGroupServlet.userManagementService == null) { - WebApplicationContext ctx = WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()); - OrganisationGroupServlet.userManagementService = (IUserManagementService) ctx - .getBean("userManagementService"); - } - return OrganisationGroupServlet.userManagementService; - } } \ No newline at end of file Index: lams_central/src/java/org/lamsfoundation/lams/web/RatingServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/RatingServlet.java (.../RatingServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/web/RatingServlet.java (.../RatingServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -29,6 +29,7 @@ import java.util.Locale; import java.util.Map; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -45,8 +46,8 @@ import org.lamsfoundation.lams.util.WebUtil; 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; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -55,20 +56,25 @@ * Stores rating. * * @author Andrey Balan - * - * - * */ public class RatingServlet extends HttpServlet { - private static Logger log = Logger.getLogger(RatingServlet.class); - private static RatingService ratingService; + @Autowired + private RatingService ratingService; + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); - getRatingService(); String objectId = WebUtil.readStrParam(request, "idBox"); Long ratingCriteriaId = Long.parseLong(objectId.split("-")[0]); @@ -161,13 +167,4 @@ throws ServletException, IOException { doGet(request, response); } - - private RatingService getRatingService() { - if (ratingService == null) { - WebApplicationContext ctx = WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()); - ratingService = (RatingService) ctx.getBean("ratingService"); - } - return ratingService; - } } Index: lams_central/src/java/org/lamsfoundation/lams/web/RuntimeStatsServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/RuntimeStatsServlet.java (.../RuntimeStatsServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/web/RuntimeStatsServlet.java (.../RuntimeStatsServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -42,25 +42,23 @@ import org.lamsfoundation.lams.web.session.SessionManager; public class RuntimeStatsServlet extends HttpServlet { - private static final long serialVersionUID = 6834774025623257743L; - private static Logger log = Logger.getLogger(RuntimeStatsServlet.class); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isLongStats = WebUtil.readBooleanParam(request, "long", false); String stats = null; if (isLongStats) { - if (RuntimeStatsServlet.log.isDebugEnabled()) { - RuntimeStatsServlet.log.debug("Getting long runtime stats"); + if (log.isDebugEnabled()) { + log.debug("Getting long runtime stats"); } - stats = RuntimeStatsServlet.getLongStats(); + stats = getLongStats(); } else { - if (RuntimeStatsServlet.log.isDebugEnabled()) { - RuntimeStatsServlet.log.debug("Getting short runtime stats"); + if (log.isDebugEnabled()) { + log.debug("Getting short runtime stats"); } - stats = RuntimeStatsServlet.getShortStats(); + stats = getShortStats(); } if (stats != null) { @@ -111,7 +109,7 @@ resp.append("Current Sessions : ").append(SessionManager.getSessionCount()).append("\n"); resp.append("Time of Request : ").append(date); } catch (Exception e) { - RuntimeStatsServlet.log.error("Error while getting short runtime stats", e); + log.error("Error while getting short runtime stats", e); } return resp.toString(); @@ -164,7 +162,7 @@ resp.append("Connections [in use/active/total]: ").append(inUseConnections).append("/") .append(activeConnections).append("/").append(availConnections).append("\n"); } catch (Exception e) { - RuntimeStatsServlet.log.error("Error while getting long runtime stats", e); + log.error("Error while getting long runtime stats", e); } return resp.toString(); Index: lams_central/src/java/org/lamsfoundation/lams/web/tag/HelpTag.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/web/tag/HelpTag.java (.../HelpTag.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/web/tag/HelpTag.java (.../HelpTag.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -34,7 +34,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; -import org.lamsfoundation.lams.authoring.web.AuthoringConstants; import org.lamsfoundation.lams.tool.IToolVO; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.util.CentralConstants; @@ -95,7 +94,7 @@ // retrieve help URL for tool ILamsToolService toolService = (ILamsToolService) getContext() - .getBean(AuthoringConstants.TOOL_SERVICE_BEAN_NAME); + .getBean(CentralConstants.TOOL_SERVICE_BEAN_NAME); IToolVO tool = toolService.getToolBySignature(toolSignature); String fullURL = HelpUtil.constructToolURL(tool.getHelpUrl(), toolSignature, module, languageCode); Index: lams_central/src/java/org/lamsfoundation/lams/webservice/GetRecordingServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/webservice/GetRecordingServlet.java (.../GetRecordingServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/webservice/GetRecordingServlet.java (.../GetRecordingServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -37,12 +37,8 @@ /** * @author pgeorges - * - * - * */ public class GetRecordingServlet extends HttpServlet { - private static Logger logger = Logger.getLogger(GetRecordingServlet.class); @Override Index: lams_central/src/java/org/lamsfoundation/lams/webservice/GetServerTimeServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/webservice/GetServerTimeServlet.java (.../GetServerTimeServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/webservice/GetServerTimeServlet.java (.../GetServerTimeServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -35,17 +35,12 @@ /** * @author Andrey Balan - * - * - * */ public class GetServerTimeServlet extends HttpServlet { - private static Logger logger = Logger.getLogger(GetServerTimeServlet.class); @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { - try { long currentTime = (new Date()).getTime(); Index: lams_central/src/java/org/lamsfoundation/lams/webservice/LearningDesignSVGServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/webservice/LearningDesignSVGServlet.java (.../LearningDesignSVGServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/webservice/LearningDesignSVGServlet.java (.../LearningDesignSVGServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -27,6 +27,7 @@ import java.io.IOException; import java.io.OutputStream; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -45,20 +46,21 @@ import org.lamsfoundation.lams.util.ConfigurationKeys; import org.lamsfoundation.lams.util.FileUtil; import org.lamsfoundation.lams.util.WebUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; import org.springframework.web.context.support.WebApplicationContextUtils; public class LearningDesignSVGServlet extends HttpServlet { - private static final long serialVersionUID = -1918180868204870617L; - private static Logger log = Logger.getLogger(LearningDesignSVGServlet.class); - private static IntegrationService integrationService = null; + @Autowired + private IntegrationService integrationService; + @Autowired + private ILearningDesignService learningDesignService; + @Autowired + private ILessonService lessonService; - private ILearningDesignService learningDesignService = null; - - private ILessonService lessonService = null; - @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { @@ -129,15 +131,13 @@ doGet(request, response); } + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ @Override - public void init() throws ServletException { - integrationService = (IntegrationService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("integrationService"); - - learningDesignService = (ILearningDesignService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("learningDesignService"); - - lessonService = (ILessonService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("lessonService"); + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); } } \ No newline at end of file Fisheye: Tag 33829c670fd8c90447d62ea3300498a103905e7a refers to a dead (removed) revision in file `lams_central/src/java/org/lamsfoundation/lams/webservice/RegisterAction.java'. Fisheye: No comparison available. Pass `N' to diff? Index: lams_central/src/java/org/lamsfoundation/lams/webservice/RegisterServlet.java =================================================================== diff -u --- lams_central/src/java/org/lamsfoundation/lams/webservice/RegisterServlet.java (revision 0) +++ lams_central/src/java/org/lamsfoundation/lams/webservice/RegisterServlet.java (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -0,0 +1,595 @@ +/**************************************************************** + * 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 + * **************************************************************** + */ + +package org.lamsfoundation.lams.webservice; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.lamsfoundation.lams.events.IEventNotificationService; +import org.lamsfoundation.lams.integration.ExtCourseClassMap; +import org.lamsfoundation.lams.integration.ExtServer; +import org.lamsfoundation.lams.integration.ExtUserUseridMap; +import org.lamsfoundation.lams.integration.UserInfoFetchException; +import org.lamsfoundation.lams.integration.security.Authenticator; +import org.lamsfoundation.lams.integration.security.RandomPasswordGenerator; +import org.lamsfoundation.lams.integration.service.IntegrationService; +import org.lamsfoundation.lams.learning.service.ILearnerService; +import org.lamsfoundation.lams.learningdesign.Group; +import org.lamsfoundation.lams.learningdesign.GroupUser; +import org.lamsfoundation.lams.learningdesign.dao.IGroupUserDAO; +import org.lamsfoundation.lams.lesson.LearnerProgress; +import org.lamsfoundation.lams.lesson.Lesson; +import org.lamsfoundation.lams.lesson.LessonClass; +import org.lamsfoundation.lams.lesson.dao.ILearnerProgressDAO; +import org.lamsfoundation.lams.lesson.service.ILessonService; +import org.lamsfoundation.lams.usermanagement.Organisation; +import org.lamsfoundation.lams.usermanagement.OrganisationState; +import org.lamsfoundation.lams.usermanagement.Role; +import org.lamsfoundation.lams.usermanagement.User; +import org.lamsfoundation.lams.usermanagement.UserOrganisation; +import org.lamsfoundation.lams.usermanagement.dto.OrganisationDTO; +import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; +import org.lamsfoundation.lams.util.CentralConstants; +import org.lamsfoundation.lams.util.Configuration; +import org.lamsfoundation.lams.util.ConfigurationKeys; +import org.lamsfoundation.lams.util.HashUtil; +import org.lamsfoundation.lams.util.MessageService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; +import org.springframework.web.context.support.WebApplicationContextUtils; + +/** + * @author Andrey Balan + */ +public class RegisterServlet extends HttpServlet { + private static Logger logger = Logger.getLogger(RegisterServlet.class); + + @Autowired + private IntegrationService integrationService; + @Autowired + private ILearnerProgressDAO learnerProgressDAO; + @Autowired + private ILessonService lessonService; + @Autowired + private ILearnerService learnerService; + @Autowired + private IGroupUserDAO groupUserDAO; + @Autowired + private IUserManagementService userManagementService; + @Autowired + private IEventNotificationService eventNotificationService; + @Autowired + private MessageService centralMessageService; + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String method = request.getParameter(CentralConstants.PARAM_METHOD); + if (method.equals("addUserToGroupLessons")) { + addUserToGroupLessons(request, response); + + } else if (method.equals("removeUserFromGroup")) { + removeUserFromGroup(request, response); + + } else if (method.equals("resetUserTimeLimit")) { + resetUserTimeLimit(request, response); + } + } + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } + + /** + * 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% + * &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. + */ + public void addUserToGroupLessons(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(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); + return; + } + 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 lessonId = request.getParameter(CentralConstants.ATTR_LESSON_ID); + String username = request.getParameter(CentralConstants.PARAM_USERNAME); + String usePrefix = request.getParameter("usePrefix"); + String firstName = request.getParameter("firstName"); + String lastName = request.getParameter("lastName"); + String email = request.getParameter("email"); + String isJoinLesson = request.getParameter("isJoinLesson"); + String isEmailParticipant = request.getParameter("isEmailParticipant"); + String isEmailCoordinator = request.getParameter("isEmailCoordinator"); + + if (serverId == null || datetime == null || hashValue == null || username == null) { + String msg = "Parameters missing"; + logger.error(msg); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameters missing"); + } + + // authenticate external server + ExtServer extServer = integrationService.getExtServer(serverId); + Authenticator.authenticate(extServer, datetime, username, method, hashValue); + + // create new password + String password = RandomPasswordGenerator.nextPassword(8); + String salt = HashUtil.salt(); + String passwordHash = HashUtil.sha256(password, salt); + + // 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, create it otherwise + ExtUserUseridMap userMap = integrationService.getImplicitExtUserUseridMap(extServer, username, passwordHash, + salt, 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 + List learnerRole = new ArrayList(); + learnerRole.add(Role.ROLE_LEARNER.toString()); + for (Organisation organisationToJoin : organisationsToJoin) { + 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"); + } + } + + // join user to all lessons in the group + if ("1".equals(isJoinLesson)) { + for (Lesson lesson : lessonsToJoin) { + + LearnerProgress learnerProgress = learnerProgressDAO.getLearnerProgressByLearner(user.getUserId(), + lesson.getLessonId()); + if (learnerProgress == null) { + 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 + resetUserTimeLimit(lesson, user); + } + } + } + + // send email to participant + if ("1".equals(isEmailParticipant)) { + boolean isHtmlFormat = false; + + eventNotificationService.sendMessage(null, user.getUserId(), + IEventNotificationService.DELIVERY_METHOD_MAIL, + centralMessageService.getMessage("register.user.email.subject"), + centralMessageService.getMessage("register.user.email.body", new Object[] { username, password }), + isHtmlFormat); + } + + // 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(null, coordinator.getUserId(), + IEventNotificationService.DELIVERY_METHOD_MAIL, + centralMessageService.getMessage("notify.coordinator.register.user.email.subject"), + centralMessageService.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. + * + * External server call must follow the next format: 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 + */ + public void removeUserFromGroup(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(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); + return; + } + 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"); + + if (serverId == null || datetime == null || hashValue == null || username == null) { + String msg = "Parameters missing"; + logger.error(msg); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameters missing"); + } + + // authenticate external server + ExtServer extServer = integrationService.getExtServer(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); + } + + // 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 + 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. + * + * 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% + * + * 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 + */ + 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(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); + return; + } + + 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 courseId = request.getParameter(CentralConstants.PARAM_COURSE_ID); + String username = request.getParameter(CentralConstants.PARAM_USERNAME); + 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(HttpServletResponse.SC_BAD_REQUEST, "Parameters missing"); + } + + // authenticate external server + ExtServer extServer = integrationService.getExtServer(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); + } + + // 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 + Organisation org = getOrganisationByName(courseId); + + // reset time limit + if (org.getLessons() != null) { + for (Lesson lesson : (Set) org.getLessons()) { + resetUserTimeLimit(lesson, user); + } + } + + writeAJAXOKResponse(response); + + } catch (Exception e) { + logger.error(e.getMessage()); + writeAJAXResponse(response, "ERROR: " + e.getMessage()); + } + } + + /** + * resetUserTimeLimit + * + * @param lesson + * @param user + */ + private void resetUserTimeLimit(Lesson lesson, User user) { + // check if lesson is set to be finished for individual users then reset finish date + if (lesson.isScheduledToCloseForIndividuals()) { + GroupUser groupUser = groupUserDAO.getGroupUser(lesson, user.getUserId()); + if (groupUser != null) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DATE, lesson.getScheduledNumberDaysToLessonFinish()); + Date endDate = calendar.getTime(); + groupUser.setScheduledLessonEndDate(endDate); + logger.debug("Reset time limit for user:" + user.getLogin() + "in lesson:" + lesson.getLessonId() + + " to " + endDate); + } + } + } + + private ExtUserUseridMap getExtUserUseridMap(ExtServer extServer, String extUsername) + throws UserInfoFetchException { + Map properties = new HashMap(); + properties.put("extServer.sid", extServer.getSid()); + properties.put("extUsername", extUsername); + List list = userManagementService.findByProperties(ExtUserUseridMap.class, properties); + if (list == null || list.size() == 0) { + throw new RuntimeException("There is no user with username: " + extUsername + + " assossiated with external server " + extServer.getSid()); + } else { + return (ExtUserUseridMap) list.get(0); + } + } + + // 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(); + properties.put("name", name); + properties.put("organisationState.organisationStateId", OrganisationState.ACTIVE); + List list = userManagementService.findByProperties(Organisation.class, properties); + if (list == null || list.size() == 0) { + throw new RuntimeException("There is no active course with courseId: " + name); + } else { + Organisation organisation = list.get(0); + return organisation; + } + } + + // 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(ExtServer extServer, ExtUserUseridMap userMap, + String extCourseId, Boolean isTeacher) { + Map properties = new HashMap(); + properties.put("courseid", extCourseId); + properties.put("extServer.sid", extServer.getSid()); + List list = userManagementService.findByProperties(ExtCourseClassMap.class, properties); + if (list == null || list.size() == 0) { + throw new RuntimeException("There is no course with courseId: " + extCourseId); + } else { + ExtCourseClassMap map = (ExtCourseClassMap) list.get(0); + return map; + } + } + + private void removeGroupMembership(User user, Integer organisationId) { + UserOrganisation userOrganisation = userManagementService.getUserOrganisation(user.getUserId(), organisationId); + + Set userOrganisations = user.getUserOrganisations(); + userOrganisations.remove(userOrganisation); + userManagementService.saveUser(user); + + // 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/src/java/org/lamsfoundation/lams/webservice/UserRoleServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/webservice/UserRoleServlet.java (.../UserRoleServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/webservice/UserRoleServlet.java (.../UserRoleServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.List; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -22,21 +23,23 @@ import org.lamsfoundation.lams.util.CentralConstants; import org.lamsfoundation.lams.util.HashUtil; import org.lamsfoundation.lams.web.util.AttributeNames; -import org.springframework.web.context.support.WebApplicationContextUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * Allows user role granting for integrated environments. * * @author Marcin Cieslak - * */ public class UserRoleServlet extends HttpServlet { - private static Logger log = Logger.getLogger(UserRoleServlet.class); - private static IntegrationService integrationService = null; - private static IUserManagementService userManagementService = null; - private static ISecurityService securityService = null; + @Autowired + private IntegrationService integrationService; + @Autowired + private IUserManagementService userManagementService; + @Autowired + private ISecurityService securityService; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -49,7 +52,7 @@ String role = request.getParameter(AttributeNames.PARAM_ROLE); try { - ExtServer extServer = UserRoleServlet.integrationService.getExtServer(serverId); + ExtServer extServer = integrationService.getExtServer(serverId); String plaintext = datetime.toLowerCase().trim() + username.toLowerCase().trim() + targetUsername.toLowerCase().trim() + method.toLowerCase().trim() + role.toLowerCase().trim() + extServer.getServerid().toLowerCase().trim() + extServer.getServerkey().toLowerCase().trim(); @@ -58,14 +61,14 @@ response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed, invalid hash"); return; } - ExtUserUseridMap sysadminUserMap = UserRoleServlet.integrationService.getExtUserUseridMap(extServer, + ExtUserUseridMap sysadminUserMap = integrationService.getExtUserUseridMap(extServer, username); if (!securityService.isSysadmin(sysadminUserMap.getUser().getUserId(), "set user role", false)) { log.error("Sysadmin role check failed while trying to set role for user: " + targetUsername); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed, user is not sysadmin"); return; } - ExtUserUseridMap userMap = UserRoleServlet.integrationService.getExtUserUseridMap(extServer, + ExtUserUseridMap userMap = integrationService.getExtUserUseridMap(extServer, targetUsername); User targetUser = userMap.getUser(); if ("grant".equalsIgnoreCase(method)) { @@ -77,7 +80,7 @@ response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown method: " + method); } } catch (Exception e) { - UserRoleServlet.log.error("Error while setting user roles", e); + log.error("Error while setting user roles", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while setting user roles"); } } @@ -87,17 +90,14 @@ doGet(request, response); } - /** - * Initialization of the servlet. + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. */ @Override - public void init() throws ServletException { - UserRoleServlet.integrationService = (IntegrationService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("integrationService"); - UserRoleServlet.userManagementService = (IUserManagementService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("userManagementService"); - UserRoleServlet.securityService = (ISecurityService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("securityService"); + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); } /** Index: lams_central/src/java/org/lamsfoundation/lams/webservice/xml/LearningDesignRepositoryServlet.java =================================================================== diff -u -r62aaf160878735888d077bf28fac3c1989bb8fbd -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/webservice/xml/LearningDesignRepositoryServlet.java (.../LearningDesignRepositoryServlet.java) (revision 62aaf160878735888d077bf28fac3c1989bb8fbd) +++ lams_central/src/java/org/lamsfoundation/lams/webservice/xml/LearningDesignRepositoryServlet.java (.../LearningDesignRepositoryServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -12,6 +12,7 @@ import java.util.List; import java.util.Vector; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -40,32 +41,30 @@ import org.lamsfoundation.lams.usermanagement.exception.UserAccessDeniedException; import org.lamsfoundation.lams.util.CentralConstants; import org.lamsfoundation.lams.util.FileUtil; -import org.lamsfoundation.lams.util.LanguageUtil; import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.workspace.dto.FolderContentDTO; import org.lamsfoundation.lams.workspace.service.IWorkspaceManagementService; import org.lamsfoundation.lams.workspace.web.WorkspaceController; -import org.springframework.web.context.support.WebApplicationContextUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; import org.w3c.dom.Document; import org.w3c.dom.Element; public class LearningDesignRepositoryServlet extends HttpServlet { - private static final long serialVersionUID = -4962711640290319063L; - private static Logger log = Logger.getLogger(LearningDesignRepositoryServlet.class); - - private static IntegrationService integrationService = null; - - private static IWorkspaceManagementService service = null; - - private static MessageService msgService = null; - - private static IExportToolContentService exportToolContentService = null; - private static final String PARAM_LEARING_DESIGN_ID = "learningDesignID"; + @Autowired + private IntegrationService integrationService; + @Autowired + private IWorkspaceManagementService workspaceManagementService; + @Autowired + private MessageService centralMessageService; + @Autowired + private IExportToolContentService exportToolContentService; + /** * Constructor of the object. */ @@ -168,18 +167,16 @@ private ContentTreeNode buildContentTree(Integer userId, Integer mode) throws IOException, UserAccessDeniedException, RepositoryCheckedException { - LearningDesignRepositoryServlet.log.debug("User Id - " + userId); - FolderContentDTO rootFolder = new FolderContentDTO( - LearningDesignRepositoryServlet.msgService.getMessage("label.workspace.root_folder"), - LearningDesignRepositoryServlet.msgService.getMessage("folder"), null, null, FolderContentDTO.FOLDER, + log.debug("User Id - " + userId); + FolderContentDTO rootFolder = new FolderContentDTO(centralMessageService.getMessage("label.workspace.root_folder"), + centralMessageService.getMessage("folder"), null, null, FolderContentDTO.FOLDER, WorkspaceController.BOOTSTRAP_FOLDER_ID.longValue(), WorkspaceFolder.READ_ACCESS, null); ContentTreeNode root = new ContentTreeNode(rootFolder); - FolderContentDTO userFolder = LearningDesignRepositoryServlet.service.getUserWorkspaceFolder(userId); + FolderContentDTO userFolder = workspaceManagementService.getUserWorkspaceFolder(userId); root.addChild(buildContentTreeNode(userFolder, userId, mode)); - FolderContentDTO dummyOrgFolder = new FolderContentDTO( - LearningDesignRepositoryServlet.msgService.getMessage("organisations"), - LearningDesignRepositoryServlet.msgService.getMessage("folder"), null, null, FolderContentDTO.FOLDER, + FolderContentDTO dummyOrgFolder = new FolderContentDTO(centralMessageService.getMessage("organisations"), + centralMessageService.getMessage("folder"), null, null, FolderContentDTO.FOLDER, new Long(WorkspaceController.ORG_FOLDER_ID.longValue()), WorkspaceFolder.READ_ACCESS, null); ContentTreeNode dummyOrgNode = new ContentTreeNode(dummyOrgFolder); // tried using service.getAccessibleOrganisationWorkspaceFolders(userId) @@ -188,14 +185,14 @@ // got from workspaceManagementService with the userId supplied is // empty, which // is not true. - Vector orgFolders = LearningDesignRepositoryServlet.service.getAccessibleOrganisationWorkspaceFolders(userId); + Vector orgFolders = workspaceManagementService.getAccessibleOrganisationWorkspaceFolders(userId); for (int i = 0; i < orgFolders.size(); i++) { FolderContentDTO orgFolder = (FolderContentDTO) orgFolders.get(i); dummyOrgNode.addChild(buildContentTreeNode(orgFolder, userId, mode)); } root.addChild(dummyOrgNode); - FolderContentDTO publicFolder = LearningDesignRepositoryServlet.service.getPublicWorkspaceFolder(userId); + FolderContentDTO publicFolder = workspaceManagementService.getPublicWorkspaceFolder(userId); if (publicFolder != null) { root.addChild(buildContentTreeNode(publicFolder, userId, mode)); } @@ -204,13 +201,12 @@ private ContentTreeNode buildContentTreeNode(FolderContentDTO folder, Integer userId, Integer mode) throws UserAccessDeniedException, RepositoryCheckedException { - LearningDesignRepositoryServlet.log.debug("build content tree node for folder - " + folder.getName()); + log.debug("build content tree node for folder - " + folder.getName()); ContentTreeNode node = new ContentTreeNode(folder); if (folder.getResourceType().equals(FolderContentDTO.FOLDER)) { - LearningDesignRepositoryServlet.log.debug(folder.getName() + " is a folder"); - WorkspaceFolder wsfolder = LearningDesignRepositoryServlet.service - .getWorkspaceFolder(folder.getResourceID().intValue()); - Vector items = LearningDesignRepositoryServlet.service.getFolderContentsExcludeHome(userId, wsfolder, mode); + log.debug(folder.getName() + " is a folder"); + WorkspaceFolder wsfolder = workspaceManagementService.getWorkspaceFolder(folder.getResourceID().intValue()); + Vector items = workspaceManagementService.getFolderContentsExcludeHome(userId, wsfolder, mode); for (int i = 0; i < items.size(); i++) { FolderContentDTO content = (FolderContentDTO) items.get(i); node.addChild(buildContentTreeNode(content, userId, mode)); @@ -258,13 +254,13 @@ if ((serverId == null) || (datetime == null) || (hashValue == null) || (username == null) || (courseId == null) || (country == null) || (locale == null)) { String msg = "Parameters missing"; - LearningDesignRepositoryServlet.log.error(msg); + log.error(msg); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameters missing"); } // LDEV-2196 preserve character encoding if necessary if (request.getCharacterEncoding() == null) { - LearningDesignRepositoryServlet.log.debug( + log.debug( "request.getCharacterEncoding is empty, parsing username and courseName as 8859_1 to UTF-8..."); username = new String(username.getBytes("8859_1"), "UTF-8"); if (courseName != null) { @@ -273,7 +269,7 @@ } // get Server map - ExtServer extServer = LearningDesignRepositoryServlet.integrationService.getExtServer(serverId); + ExtServer extServer = integrationService.getExtServer(serverId); // authenticate Authenticator.authenticate(extServer, datetime, username, hashValue); @@ -296,17 +292,16 @@ if (method.equals("getLearningDesignsJSON")) { Integer folderID = WebUtil.readIntParam(request, "folderID", true); String designType = request.getParameter("type"); - folderContentsJSON = LearningDesignRepositoryServlet.service.getFolderContentsJSON(folderID, userId, - allowInvalidDesigns, designType); + folderContentsJSON = workspaceManagementService.getFolderContentsJSON(folderID, userId, allowInvalidDesigns, + designType); } else { Integer page = WebUtil.readIntParam(request, "page", true); Integer size = WebUtil.readIntParam(request, "size", true); String sortName = request.getParameter("sortName"); String sortDate = request.getParameter("sortDate"); String search = request.getParameter("search"); - folderContentsJSON = LearningDesignRepositoryServlet.service.getPagedLearningDesignsJSON(userId, - allowInvalidDesigns, search, page, size, - sortName == null ? null : (sortName.equals("0") ? "DESC" : "ASC"), + folderContentsJSON = workspaceManagementService.getPagedLearningDesignsJSON(userId, allowInvalidDesigns, search, page, + size, sortName == null ? null : (sortName.equals("0") ? "DESC" : "ASC"), sortDate == null ? null : (sortDate.equals("0") ? "DESC" : "ASC")); } @@ -318,36 +313,32 @@ Integer userId = getUserId(username, courseId, courseName, locale, country, usePrefix, isUpdateUserDetails, firstName, lastName, email, extServer); - Long learningDesignId = WebUtil.readLongParam(request, - LearningDesignRepositoryServlet.PARAM_LEARING_DESIGN_ID); - LearningDesignRepositoryServlet.log - .debug("User " + userId + " " + username + " deleting learning design " + learningDesignId); + Long learningDesignId = WebUtil.readLongParam(request, PARAM_LEARING_DESIGN_ID); + log.debug("User " + userId + " " + username + " deleting learning design " + learningDesignId); // if OK then just return HTTP 200, otherwise an exception will result in error code - LearningDesignRepositoryServlet.service.deleteResource(learningDesignId, FolderContentDTO.DESIGN, - userId); + workspaceManagementService.deleteResource(learningDesignId, FolderContentDTO.DESIGN, userId); //TODO remove the next else-paragraph as soon as all integrations will start using new method. (After this also stop checking for (method != null && method.equals("getLearningDesignsJSONFormat"))) } else { if (mode == null) { String msg = "Parameter missing: mode"; - LearningDesignRepositoryServlet.log.error(msg); + log.error(msg); response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } ExtUserUseridMap userMap = null; boolean prefix = usePrefix == null ? true : Boolean.parseBoolean(usePrefix); if ((firstName == null) && (lastName == null)) { - userMap = LearningDesignRepositoryServlet.integrationService.getExtUserUseridMap(extServer, - username, prefix); + userMap = integrationService.getExtUserUseridMap(extServer, username, prefix); } else { - userMap = LearningDesignRepositoryServlet.integrationService.getImplicitExtUserUseridMap(extServer, - username, firstName, lastName, locale, country, email, prefix, isUpdateUserDetails); + userMap = integrationService.getImplicitExtUserUseridMap(extServer, username, firstName, lastName, + locale, country, email, prefix, isUpdateUserDetails); } // create group for external course if necessary - LearningDesignRepositoryServlet.integrationService.getExtCourseClassMap(extServer, userMap, courseId, - courseName, LoginRequestDispatcher.METHOD_AUTHOR); + integrationService.getExtCourseClassMap(extServer, userMap, courseId, courseName, + LoginRequestDispatcher.METHOD_AUTHOR); Integer userId = userMap.getUser().getUserId(); String contentTree = buildContentTree(userId, mode).toString(); @@ -361,22 +352,22 @@ } } catch (NumberFormatException nfe) { - LearningDesignRepositoryServlet.log.error("mode is not an integer", nfe); + log.error("mode is not an integer", nfe); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "mode is not an integer"); } catch (AuthenticationException e) { - LearningDesignRepositoryServlet.log.error("can not authenticate", e); + log.error("can not authenticate", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "can not authenticate"); } catch (UserInfoFetchException e) { - LearningDesignRepositoryServlet.log.error("can not retrieve user information", e); + log.error("can not retrieve user information", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "can not retrieve user information"); } catch (UserAccessDeniedException e) { - LearningDesignRepositoryServlet.log.error("user access denied", e); + log.error("user access denied", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "user access denied"); } catch (RepositoryCheckedException e) { - LearningDesignRepositoryServlet.log.error("repository checked", e); + log.error("repository checked", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "repository checked"); } catch (Exception e) { - LearningDesignRepositoryServlet.log.error("Problem with LearningDesignRepositoryServlet request", e); + log.error("Problem with LearningDesignRepositoryServlet request", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Problem with LearningDesignRepositoryServlet request"); } @@ -385,22 +376,19 @@ private Integer getUserId(String username, String courseId, String courseName, String locale, String country, String usePrefix, final boolean isUpdateUserDetails, String firstName, String lastName, String email, - ExtServer extServer) - throws UserInfoFetchException, UserInfoValidationException { + ExtServer extServer) throws UserInfoFetchException, UserInfoValidationException { ExtUserUseridMap userMap = null; boolean prefix = usePrefix == null ? true : Boolean.parseBoolean(usePrefix); if ((firstName == null) && (lastName == null)) { - userMap = LearningDesignRepositoryServlet.integrationService.getExtUserUseridMap(extServer, username, - prefix); + userMap = integrationService.getExtUserUseridMap(extServer, username, prefix); } else { - userMap = LearningDesignRepositoryServlet.integrationService.getImplicitExtUserUseridMap(extServer, - username, firstName, lastName, locale, country, email, prefix, - isUpdateUserDetails); + userMap = integrationService.getImplicitExtUserUseridMap(extServer, username, firstName, lastName, locale, + country, email, prefix, isUpdateUserDetails); } // create group for external course if necessary - LearningDesignRepositoryServlet.integrationService.getExtCourseClassMap(extServer, userMap, courseId, - courseName, LoginRequestDispatcher.METHOD_AUTHOR); + integrationService.getExtCourseClassMap(extServer, userMap, courseId, courseName, + LoginRequestDispatcher.METHOD_AUTHOR); Integer userId = userMap.getUser().getUserId(); return userId; } @@ -411,12 +399,11 @@ } public void exportLD(HttpServletRequest request, HttpServletResponse response) { - Long learningDesignId = WebUtil.readLongParam(request, LearningDesignRepositoryServlet.PARAM_LEARING_DESIGN_ID); + Long learningDesignId = WebUtil.readLongParam(request, PARAM_LEARING_DESIGN_ID); List toolsErrorMsgs = new ArrayList(); try { - String zipFilename = LearningDesignRepositoryServlet.exportToolContentService - .exportLearningDesign(learningDesignId, toolsErrorMsgs); + String zipFilename = exportToolContentService.exportLearningDesign(learningDesignId, toolsErrorMsgs); // get only filename String zipfile = FileUtil.getFileName(zipFilename); @@ -426,7 +413,7 @@ // Different browsers handle stream downloads differently LDEV-1243 String filename = FileUtil.encodeFilenameForDownload(request, zipfile); - LearningDesignRepositoryServlet.log.debug("Final filename to export: " + filename); + log.debug("Final filename to export: " + filename); response.setContentType("application/x-download"); // response.setContentType("application/zip"); @@ -443,11 +430,11 @@ out.write((char) ch); count++; } - LearningDesignRepositoryServlet.log.debug("Wrote out " + count + " bytes"); + log.debug("Wrote out " + count + " bytes"); response.setContentLength(count); out.flush(); } catch (Exception e) { - LearningDesignRepositoryServlet.log.error("Exception occured writing out file:" + e.getMessage()); + log.error("Exception occured writing out file:" + e.getMessage()); throw new ExportToolContentException(e); } finally { try { @@ -458,33 +445,21 @@ out.close(); } } catch (Exception e) { - LearningDesignRepositoryServlet.log - .error("Error Closing file. File already written out - no exception being thrown.", e); + log.error("Error Closing file. File already written out - no exception being thrown.", e); } } } catch (Exception e1) { - LearningDesignRepositoryServlet.log - .error("Unable to export tool content to external integrated server: " + e1.toString()); + log.error("Unable to export tool content to external integrated server: " + e1.toString()); } } - /** - * Initialization of the servlet.
- * - * @throws ServletException - * if an error occure + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. */ @Override - public void init() throws ServletException { - LearningDesignRepositoryServlet.integrationService = (IntegrationService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("integrationService"); - - LearningDesignRepositoryServlet.service = (IWorkspaceManagementService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("workspaceManagementService"); - - LearningDesignRepositoryServlet.msgService = LearningDesignRepositoryServlet.service.getMessageService(); - - LearningDesignRepositoryServlet.exportToolContentService = (IExportToolContentService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("exportToolContentService"); + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); } } Index: lams_central/src/java/org/lamsfoundation/lams/webservice/xml/LessonManagerServlet.java =================================================================== diff -u -r62aaf160878735888d077bf28fac3c1989bb8fbd -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/webservice/xml/LessonManagerServlet.java (.../LessonManagerServlet.java) (revision 62aaf160878735888d077bf28fac3c1989bb8fbd) +++ lams_central/src/java/org/lamsfoundation/lams/webservice/xml/LessonManagerServlet.java (.../LessonManagerServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -16,6 +16,7 @@ import java.util.TreeSet; import java.util.Vector; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; @@ -68,6 +69,8 @@ import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.web.session.SessionManager; import org.lamsfoundation.lams.web.util.AttributeNames; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; import org.springframework.web.context.support.WebApplicationContextUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -78,25 +81,35 @@ @SuppressWarnings("serial") public class LessonManagerServlet extends HttpServlet { - private static Logger log = Logger.getLogger(LessonManagerServlet.class); - private static IntegrationService integrationService = null; + @Autowired + private IntegrationService integrationService; + @Autowired + private IMonitoringService monitoringService; + @Autowired + private ILessonService lessonService; + @Autowired + private IExportToolContentService exportToolContentService; + @Autowired + private ILamsCoreToolService lamsCoreToolService; + @Autowired + private IGradebookService gradebookService; + @Autowired + private IUserManagementService userManagementService; + @Autowired + private ISecurityService securityService; + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } - private static IMonitoringService monitoringService = null; - - private static ILessonService lessonService = null; - - private static IExportToolContentService exportService = null; - - private static ILamsCoreToolService toolService = null; - - private static IGradebookService gradebookService = null; - - private static IUserManagementService userManagementService = null; - - private static ISecurityService securityService = null; - /** * The doGet method of the servlet.
* @@ -180,8 +193,8 @@ if (method.equals(CentralConstants.METHOD_START)) { ldId = new Long(ldIdStr); - Long lessonId = LessonManagerServlet.startLesson(serverId, datetime, hashValue, username, ldId, - courseId, title, desc, enforceAllowLearnerRestart, country, locale, customCSV, presenceEnable, imEnable, + Long lessonId = startLesson(serverId, datetime, hashValue, username, ldId, courseId, title, desc, + enforceAllowLearnerRestart, country, locale, customCSV, presenceEnable, imEnable, enableNotifications); element = document.createElement(CentralConstants.ELEM_LESSON); @@ -380,7 +393,7 @@ doGet(request, response); } - private static Long startLesson(String serverId, String datetime, String hashValue, String username, long ldId, + private Long startLesson(String serverId, String datetime, String hashValue, String username, long ldId, String courseId, String title, String desc, boolean enforceAllowLearnerRestart, String countryIsoCode, String langIsoCode, String customCSV, Boolean presenceEnable, Boolean imEnable, Boolean enableNotifications) throws RemoteException { @@ -403,7 +416,7 @@ enforceAllowLearnerRestart ? true : extServer.getAllowLearnerRestart(), extServer.getGradebookOnComplete(), null, null); // 2. create lessonClass for lesson - LessonManagerServlet.createLessonClass(lesson, organisation, user); + createLessonClass(lesson, organisation, user); // 3. start lesson monitoringService.startLesson(lesson.getLessonId(), user.getUserId()); // store information which extServer has started the lesson @@ -435,7 +448,7 @@ enforceAllowLearnerRestart ? true : extServer.getAllowLearnerRestart(), extServer.getGradebookOnComplete(), null, null); // 2. create lessonClass for lesson - LessonManagerServlet.createLessonClass(lesson, orgMap.getOrganisation(), userMap.getUser()); + createLessonClass(lesson, orgMap.getOrganisation(), userMap.getUser()); // 3. schedule lesson Date date = DateUtil.convertFromString(startDate, DateUtil.SCHEDULE_LESSON_FORMAT); monitoringService.startLessonOnSchedule(lesson.getLessonId(), date, userMap.getUser().getUserId()); @@ -785,7 +798,7 @@ } File designFile = new File(filePath); - Object[] ldResults = exportService.importLearningDesign(designFile, user, workspaceFolderUid, + Object[] ldResults = exportToolContentService.importLearningDesign(designFile, user, workspaceFolderUid, toolsErrorMsgs, customCSV); ldId = (Long) ldResults[0]; ldErrorMsgs = (List) ldResults[1]; @@ -803,7 +816,7 @@ } @SuppressWarnings("unchecked") - private static void createLessonClass(Lesson lesson, Organisation organisation, User creator) { + private void createLessonClass(Lesson lesson, Organisation organisation, User creator) { List staffList = new LinkedList<>(); staffList.add(creator); List learnerList = new LinkedList<>(); @@ -815,40 +828,6 @@ creator.getUserId()); } - /** - * Initialization of the servlet.
- * - * @throws ServletException - * if an error occured - */ - @Override - public void init() throws ServletException { - - integrationService = (IntegrationService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("integrationService"); - - monitoringService = (IMonitoringService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("monitoringService"); - - lessonService = (ILessonService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("lessonService"); - - exportService = (IExportToolContentService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("exportToolContentService"); - - toolService = (ILamsCoreToolService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("lamsCoreToolService"); - - gradebookService = (IGradebookService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("gradebookService"); - - userManagementService = (IUserManagementService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("userManagementService"); - - securityService = (ISecurityService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("securityService"); - } - private class AddUsersToLessonThread implements Runnable { private String serverId; @@ -1086,7 +1065,7 @@ lessonElement.setAttribute("lessonName", lesson.getLessonName()); // calculate lesson's MaxPossibleMark - Long lessonMaxPossibleMark = toolService.getLessonMaxPossibleMark(lesson); + Long lessonMaxPossibleMark = lamsCoreToolService.getLessonMaxPossibleMark(lesson); lessonElement.setAttribute("lessonMaxPossibleMark", lessonMaxPossibleMark.toString()); List allUsers = integrationService.getExtUserUseridMapByExtServer(extServer); @@ -1243,14 +1222,14 @@ toolOutputsElement.setAttribute("name", lesson.getLessonName()); List learnerProgresses = lessonService.getUserProgressForLesson(lesson.getLessonId()); - List toolSessions = toolService.getToolSessionsByLesson(lesson); + List toolSessions = lamsCoreToolService.getToolSessionsByLesson(lesson); // map contains pairs toolContentId -> toolOutputDefinitions Map> toolOutputDefinitionsMap = new TreeMap<>(); for (ToolActivity activity : activities) { Long toolContentId = activity.getToolContentId(); if (toolOutputDefinitionsMap.get(toolContentId) == null) { - SortedMap toolOutputDefinitions = toolService + SortedMap toolOutputDefinitions = lamsCoreToolService .getOutputDefinitionsFromTool(toolContentId, ToolOutputDefinition.DATA_OUTPUT_DEFINITION_TYPE_CONDITION); toolOutputDefinitionsMap.put(toolContentId, toolOutputDefinitions); @@ -1431,13 +1410,13 @@ ActivityEvaluation evaluation = activity.getEvaluation(); if (evaluation != null) { if (outputName.equals(evaluation.getToolOutputDefinition())) { - ToolOutput toolOutput = toolService.getOutputFromTool(outputName, toolSession, + ToolOutput toolOutput = lamsCoreToolService.getOutputFromTool(outputName, toolSession, learner.getUserId()); activityElement.appendChild(getOutputElement(document, toolOutput, definition)); } } } else { - ToolOutput toolOutput = toolService.getOutputFromTool(outputName, toolSession, + ToolOutput toolOutput = lamsCoreToolService.getOutputFromTool(outputName, toolSession, learner.getUserId()); if (toolOutput != null) { Index: lams_central/src/java/org/lamsfoundation/lams/webservice/xml/NotificationServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/webservice/xml/NotificationServlet.java (.../NotificationServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/webservice/xml/NotificationServlet.java (.../NotificationServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -24,6 +24,7 @@ import org.lamsfoundation.lams.integration.service.IntegrationService; import org.lamsfoundation.lams.util.CentralConstants; import org.lamsfoundation.lams.util.WebUtil; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.support.WebApplicationContextUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -35,19 +36,18 @@ * Allows notifications access for integrated environments. * * @author Marcin Cieslak - * */ public class NotificationServlet extends HttpServlet { private static final long serialVersionUID = 4856874776383254865L; - private static Logger log = Logger.getLogger(NotificationServlet.class); - - private static IntegrationService integrationService = null; - private static IEventNotificationService eventNotificationService = null; - - private static DocumentBuilder docBuilder = null; private static final Pattern anchorPattern = Pattern.compile("(.*)"); + private static DocumentBuilder docBuilder = null; + @Autowired + private IntegrationService integrationService; + @Autowired + private IEventNotificationService eventNotificationService; + static { try { NotificationServlet.docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); @@ -67,15 +67,15 @@ String username = request.getParameter(CentralConstants.PARAM_USERNAME); try { - ExtServer extServer = NotificationServlet.integrationService.getExtServer(serverId); + ExtServer extServer = integrationService.getExtServer(serverId); Authenticator.authenticate(extServer, datetime, username, hashValue); - ExtUserUseridMap userMap = NotificationServlet.integrationService.getExtUserUseridMap(extServer, username); + ExtUserUseridMap userMap = integrationService.getExtUserUseridMap(extServer, username); String method = request.getParameter(CentralConstants.PARAM_METHOD); if ("getNotifications".equalsIgnoreCase(method)) { getNotifications(userMap.getUser().getUserId(), request, response); } } catch (Exception e) { - NotificationServlet.log.error("Error while getting notifications", e); + log.error("Error while getting notifications", e); } } @@ -92,10 +92,10 @@ */ @Override public void init() throws ServletException { - NotificationServlet.integrationService = (IntegrationService) WebApplicationContextUtils + integrationService = (IntegrationService) WebApplicationContextUtils .getRequiredWebApplicationContext(getServletContext()).getBean("integrationService"); - NotificationServlet.eventNotificationService = (IEventNotificationService) WebApplicationContextUtils + eventNotificationService = (IEventNotificationService) WebApplicationContextUtils .getRequiredWebApplicationContext(getServletContext()).getBean("eventNotificationService"); } @@ -110,7 +110,7 @@ Integer offset = WebUtil.readIntParam(request, "offset", true); Boolean pendingOnly = WebUtil.readBooleanParam(request, "pendingOnly", true); - List subscriptions = NotificationServlet.eventNotificationService + List subscriptions = eventNotificationService .getNotificationSubscriptions(lessonId, userId, pendingOnly, limit, offset); for (Subscription subscription : subscriptions) { Element notificationElement = doc.createElement("Notification"); Index: lams_central/src/java/org/lamsfoundation/lams/webservice/xml/OrganisationGroupServlet.java =================================================================== diff -u -r7475d08afc280b5e2e5ddf04e8bf35e3166aaf80 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/src/java/org/lamsfoundation/lams/webservice/xml/OrganisationGroupServlet.java (.../OrganisationGroupServlet.java) (revision 7475d08afc280b5e2e5ddf04e8bf35e3166aaf80) +++ lams_central/src/java/org/lamsfoundation/lams/webservice/xml/OrganisationGroupServlet.java (.../OrganisationGroupServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -3,6 +3,7 @@ import java.io.IOException; import java.util.List; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -22,7 +23,8 @@ import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; import org.lamsfoundation.lams.util.CentralConstants; import org.lamsfoundation.lams.util.WebUtil; -import org.springframework.web.context.support.WebApplicationContextUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.ls.DOMImplementationLS; @@ -38,18 +40,30 @@ public class OrganisationGroupServlet extends HttpServlet { private static Logger log = Logger.getLogger(OrganisationGroupServlet.class); - private static IntegrationService integrationService = null; - private static IUserManagementService userManagementService = null; + @Autowired + private IntegrationService integrationService; + @Autowired + private IUserManagementService userManagementService; private static DocumentBuilder docBuilder = null; static { try { OrganisationGroupServlet.docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { - OrganisationGroupServlet.log.error("Error while initialising XML document builder", e); + log.error("Error while initialising XML document builder", e); } } + + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { @@ -59,7 +73,7 @@ String username = request.getParameter(CentralConstants.PARAM_USERNAME); try { - ExtServer extServer = OrganisationGroupServlet.integrationService.getExtServer(serverId); + ExtServer extServer = integrationService.getExtServer(serverId); Authenticator.authenticate(extServer, datetime, username, hashValue); String method = request.getParameter(CentralConstants.PARAM_METHOD); @@ -71,7 +85,7 @@ response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown method: " + method); } } catch (Exception e) { - OrganisationGroupServlet.log.error("Error while getting notifications", e); + log.error("Error while getting notifications", e); } } @@ -80,18 +94,6 @@ doGet(request, response); } - /** - * Initialization of the servlet. - */ - @Override - public void init() throws ServletException { - OrganisationGroupServlet.integrationService = (IntegrationService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("integrationService"); - - userManagementService = (IUserManagementService) WebApplicationContextUtils - .getRequiredWebApplicationContext(getServletContext()).getBean("userManagementService"); - } - @SuppressWarnings("unchecked") private void getGroupings(Integer organisationId, HttpServletResponse response) throws IOException { Document doc = OrganisationGroupServlet.docBuilder.newDocument(); Index: lams_central/web/WEB-INF/web.xml =================================================================== diff -u -rfd067e2f01c881d99c717983bdeb4ce64df77db2 -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_central/web/WEB-INF/web.xml (.../web.xml) (revision fd067e2f01c881d99c717983bdeb4ce64df77db2) +++ lams_central/web/WEB-INF/web.xml (.../web.xml) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -201,7 +201,7 @@ RegisterServlet - org.lamsfoundation.lams.webservice.RegisterAction + org.lamsfoundation.lams.webservice.RegisterServlet Index: lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/servlet/RecalculateTotalMarksForLessonServlet.java =================================================================== diff -u -r62aaf160878735888d077bf28fac3c1989bb8fbd -r33829c670fd8c90447d62ea3300498a103905e7a --- lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/servlet/RecalculateTotalMarksForLessonServlet.java (.../RecalculateTotalMarksForLessonServlet.java) (revision 62aaf160878735888d077bf28fac3c1989bb8fbd) +++ lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/servlet/RecalculateTotalMarksForLessonServlet.java (.../RecalculateTotalMarksForLessonServlet.java) (revision 33829c670fd8c90447d62ea3300498a103905e7a) @@ -26,6 +26,7 @@ import java.io.IOException; import java.io.PrintWriter; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -41,8 +42,8 @@ import org.lamsfoundation.lams.util.WebUtil; 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; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * Recalculates total marks for all users in a lesson. Then stores that mark in a gradebookUserLesson. Doesn't @@ -55,16 +56,21 @@ private static Logger log = Logger.getLogger(RecalculateTotalMarksForLessonServlet.class); - private static ILogEventService logEventService; - private static ILessonService lessonService; - private static IGradebookFullService gradebookService; + @Autowired + private ILogEventService logEventService; + @Autowired + private ILessonService lessonService; + @Autowired + private IGradebookFullService gradebookService; + /* + * Request Spring to lookup the applicationContext tied to the current ServletContext and inject service beans + * available in that applicationContext. + */ @Override - public void init() throws ServletException { - WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); - logEventService = (ILogEventService) ctx.getBean("logEventService"); - lessonService = (ILessonService) ctx.getBean("lessonService"); - gradebookService = (IGradebookFullService) ctx.getBean("gradebookService"); + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); } @Override