Index: lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/service/VoteService.java =================================================================== diff -u -r9349bab097150a4a15cf4c6c10b7946400c3fbd0 -r8bc11142a6db14da1d00d3fd8adfe7d4938ead15 --- lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/service/VoteService.java (.../VoteService.java) (revision 9349bab097150a4a15cf4c6c10b7946400c3fbd0) +++ lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/service/VoteService.java (.../VoteService.java) (revision 8bc11142a6db14da1d00d3fd8adfe7d4938ead15) @@ -92,7 +92,7 @@ import org.lamsfoundation.lams.tool.vote.util.VoteApplicationException; import org.lamsfoundation.lams.tool.vote.util.VoteComparator; import org.lamsfoundation.lams.tool.vote.util.VoteUtils; -import org.lamsfoundation.lams.tool.vote.web.action.MonitoringController; +import org.lamsfoundation.lams.tool.vote.web.controller.MonitoringController; import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; Fisheye: Tag 8bc11142a6db14da1d00d3fd8adfe7d4938ead15 refers to a dead (removed) revision in file `lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/action/AuthoringController.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 8bc11142a6db14da1d00d3fd8adfe7d4938ead15 refers to a dead (removed) revision in file `lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/action/ClearSessionController.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 8bc11142a6db14da1d00d3fd8adfe7d4938ead15 refers to a dead (removed) revision in file `lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/action/LearningController.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 8bc11142a6db14da1d00d3fd8adfe7d4938ead15 refers to a dead (removed) revision in file `lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/action/MonitoringController.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 8bc11142a6db14da1d00d3fd8adfe7d4938ead15 refers to a dead (removed) revision in file `lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/action/VoteChartGeneratorController.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 8bc11142a6db14da1d00d3fd8adfe7d4938ead15 refers to a dead (removed) revision in file `lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/action/VotePedagogicalPlannerController.java'. Fisheye: No comparison available. Pass `N' to diff? Index: lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/AuthoringController.java =================================================================== diff -u --- lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/AuthoringController.java (revision 0) +++ lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/AuthoringController.java (revision 8bc11142a6db14da1d00d3fd8adfe7d4938ead15) @@ -0,0 +1,1245 @@ +/*************************************************************************** + * 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.tool.vote.web.controller; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.apache.log4j.Logger; +import org.lamsfoundation.lams.authoring.web.AuthoringConstants; +import org.lamsfoundation.lams.learningdesign.DataFlowObject; +import org.lamsfoundation.lams.tool.ToolAccessMode; +import org.lamsfoundation.lams.tool.vote.VoteAppConstants; +import org.lamsfoundation.lams.tool.vote.dto.VoteGeneralAuthoringDTO; +import org.lamsfoundation.lams.tool.vote.dto.VoteQuestionDTO; +import org.lamsfoundation.lams.tool.vote.pojos.VoteContent; +import org.lamsfoundation.lams.tool.vote.pojos.VoteQueContent; +import org.lamsfoundation.lams.tool.vote.service.IVoteService; +import org.lamsfoundation.lams.tool.vote.util.VoteComparator; +import org.lamsfoundation.lams.tool.vote.util.VoteUtils; +import org.lamsfoundation.lams.tool.vote.web.form.VoteAuthoringForm; +import org.lamsfoundation.lams.usermanagement.dto.UserDTO; +import org.lamsfoundation.lams.util.MessageService; +import org.lamsfoundation.lams.util.WebUtil; +import org.lamsfoundation.lams.web.session.SessionManager; +import org.lamsfoundation.lams.web.util.AttributeNames; +import org.lamsfoundation.lams.web.util.SessionMap; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Controller; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/authoring") +public class AuthoringController implements VoteAppConstants { + private static Logger logger = Logger.getLogger(AuthoringController.class.getName()); + + @Autowired + @Qualifier("voteService") + private IVoteService voteService; + + @Autowired + @Qualifier("lavoteMessageService") + private MessageService messageService; + + /** + * repopulateRequestParameters reads and saves request parameters + */ + private static void repopulateRequestParameters(HttpServletRequest request, VoteAuthoringForm voteAuthoringForm, + VoteGeneralAuthoringDTO voteGeneralAuthoringDTO) { + + String toolContentID = request.getParameter(VoteAppConstants.TOOL_CONTENT_ID); + voteAuthoringForm.setToolContentID(toolContentID); + voteGeneralAuthoringDTO.setToolContentID(toolContentID); + + String httpSessionID = request.getParameter(VoteAppConstants.HTTP_SESSION_ID); + voteAuthoringForm.setHttpSessionID(httpSessionID); + voteGeneralAuthoringDTO.setHttpSessionID(httpSessionID); + + String lockOnFinish = request.getParameter(VoteAppConstants.LOCK_ON_FINISH); + voteAuthoringForm.setLockOnFinish(lockOnFinish); + voteGeneralAuthoringDTO.setLockOnFinish(lockOnFinish); + + String useSelectLeaderToolOuput = request.getParameter(VoteAppConstants.USE_SELECT_LEADER_TOOL_OUTPUT); + voteAuthoringForm.setUseSelectLeaderToolOuput(useSelectLeaderToolOuput); + voteGeneralAuthoringDTO.setUseSelectLeaderToolOuput(useSelectLeaderToolOuput); + + String allowText = request.getParameter(VoteAppConstants.ALLOW_TEXT); + voteAuthoringForm.setAllowText(allowText); + voteGeneralAuthoringDTO.setAllowText(allowText); + + String showResults = request.getParameter(VoteAppConstants.SHOW_RESULTS); + voteAuthoringForm.setShowResults(showResults); + voteGeneralAuthoringDTO.setShowResults(showResults); + + String maxNominationCount = request.getParameter(VoteAppConstants.MAX_NOMINATION_COUNT); + voteAuthoringForm.setMaxNominationCount(maxNominationCount); + voteGeneralAuthoringDTO.setMaxNominationCount(maxNominationCount); + + String minNominationCount = request.getParameter(MIN_NOMINATION_COUNT); + voteAuthoringForm.setMinNominationCount(minNominationCount); + voteGeneralAuthoringDTO.setMinNominationCount(minNominationCount); + + String reflect = request.getParameter("reflect"); + voteAuthoringForm.setReflect(reflect); + voteGeneralAuthoringDTO.setReflect(reflect); + + String reflectionSubject = request.getParameter("reflectionSubject"); + voteAuthoringForm.setReflectionSubject(reflectionSubject); + voteGeneralAuthoringDTO.setReflectionSubject(reflectionSubject); + + String maxInputs = request.getParameter(VoteAppConstants.MAX_INPUTS); + if (maxInputs == null) { + logger.info("Since minNomcount is equal to null hence setting it to '0'"); + maxInputs = "0"; + } + voteAuthoringForm.setMaxInputs(new Short(maxInputs)); + + ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request); + request.setAttribute(AttributeNames.ATTR_MODE, mode.toString()); + } + + /** + * moves a nomination down in the authoring list + */ + @RequestMapping(path = "/moveNominationDown", method = RequestMethod.POST) + @SuppressWarnings("unchecked") + public String moveNominationDown(VoteAuthoringForm voteAuthoringForm, HttpServletRequest request) { + String httpSessionID = voteAuthoringForm.getHttpSessionID(); + SessionMap sessionMap = (SessionMap) request.getSession() + .getAttribute(httpSessionID); + + String questionIndex = request.getParameter("questionIndex"); + + List questionDTOs = (List) sessionMap.get(VoteAppConstants.LIST_QUESTION_DTO); + + questionDTOs = AuthoringController.swapQuestions(questionDTOs, questionIndex, "down"); + + questionDTOs = AuthoringController.reorderQuestionDTOs(questionDTOs); + sessionMap.put(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + + String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); + voteAuthoringForm.setContentFolderID(contentFolderID); + + String richTextTitle = request.getParameter(VoteAppConstants.TITLE); + + String richTextInstructions = request.getParameter(VoteAppConstants.INSTRUCTIONS); + + sessionMap.put(VoteAppConstants.ACTIVITY_TITLE_KEY, richTextTitle); + sessionMap.put(VoteAppConstants.ACTIVITY_INSTRUCTIONS_KEY, richTextInstructions); + + String strToolContentID = request.getParameter(AttributeNames.PARAM_TOOL_CONTENT_ID); + + VoteGeneralAuthoringDTO voteGeneralAuthoringDTO = new VoteGeneralAuthoringDTO(); + voteGeneralAuthoringDTO.setContentFolderID(contentFolderID); + + AuthoringController.repopulateRequestParameters(request, voteAuthoringForm, voteGeneralAuthoringDTO); + + voteGeneralAuthoringDTO.setActivityTitle(richTextTitle); + voteAuthoringForm.setTitle(richTextTitle); + + voteGeneralAuthoringDTO.setActivityInstructions(richTextInstructions); + + request.getSession().setAttribute(httpSessionID, sessionMap); + + voteGeneralAuthoringDTO.setToolContentID(strToolContentID); + voteGeneralAuthoringDTO.setHttpSessionID(httpSessionID); + voteAuthoringForm.setToolContentID(strToolContentID); + voteAuthoringForm.setHttpSessionID(httpSessionID); + voteAuthoringForm.setCurrentTab("1"); + + request.setAttribute(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + + return "/authoring/AuthoringMaincontent"; + } + + /** + * moves a nomination up in the authoring list + */ + @RequestMapping(path = "/moveNominationUp", method = RequestMethod.POST) + @SuppressWarnings("unchecked") + public String moveNominationUp(VoteAuthoringForm voteAuthoringForm, HttpServletRequest request) { + String httpSessionID = voteAuthoringForm.getHttpSessionID(); + SessionMap sessionMap = (SessionMap) request.getSession() + .getAttribute(httpSessionID); + + String questionIndex = request.getParameter("questionIndex"); + + List questionDTOs = (List) sessionMap.get(VoteAppConstants.LIST_QUESTION_DTO); + + questionDTOs = AuthoringController.swapQuestions(questionDTOs, questionIndex, "up"); + + questionDTOs = AuthoringController.reorderQuestionDTOs(questionDTOs); + + sessionMap.put(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + + String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); + voteAuthoringForm.setContentFolderID(contentFolderID); + + String richTextTitle = request.getParameter(VoteAppConstants.TITLE); + + String richTextInstructions = request.getParameter(VoteAppConstants.INSTRUCTIONS); + + sessionMap.put(VoteAppConstants.ACTIVITY_TITLE_KEY, richTextTitle); + sessionMap.put(VoteAppConstants.ACTIVITY_INSTRUCTIONS_KEY, richTextInstructions); + + String strToolContentID = request.getParameter(AttributeNames.PARAM_TOOL_CONTENT_ID); + + VoteGeneralAuthoringDTO voteGeneralAuthoringDTO = new VoteGeneralAuthoringDTO(); + voteGeneralAuthoringDTO.setContentFolderID(contentFolderID); + + AuthoringController.repopulateRequestParameters(request, voteAuthoringForm, voteGeneralAuthoringDTO); + + voteGeneralAuthoringDTO.setActivityTitle(richTextTitle); + voteAuthoringForm.setTitle(richTextTitle); + + voteGeneralAuthoringDTO.setActivityInstructions(richTextInstructions); + + request.getSession().setAttribute(httpSessionID, sessionMap); + + voteGeneralAuthoringDTO.setToolContentID(strToolContentID); + voteGeneralAuthoringDTO.setHttpSessionID(httpSessionID); + voteAuthoringForm.setToolContentID(strToolContentID); + voteAuthoringForm.setHttpSessionID(httpSessionID); + voteAuthoringForm.setCurrentTab("1"); + + request.setAttribute(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + return "/authoring/AuthoringMaincontent"; + } + + /** + * removes a nomination from the authoring list + */ + @RequestMapping(path = "/removeNomination", method = RequestMethod.POST) + @SuppressWarnings("unchecked") + public String removeNomination(VoteAuthoringForm voteAuthoringForm, HttpServletRequest request) { + String httpSessionID = voteAuthoringForm.getHttpSessionID(); + SessionMap sessionMap = (SessionMap) request.getSession() + .getAttribute(httpSessionID); + + String questionIndexToDelete = request.getParameter("questionIndex"); + logger.info("Question Index to delete" + questionIndexToDelete); + List questionDTOs = (List) sessionMap.get(VoteAppConstants.LIST_QUESTION_DTO); + + List listFinalQuestionDTO = new LinkedList<>(); + int queIndex = 0; + for (VoteQuestionDTO questionDTO : questionDTOs) { + + String questionText = questionDTO.getNomination(); + String displayOrder = questionDTO.getDisplayOrder(); + + if (questionText != null && !questionText.equals("") && (!displayOrder.equals(questionIndexToDelete))) { + + ++queIndex; + questionDTO.setDisplayOrder(new Integer(queIndex).toString()); + listFinalQuestionDTO.add(questionDTO); + } + if ((questionText != null) && (!questionText.isEmpty()) && displayOrder.equals(questionIndexToDelete)) { + List deletedQuestionDTOs = (List) sessionMap + .get(LIST_DELETED_QUESTION_DTOS); + ; + deletedQuestionDTOs.add(questionDTO); + sessionMap.put(LIST_DELETED_QUESTION_DTOS, deletedQuestionDTOs); + } + } + + sessionMap.put(VoteAppConstants.LIST_QUESTION_DTO, listFinalQuestionDTO); + request.setAttribute(VoteAppConstants.LIST_QUESTION_DTO, listFinalQuestionDTO); + + String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); + voteAuthoringForm.setContentFolderID(contentFolderID); + + String richTextTitle = request.getParameter(VoteAppConstants.TITLE); + String richTextInstructions = request.getParameter(VoteAppConstants.INSTRUCTIONS); + + sessionMap.put(VoteAppConstants.ACTIVITY_TITLE_KEY, richTextTitle); + sessionMap.put(VoteAppConstants.ACTIVITY_INSTRUCTIONS_KEY, richTextInstructions); + + String strToolContentID = request.getParameter(AttributeNames.PARAM_TOOL_CONTENT_ID); + + VoteGeneralAuthoringDTO voteGeneralAuthoringDTO = new VoteGeneralAuthoringDTO(); + voteGeneralAuthoringDTO.setContentFolderID(contentFolderID); + + AuthoringController.repopulateRequestParameters(request, voteAuthoringForm, voteGeneralAuthoringDTO); + + voteGeneralAuthoringDTO.setActivityTitle(richTextTitle); + voteAuthoringForm.setTitle(richTextTitle); + + voteGeneralAuthoringDTO.setActivityInstructions(richTextInstructions); + + request.getSession().setAttribute(httpSessionID, sessionMap); + + voteGeneralAuthoringDTO.setToolContentID(strToolContentID); + voteGeneralAuthoringDTO.setHttpSessionID(httpSessionID); + voteAuthoringForm.setToolContentID(strToolContentID); + voteAuthoringForm.setHttpSessionID(httpSessionID); + voteAuthoringForm.setCurrentTab("1"); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + + return "/authoring/AuthoringMaincontent"; + } + + /** + * enables editing a nomination + */ + @RequestMapping("/newEditableNominationBox") + @SuppressWarnings("unchecked") + public String newEditableNominationBox(VoteAuthoringForm voteAuthoringForm, HttpServletRequest request) { + + String httpSessionID = voteAuthoringForm.getHttpSessionID(); + + SessionMap sessionMap = (SessionMap) request.getSession() + .getAttribute(httpSessionID); + + String questionIndex = request.getParameter("questionIndex"); + logger.info("Question Index" + questionIndex); + voteAuthoringForm.setEditableNominationIndex(questionIndex); + + List questionDTOs = (List) sessionMap.get(VoteAppConstants.LIST_QUESTION_DTO); + + String editableNomination = ""; + Iterator iter = questionDTOs.iterator(); + while (iter.hasNext()) { + VoteQuestionDTO voteQuestionDTO = iter.next(); + // String question = voteQuestionDTO.getNomination(); + String displayOrder = voteQuestionDTO.getDisplayOrder(); + + if (displayOrder != null && !displayOrder.equals("")) { + if (displayOrder.equals(questionIndex)) { + editableNomination = voteQuestionDTO.getNomination(); + break; + } + + } + } + String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); + voteAuthoringForm.setContentFolderID(contentFolderID); + + VoteGeneralAuthoringDTO voteGeneralAuthoringDTO = new VoteGeneralAuthoringDTO(); + voteGeneralAuthoringDTO.setContentFolderID(contentFolderID); + + AuthoringController.repopulateRequestParameters(request, voteAuthoringForm, voteGeneralAuthoringDTO); + + String richTextTitle = request.getParameter(VoteAppConstants.TITLE); + String richTextInstructions = request.getParameter(VoteAppConstants.INSTRUCTIONS); + + voteGeneralAuthoringDTO.setActivityTitle(richTextTitle); + voteAuthoringForm.setTitle(richTextTitle); + voteGeneralAuthoringDTO.setActivityInstructions(richTextInstructions); + + voteGeneralAuthoringDTO.setEditableNominationText(editableNomination); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + + return "/authoring/editNominationBox"; + } + + /** + * enables adding a new nomination + */ + @RequestMapping("/newNominationBox") + public String newNominationBox(VoteAuthoringForm voteAuthoringForm, HttpServletRequest request) { + String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); + voteAuthoringForm.setContentFolderID(contentFolderID); + + VoteGeneralAuthoringDTO voteGeneralAuthoringDTO = new VoteGeneralAuthoringDTO(); + voteGeneralAuthoringDTO.setContentFolderID(contentFolderID); + + AuthoringController.repopulateRequestParameters(request, voteAuthoringForm, voteGeneralAuthoringDTO); + + String richTextTitle = request.getParameter(VoteAppConstants.TITLE); + String richTextInstructions = request.getParameter(VoteAppConstants.INSTRUCTIONS); + + voteGeneralAuthoringDTO.setActivityTitle(richTextTitle); + voteAuthoringForm.setTitle(richTextTitle); + + voteGeneralAuthoringDTO.setActivityInstructions(richTextInstructions); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + + return "/authoring/newNominationBox"; + } + + /** + * enables adding a new nomination to the authoring nominations list + */ + @RequestMapping(path = "/addSingleNomination", method = RequestMethod.POST) + @SuppressWarnings("unchecked") + public String addSingleNomination(VoteAuthoringForm voteAuthoringForm, HttpServletRequest request) { + String httpSessionID = voteAuthoringForm.getHttpSessionID(); + + SessionMap sessionMap = (SessionMap) request.getSession() + .getAttribute(httpSessionID); + String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); + voteAuthoringForm.setContentFolderID(contentFolderID); + + String strToolContentID = request.getParameter(AttributeNames.PARAM_TOOL_CONTENT_ID); + + VoteGeneralAuthoringDTO voteGeneralAuthoringDTO = new VoteGeneralAuthoringDTO(); + voteGeneralAuthoringDTO.setContentFolderID(contentFolderID); + + AuthoringController.repopulateRequestParameters(request, voteAuthoringForm, voteGeneralAuthoringDTO); + + List questionDTOs = (List) sessionMap.get(VoteAppConstants.LIST_QUESTION_DTO); + + String newNomination = request.getParameter("newNomination"); + + int listSize = questionDTOs.size(); + + if (newNomination != null && newNomination.length() > 0) { + boolean duplicates = AuthoringController.checkDuplicateNominations(questionDTOs, newNomination); + + if (!duplicates) { + VoteQuestionDTO voteQuestionDTO = new VoteQuestionDTO(); + voteQuestionDTO.setDisplayOrder(new Long(listSize + 1).toString()); + voteQuestionDTO.setNomination(newNomination); + + questionDTOs.add(voteQuestionDTO); + } + } + + request.setAttribute(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + sessionMap.put(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + + String richTextTitle = (String) sessionMap.get(VoteAppConstants.ACTIVITY_TITLE_KEY); + String richTextInstructions = (String) sessionMap.get(VoteAppConstants.ACTIVITY_INSTRUCTIONS_KEY); + + voteGeneralAuthoringDTO.setActivityTitle(richTextTitle); + voteAuthoringForm.setTitle(richTextTitle); + voteGeneralAuthoringDTO.setActivityInstructions(richTextInstructions); + + request.getSession().setAttribute(httpSessionID, sessionMap); + + voteGeneralAuthoringDTO.setToolContentID(strToolContentID); + voteGeneralAuthoringDTO.setHttpSessionID(httpSessionID); + + voteAuthoringForm.setToolContentID(strToolContentID); + voteAuthoringForm.setHttpSessionID(httpSessionID); + voteAuthoringForm.setCurrentTab("1"); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + + request.getSession().setAttribute(httpSessionID, sessionMap); + + return "/authoring/itemlist"; + } + + /** + * saves a new or updated nomination in the authoring nominations list + */ + @RequestMapping(path = "/saveSingleNomination", method = RequestMethod.POST) + @SuppressWarnings("unchecked") + public String saveSingleNomination(VoteAuthoringForm voteAuthoringForm, HttpServletRequest request) { + String httpSessionID = voteAuthoringForm.getHttpSessionID(); + + SessionMap sessionMap = (SessionMap) request.getSession() + .getAttribute(httpSessionID); + + String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); + voteAuthoringForm.setContentFolderID(contentFolderID); + + String strToolContentID = request.getParameter(AttributeNames.PARAM_TOOL_CONTENT_ID); + + String editNominationBoxRequest = request.getParameter("editNominationBoxRequest"); + + logger.info("Edit nomination box request" + editNominationBoxRequest); + + VoteGeneralAuthoringDTO voteGeneralAuthoringDTO = new VoteGeneralAuthoringDTO(); + + voteGeneralAuthoringDTO.setContentFolderID(contentFolderID); + + AuthoringController.repopulateRequestParameters(request, voteAuthoringForm, voteGeneralAuthoringDTO); + + List questionDTOs = (List) sessionMap.get(VoteAppConstants.LIST_QUESTION_DTO); + + String newNomination = request.getParameter("newNomination"); + + String editableNominationIndex = request.getParameter("editableNominationIndex"); + + if (newNomination != null && newNomination.length() > 0) { + if (editNominationBoxRequest != null && editNominationBoxRequest.equals("false")) { + boolean duplicates = AuthoringController.checkDuplicateNominations(questionDTOs, newNomination); + + if (!duplicates) { + VoteQuestionDTO voteQuestionDTO = null; + Iterator iter = questionDTOs.iterator(); + while (iter.hasNext()) { + voteQuestionDTO = iter.next(); + + //String question = voteQuestionDTO.getNomination(); + String displayOrder = voteQuestionDTO.getDisplayOrder(); + + if (displayOrder != null && !displayOrder.equals("")) { + if (displayOrder.equals(editableNominationIndex)) { + break; + } + + } + } + + voteQuestionDTO.setQuestion(newNomination); + voteQuestionDTO.setDisplayOrder(editableNominationIndex); + + questionDTOs = AuthoringController.reorderUpdateListQuestionDTO(questionDTOs, voteQuestionDTO, + editableNominationIndex); + } else { + logger.info("Duplicate question entry therefore not adding"); + //duplicate question entry, not adding + } + } else { + logger.info("In Request for Save and Edit"); + //request for edit and save + VoteQuestionDTO voteQuestionDTO = null; + Iterator iter = questionDTOs.iterator(); + while (iter.hasNext()) { + voteQuestionDTO = iter.next(); + + // String question = voteQuestionDTO.getNomination(); + String displayOrder = voteQuestionDTO.getDisplayOrder(); + + if (displayOrder != null && !displayOrder.equals("")) { + if (displayOrder.equals(editableNominationIndex)) { + break; + } + + } + } + + voteQuestionDTO.setNomination(newNomination); + voteQuestionDTO.setDisplayOrder(editableNominationIndex); + + questionDTOs = AuthoringController.reorderUpdateListQuestionDTO(questionDTOs, voteQuestionDTO, + editableNominationIndex); + } + } else { + logger.info("newNomination entry is blank,therefore not adding"); + //entry blank, not adding + } + + request.setAttribute(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + sessionMap.put(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + + String richTextTitle = (String) sessionMap.get(VoteAppConstants.ACTIVITY_TITLE_KEY); + String richTextInstructions = (String) sessionMap.get(VoteAppConstants.ACTIVITY_INSTRUCTIONS_KEY); + + voteGeneralAuthoringDTO.setActivityTitle(richTextTitle); + voteAuthoringForm.setTitle(richTextTitle); + voteGeneralAuthoringDTO.setActivityInstructions(richTextInstructions); + + request.getSession().setAttribute(httpSessionID, sessionMap); + + voteGeneralAuthoringDTO.setToolContentID(strToolContentID); + voteGeneralAuthoringDTO.setHttpSessionID(httpSessionID); + + voteAuthoringForm.setToolContentID(strToolContentID); + voteAuthoringForm.setHttpSessionID(httpSessionID); + voteAuthoringForm.setCurrentTab("1"); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + + request.getSession().setAttribute(httpSessionID, sessionMap); + + return "/authoring/itemlist"; + } + + /** + * persists the nominations list and other user selections in the db. + */ + @RequestMapping(path = "/submitAllContent", method = RequestMethod.POST) + @SuppressWarnings("unchecked") + public String submitAllContent(VoteAuthoringForm voteAuthoringForm, HttpServletRequest request) { + String httpSessionID = voteAuthoringForm.getHttpSessionID(); + + SessionMap sessionMap = (SessionMap) request.getSession() + .getAttribute(httpSessionID); + + String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); + voteAuthoringForm.setContentFolderID(contentFolderID); + + String strToolContentID = request.getParameter(AttributeNames.PARAM_TOOL_CONTENT_ID); + + List questionDTOs = (List) sessionMap.get(VoteAppConstants.LIST_QUESTION_DTO); + + MultiValueMap errorMap = new LinkedMultiValueMap<>(); + if (questionDTOs.isEmpty() && (voteAuthoringForm.getAssignedDataFlowObject() == null + || voteAuthoringForm.getAssignedDataFlowObject() == 0)) { + errorMap.add("nominations", messageService.getMessage("nominations.none.submitted")); + logger.error("Nominations not submitted"); + } + + String maxNomCount = voteAuthoringForm.getMaxNominationCount(); + if (maxNomCount != null) { + if (maxNomCount.equals("0") || maxNomCount.contains("-")) { + errorMap.add("maxNominationCount", messageService.getMessage("maxNomination.invalid")); + logger.error("Maximum votes in Advance tab is invalid"); + } + + try { + //int intMaxNomCount = new Integer(maxNomCount).intValue(); + } catch (NumberFormatException e) { + errorMap.add("maxNominationCount", messageService.getMessage("maxNomination.invalid")); + logger.error("Maximum votes in Advance tab is invalid"); + } + } + + //verifyDuplicateNominations + Map mapQuestion = AuthoringController.extractMapQuestion(questionDTOs); + int optionCount = 0; + boolean isNominationsDuplicate = false; + for (long i = 1; i <= VoteAppConstants.MAX_OPTION_COUNT; i++) { + String currentOption = mapQuestion.get(new Long(i).toString()); + + optionCount = 0; + for (long j = 1; j <= VoteAppConstants.MAX_OPTION_COUNT; j++) { + String backedOption = mapQuestion.get(new Long(j).toString()); + + if (currentOption != null && backedOption != null) { + if (currentOption.equals(backedOption)) { + optionCount++; + } + + if (optionCount > 1) { + isNominationsDuplicate = true; + } + } + } + } + + if (isNominationsDuplicate == true) { + errorMap.add("nominations", messageService.getMessage("nominations.duplicate")); + logger.error("There are duplicate nomination entries."); + } + + VoteGeneralAuthoringDTO voteGeneralAuthoringDTO = new VoteGeneralAuthoringDTO(); + AuthoringController.repopulateRequestParameters(request, voteAuthoringForm, voteGeneralAuthoringDTO); + + DataFlowObject assignedDataFlowObject = null; + + List dataFlowObjects = voteService.getDataFlowObjects(new Long(strToolContentID)); + List dataFlowObjectNames = null; + if (dataFlowObjects != null) { + dataFlowObjectNames = new ArrayList<>(dataFlowObjects.size()); + int objectIndex = 1; + for (DataFlowObject dataFlowObject : dataFlowObjects) { + dataFlowObjectNames.add(dataFlowObject.getDisplayName()); + if (VoteAppConstants.DATA_FLOW_OBJECT_ASSIGMENT_ID.equals(dataFlowObject.getToolAssigmentId())) { + voteAuthoringForm.setAssignedDataFlowObject(objectIndex); + } + objectIndex++; + + } + } + voteGeneralAuthoringDTO.setDataFlowObjectNames(dataFlowObjectNames); + + if (voteAuthoringForm.getAssignedDataFlowObject() != null + && voteAuthoringForm.getAssignedDataFlowObject() != 0) { + assignedDataFlowObject = dataFlowObjects.get(voteAuthoringForm.getAssignedDataFlowObject() - 1); + } + + voteGeneralAuthoringDTO.setContentFolderID(contentFolderID); + + String richTextTitle = request.getParameter(VoteAppConstants.TITLE); + String richTextInstructions = request.getParameter(VoteAppConstants.INSTRUCTIONS); + + voteGeneralAuthoringDTO.setActivityTitle(richTextTitle); + voteAuthoringForm.setTitle(richTextTitle); + + voteGeneralAuthoringDTO.setActivityInstructions(richTextInstructions); + + sessionMap.put(VoteAppConstants.ACTIVITY_TITLE_KEY, richTextTitle); + sessionMap.put(VoteAppConstants.ACTIVITY_INSTRUCTIONS_KEY, richTextInstructions); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + + VoteContent voteContentTest = voteService.getVoteContent(new Long(strToolContentID)); + + if (errorMap.isEmpty()) { + ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request); + request.setAttribute(AttributeNames.ATTR_MODE, mode.toString()); + + List deletedQuestionDTOs = (List) sessionMap + .get(LIST_DELETED_QUESTION_DTOS); + + // in case request is from monitoring module - recalculate User Answers + if (mode.isTeacher()) { + Set oldQuestions = voteContentTest.getVoteQueContents(); + voteService.removeQuestionsFromCache(voteContentTest); + VoteUtils.setDefineLater(request, false, strToolContentID, voteService); + + // audit log the teacher has started editing activity in monitor + voteService.auditLogStartEditingActivityInMonitor(new Long(strToolContentID)); + + // recalculate User Answers + voteService.recalculateUserAnswers(voteContentTest, oldQuestions, questionDTOs, deletedQuestionDTOs); + } + + // remove deleted questions + for (VoteQuestionDTO deletedQuestionDTO : deletedQuestionDTOs) { + VoteQueContent removeableQuestion = voteService.getVoteQueContentByUID(deletedQuestionDTO.getUid()); + if (removeableQuestion != null) { +// Set attempts = removeableQuestion.getMcUsrAttempts(); +// Iterator iter = attempts.iterator(); +// while (iter.hasNext()) { +// McUsrAttempt attempt = iter.next(); +// iter.remove(); +// } +// mcService.updateQuestion(removeableQuestion); + voteContentTest.getVoteQueContents().remove(removeableQuestion); + voteService.removeVoteQueContent(removeableQuestion); + } + } + + // store content + VoteContent voteContent = saveOrUpdateVoteContent(voteAuthoringForm, request, voteContentTest, + strToolContentID); + + //store questions + voteContent = voteService.createQuestions(questionDTOs, voteContent); + + //store DataFlowObjectAssigment + voteService.saveDataFlowObjectAssigment(assignedDataFlowObject); + + //reOrganizeDisplayOrder + List sortedQuestions = voteService.getAllQuestionsSorted(voteContent.getUid().longValue()); + Iterator iter = sortedQuestions.iterator(); + while (iter.hasNext()) { + VoteQueContent question = iter.next(); + + VoteQueContent existingQuestion = voteService.getQuestionByUid(question.getUid()); + voteService.saveOrUpdateVoteQueContent(existingQuestion); + } + + // standard authoring close + request.setAttribute(AuthoringConstants.LAMS_AUTHORING_SUCCESS_FLAG, Boolean.TRUE); + + } else { + request.setAttribute("errorMap", errorMap); + } + + voteAuthoringForm.resetUserAction(); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + + request.setAttribute(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + sessionMap.put(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + request.getSession().setAttribute(httpSessionID, sessionMap); + + voteGeneralAuthoringDTO.setToolContentID(strToolContentID); + voteGeneralAuthoringDTO.setHttpSessionID(httpSessionID); + + voteAuthoringForm.setToolContentID(strToolContentID); + voteAuthoringForm.setHttpSessionID(httpSessionID); + voteAuthoringForm.setCurrentTab("1"); + + return "/authoring/AuthoringMaincontent"; + } + + @RequestMapping("/start") + public String start(VoteAuthoringForm voteAuthoringForm, HttpServletRequest request) { + VoteGeneralAuthoringDTO voteGeneralAuthoringDTO = new VoteGeneralAuthoringDTO(); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + // model.addAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + + String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); + voteAuthoringForm.setContentFolderID(contentFolderID); + + AuthoringController.repopulateRequestParameters(request, voteAuthoringForm, voteGeneralAuthoringDTO); + + voteGeneralAuthoringDTO.setContentFolderID(contentFolderID); + + SessionMap sessionMap = new SessionMap<>(); + voteAuthoringForm.setHttpSessionID(sessionMap.getSessionID()); + voteGeneralAuthoringDTO.setHttpSessionID(sessionMap.getSessionID()); + request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); + + voteAuthoringForm.resetRadioBoxes(); + voteAuthoringForm.setExceptionMaxNominationInvalid(new Boolean(false).toString()); + voteGeneralAuthoringDTO.setExceptionMaxNominationInvalid(new Boolean(false).toString()); + + MultiValueMap errorMap = new LinkedMultiValueMap<>(); + boolean validateSignature = validateDefaultContent(voteAuthoringForm, errorMap); + if (!validateSignature) { + request.setAttribute("errorMap", errorMap); + return "/error"; + } + + //no problems getting the default content, will render authoring screen + + /* the authoring url must be passed a tool content id */ + String strToolContentId = request.getParameter(AttributeNames.PARAM_TOOL_CONTENT_ID); + voteAuthoringForm.setToolContentID(new Long(strToolContentId).toString()); + voteGeneralAuthoringDTO.setToolContentID(new Long(strToolContentId).toString()); + + if (strToolContentId == null || strToolContentId.equals("")) { + errorMap.add("GLOBAL", messageService.getMessage("error.contentId.required")); + request.setAttribute("errorMap", errorMap); + return "/error"; + } + + ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request); + // request is from monitoring module + if (mode.isTeacher()) { + VoteUtils.setDefineLater(request, true, strToolContentId, voteService); + } + request.setAttribute(AttributeNames.ATTR_MODE, mode.toString()); + + VoteContent voteContent = voteService.getVoteContent(new Long(strToolContentId)); + + // if mcContent does not exist, try to use default content instead. + if (voteContent == null) { + long defaultContentID = voteService.getToolDefaultContentIdBySignature(VoteAppConstants.MY_SIGNATURE); + voteContent = voteService.getVoteContent(defaultContentID); + voteContent = VoteContent.newInstance(voteContent, new Long(strToolContentId)); + } + + AuthoringController.prepareDTOandForm(request, voteContent, voteAuthoringForm, voteGeneralAuthoringDTO); + if (voteContent.getTitle() == null) { + voteGeneralAuthoringDTO.setActivityTitle(VoteAppConstants.DEFAULT_VOTING_TITLE); + voteAuthoringForm.setTitle(VoteAppConstants.DEFAULT_VOTING_TITLE); + } else { + voteGeneralAuthoringDTO.setActivityTitle(voteContent.getTitle()); + voteAuthoringForm.setTitle(voteContent.getTitle()); + } + + if (voteContent.getInstructions() == null) { + voteGeneralAuthoringDTO.setActivityInstructions(VoteAppConstants.DEFAULT_VOTING_INSTRUCTIONS); + voteAuthoringForm.setInstructions(VoteAppConstants.DEFAULT_VOTING_INSTRUCTIONS); + } else { + voteGeneralAuthoringDTO.setActivityInstructions(voteContent.getInstructions()); + voteAuthoringForm.setInstructions(voteContent.getInstructions()); + } + + sessionMap.put(VoteAppConstants.ACTIVITY_TITLE_KEY, voteGeneralAuthoringDTO.getActivityTitle()); + sessionMap.put(VoteAppConstants.ACTIVITY_INSTRUCTIONS_KEY, voteGeneralAuthoringDTO.getActivityInstructions()); + + voteAuthoringForm.setReflectionSubject(voteContent.getReflectionSubject()); + voteGeneralAuthoringDTO.setReflectionSubject(voteContent.getReflectionSubject()); + + List dataFlowObjects = voteService.getDataFlowObjects(new Long(strToolContentId)); + if (dataFlowObjects != null) { + List dataFlowObjectNames = new ArrayList<>(dataFlowObjects.size()); + int objectIndex = 1; + for (DataFlowObject dataFlowObject : dataFlowObjects) { + dataFlowObjectNames.add(dataFlowObject.getDisplayName()); + if (VoteAppConstants.DATA_FLOW_OBJECT_ASSIGMENT_ID.equals(dataFlowObject.getToolAssigmentId())) { + voteAuthoringForm.setAssignedDataFlowObject(objectIndex); + } + objectIndex++; + + } + voteGeneralAuthoringDTO.setDataFlowObjectNames(dataFlowObjectNames); + } + + List questionDTOs = new LinkedList<>(); + + for (VoteQueContent question : voteContent.getVoteQueContents()) { + VoteQuestionDTO questionDTO = new VoteQuestionDTO(); + + questionDTO.setUid(question.getUid()); + questionDTO.setQuestion(question.getQuestion()); + questionDTO.setDisplayOrder(new Integer(question.getDisplayOrder()).toString()); + questionDTOs.add(questionDTO); + } + + request.setAttribute(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + sessionMap.put(VoteAppConstants.LIST_QUESTION_DTO, questionDTOs); + + Short maxInputs = voteContent.getMaxExternalInputs(); + if (maxInputs == null) { + maxInputs = 0; + } + voteAuthoringForm.setMaxInputs(maxInputs); + voteAuthoringForm.resetUserAction(); + + List listDeletedQuestionDTOs = new ArrayList<>(); + sessionMap.put(VoteAppConstants.LIST_DELETED_QUESTION_DTOS, listDeletedQuestionDTOs); + + voteAuthoringForm.resetUserAction(); + voteAuthoringForm.setCurrentTab("1"); + + return "/authoring/AuthoringMaincontent"; + } + + /** + * each tool has a signature. Voting tool's signature is stored in MY_SIGNATURE. The default tool content id and + * other depending content ids are obtained in this method. if all the default content has been setup properly the + * method saves DEFAULT_CONTENT_ID in the session. + * + * @param request + * @param mapping + * @return ActionForward + */ + private boolean validateDefaultContent(VoteAuthoringForm voteAuthoringForm, + MultiValueMap errorMap) { + /* + * retrieve the default content id based on tool signature + */ + long defaultContentID = 0; + try { + defaultContentID = voteService.getToolDefaultContentIdBySignature(VoteAppConstants.MY_SIGNATURE); + if (defaultContentID == 0) { + logger.error("Exception occured: No default content"); + errorMap.add("GLOBAL", messageService.getMessage("error.defaultContent.notSetup")); + return false; + } + } catch (Exception e) { + logger.error("error getting the default content id: " + e.getMessage()); + errorMap.add("GLOBAL", messageService.getMessage("error.defaultContent.notSetup")); + return false; + } + + try { + //retrieve uid of the content based on default content id determined above defaultContentID + VoteContent voteContent = voteService.getVoteContent(new Long(defaultContentID)); + if (voteContent == null) { + logger.error("Exception occured: No default content"); + errorMap.add("GLOBAL", messageService.getMessage("error.defaultContent.notSetup")); + return false; + } + } catch (Exception e) { + logger.error("other problems: " + e); + logger.error("Exception occured: No default question content"); + errorMap.add("GLOBAL", messageService.getMessage("error.defaultContent.notSetup")); + return false; + } + + return true; + } + + private static void prepareDTOandForm(HttpServletRequest request, VoteContent voteContent, + VoteAuthoringForm voteAuthoringForm, VoteGeneralAuthoringDTO voteGeneralAuthoringDTO) { + + voteGeneralAuthoringDTO.setActivityTitle(voteContent.getTitle()); + voteGeneralAuthoringDTO.setActivityInstructions(voteContent.getInstructions()); + + voteAuthoringForm.setUseSelectLeaderToolOuput(voteContent.isUseSelectLeaderToolOuput() ? "1" : "0"); + voteAuthoringForm.setAllowText(voteContent.isAllowText() ? "1" : "0"); + voteAuthoringForm.setAllowTextEntry(voteContent.isAllowText() ? "1" : "0"); + + voteAuthoringForm.setShowResults(voteContent.isShowResults() ? "1" : "0"); + + voteAuthoringForm.setLockOnFinish(voteContent.isLockOnFinish() ? "1" : "0"); + voteAuthoringForm.setReflect(voteContent.isReflect() ? "1" : "0"); + + voteGeneralAuthoringDTO.setUseSelectLeaderToolOuput(voteContent.isUseSelectLeaderToolOuput() ? "1" : "0"); + voteGeneralAuthoringDTO.setAllowText(voteContent.isAllowText() ? "1" : "0"); + voteGeneralAuthoringDTO.setLockOnFinish(voteContent.isLockOnFinish() ? "1" : "0"); + voteAuthoringForm.setReflect(voteContent.isReflect() ? "1" : "0"); + + String maxNomcount = voteContent.getMaxNominationCount(); + if (maxNomcount.equals("")) { + logger.info("Since minNomcount is equal to null hence setting it to '0'"); + maxNomcount = "0"; + } + voteAuthoringForm.setMaxNominationCount(maxNomcount); + voteGeneralAuthoringDTO.setMaxNominationCount(maxNomcount); + + String minNomcount = voteContent.getMinNominationCount(); + if ((minNomcount == null) || minNomcount.equals("")) { + logger.info("Since minNomcount is equal to null hence setting it to '0'"); + minNomcount = "0"; + } + voteAuthoringForm.setMinNominationCount(minNomcount); + voteGeneralAuthoringDTO.setMinNominationCount(minNomcount); + } + + private static List swapQuestions(List questionDTOs, String questionIndex, + String direction) { + + int intQuestionIndex = new Integer(questionIndex).intValue(); + int intOriginalQuestionIndex = intQuestionIndex; + + int replacedQuestionIndex = 0; + if (direction.equals("down")) { + replacedQuestionIndex = ++intQuestionIndex; + } else { + replacedQuestionIndex = --intQuestionIndex; + } + + VoteQuestionDTO mainQuestion = AuthoringController.getQuestionAtDisplayOrder(questionDTOs, + intOriginalQuestionIndex); + + VoteQuestionDTO replacedQuestion = AuthoringController.getQuestionAtDisplayOrder(questionDTOs, + replacedQuestionIndex); + + List newQuestionDtos = new LinkedList(); + + Iterator iter = questionDTOs.iterator(); + while (iter.hasNext()) { + VoteQuestionDTO questionDTO = iter.next(); + VoteQuestionDTO tempQuestion = new VoteQuestionDTO(); + + if (!questionDTO.getDisplayOrder().equals(new Integer(intOriginalQuestionIndex).toString()) + && !questionDTO.getDisplayOrder().equals(new Integer(replacedQuestionIndex).toString())) { + logger.info("Normal Copy"); + // normal copy + tempQuestion = questionDTO; + + } else if (questionDTO.getDisplayOrder().equals(new Integer(intOriginalQuestionIndex).toString())) { + // move type 1 + logger.info("Move type 1"); + tempQuestion = replacedQuestion; + + } else if (questionDTO.getDisplayOrder().equals(new Integer(replacedQuestionIndex).toString())) { + // move type 1 + logger.info("Move type 1"); + tempQuestion = mainQuestion; + } + + newQuestionDtos.add(tempQuestion); + } + + return newQuestionDtos; + } + + private static VoteQuestionDTO getQuestionAtDisplayOrder(List questionDTOs, + int intOriginalQuestionIndex) { + + Iterator iter = questionDTOs.iterator(); + while (iter.hasNext()) { + VoteQuestionDTO voteQuestionDTO = iter.next(); + + if (new Integer(intOriginalQuestionIndex).toString().equals(voteQuestionDTO.getDisplayOrder())) { + return voteQuestionDTO; + } + } + return null; + } + + private static List reorderQuestionDTOs(List listQuestionDTO) { + List listFinalQuestionDTO = new LinkedList(); + + int queIndex = 0; + Iterator iter = listQuestionDTO.iterator(); + while (iter.hasNext()) { + VoteQuestionDTO voteQuestionDTO = iter.next(); + + String question = voteQuestionDTO.getNomination(); + + // String displayOrder = voteQuestionDTO.getDisplayOrder(); + + if (question != null && !question.equals("")) { + ++queIndex; + + voteQuestionDTO.setNomination(question); + voteQuestionDTO.setDisplayOrder(new Integer(queIndex).toString()); + + listFinalQuestionDTO.add(voteQuestionDTO); + } + } + + return listFinalQuestionDTO; + } + + @SuppressWarnings("rawtypes") + private static boolean checkDuplicateNominations(List listQuestionDTO, String newQuestion) { + if (logger.isDebugEnabled()) { + logger.debug("New Question" + newQuestion); + } + + Map mapQuestion = AuthoringController.extractMapQuestion(listQuestionDTO); + + Iterator itMap = mapQuestion.entrySet().iterator(); + while (itMap.hasNext()) { + Map.Entry pairs = (Map.Entry) itMap.next(); + if (pairs.getValue() != null && !pairs.getValue().equals("")) { + + if (pairs.getValue().equals(newQuestion)) { + return true; + } + } + } + return false; + } + + private static Map extractMapQuestion(List listQuestionDTO) { + Map mapQuestion = new TreeMap(new VoteComparator()); + + Iterator iter = listQuestionDTO.iterator(); + int queIndex = 0; + while (iter.hasNext()) { + VoteQuestionDTO voteQuestionDTO = iter.next(); + + queIndex++; + mapQuestion.put(new Integer(queIndex).toString(), voteQuestionDTO.getNomination()); + } + return mapQuestion; + } + + private static List reorderUpdateListQuestionDTO(List listQuestionDTO, + VoteQuestionDTO voteQuestionDTONew, String editableQuestionIndex) { + + List listFinalQuestionDTO = new LinkedList(); + + Iterator iter = listQuestionDTO.iterator(); + while (iter.hasNext()) { + VoteQuestionDTO voteQuestionDTO = iter.next(); + + String question = voteQuestionDTO.getNomination(); + + String displayOrder = voteQuestionDTO.getDisplayOrder(); + + if (displayOrder.equals(editableQuestionIndex)) { + voteQuestionDTO.setNomination(voteQuestionDTONew.getNomination()); + voteQuestionDTO.setDisplayOrder(voteQuestionDTONew.getDisplayOrder()); + + listFinalQuestionDTO.add(voteQuestionDTO); + } else { + voteQuestionDTO.setNomination(question); + voteQuestionDTO.setDisplayOrder(displayOrder); + + listFinalQuestionDTO.add(voteQuestionDTO); + } + } + + return listFinalQuestionDTO; + } + + private VoteContent saveOrUpdateVoteContent(VoteAuthoringForm voteAuthoringForm, HttpServletRequest request, + VoteContent voteContent, String strToolContentID) { + if (logger.isDebugEnabled()) { + logger.debug("ToolContentID" + strToolContentID); + } + UserDTO toolUser = (UserDTO) SessionManager.getSession().getAttribute(AttributeNames.USER); + + String richTextTitle = request.getParameter(VoteAppConstants.TITLE); + String richTextInstructions = request.getParameter(VoteAppConstants.INSTRUCTIONS); + + String lockOnFinish = request.getParameter("lockOnFinish"); + + String allowTextEntry = request.getParameter("allowText"); + + String showResults = request.getParameter("showResults"); + + String maxInputs = request.getParameter("maxInputs"); + + String useSelectLeaderToolOuput = request.getParameter("useSelectLeaderToolOuput"); + + String reflect = request.getParameter(VoteAppConstants.REFLECT); + + String reflectionSubject = voteAuthoringForm.getReflectionSubject(); + + String maxNomcount = voteAuthoringForm.getMaxNominationCount(); + + String minNomcount = voteAuthoringForm.getMinNominationCount(); + + boolean lockOnFinishBoolean = false; + boolean allowTextEntryBoolean = false; + boolean useSelectLeaderToolOuputBoolean = false; + boolean reflectBoolean = false; + boolean showResultsBoolean = false; + short maxInputsShort = 0; + + if (lockOnFinish != null && lockOnFinish.equalsIgnoreCase("1")) { + lockOnFinishBoolean = true; + } + + if (allowTextEntry != null && allowTextEntry.equalsIgnoreCase("1")) { + allowTextEntryBoolean = true; + } + + if (useSelectLeaderToolOuput != null && useSelectLeaderToolOuput.equalsIgnoreCase("1")) { + useSelectLeaderToolOuputBoolean = true; + } + + if (reflect != null && reflect.equalsIgnoreCase("1")) { + reflectBoolean = true; + } + + if (showResults != null && showResults.equalsIgnoreCase("1")) { + showResultsBoolean = true; + } + + if (maxInputs != null && !"0".equals(maxInputs)) { + maxInputsShort = Short.parseShort(maxInputs); + } + + long userId = 0; + if (toolUser != null) { + userId = toolUser.getUserID().longValue(); + } else { + HttpSession ss = SessionManager.getSession(); + UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); + if (user != null) { + userId = user.getUserID().longValue(); + } else { + userId = 0; + } + } + + boolean newContent = false; + if (voteContent == null) { + voteContent = new VoteContent(); + newContent = true; + } + + voteContent.setVoteContentId(new Long(strToolContentID)); + voteContent.setTitle(richTextTitle); + voteContent.setInstructions(richTextInstructions); + voteContent.setUpdateDate(new Date(System.currentTimeMillis())); + /** keep updating this one */ + voteContent.setCreatedBy(userId); + /** make sure we are setting the userId from the User object above */ + + voteContent.setLockOnFinish(lockOnFinishBoolean); + voteContent.setAllowText(allowTextEntryBoolean); + voteContent.setShowResults(showResultsBoolean); + voteContent.setUseSelectLeaderToolOuput(useSelectLeaderToolOuputBoolean); + voteContent.setReflect(reflectBoolean); + voteContent.setMaxNominationCount(maxNomcount); + voteContent.setMinNominationCount(minNomcount); + + voteContent.setReflectionSubject(reflectionSubject); + + voteContent.setMaxExternalInputs(maxInputsShort); + + if (newContent) { + logger.info("In New Content"); + voteService.saveVoteContent(voteContent); + } else { + voteService.updateVote(voteContent); + } + + voteContent = voteService.getVoteContent(new Long(strToolContentID)); + + return voteContent; + } +} \ No newline at end of file Index: lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/ClearSessionController.java =================================================================== diff -u --- lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/ClearSessionController.java (revision 0) +++ lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/ClearSessionController.java (revision 8bc11142a6db14da1d00d3fd8adfe7d4938ead15) @@ -0,0 +1,67 @@ +/**************************************************************** + * 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.tool.vote.web.controller; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.log4j.Logger; +import org.lamsfoundation.lams.authoring.web.AuthoringConstants; +import org.lamsfoundation.lams.authoring.web.LamsAuthoringFinishController; +import org.lamsfoundation.lams.tool.ToolAccessMode; +import org.lamsfoundation.lams.tool.vote.VoteAppConstants; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.context.WebApplicationContext; + +/** + * This class give a chance to clear HttpSession when user save/close authoring page. + * + * @author Steve.Ni, Ozgur Demirtas + */ +@Controller +public class ClearSessionController extends LamsAuthoringFinishController implements VoteAppConstants { + private static Logger logger = Logger.getLogger(ClearSessionController.class.getName()); + + @Autowired + private WebApplicationContext applicationContext; + + @RequestMapping("/clearsession") + public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException { + super.execute(request, response, applicationContext); + } + + @Override + public void clearSession(String customiseSessionID, HttpSession session, ToolAccessMode mode) { + session.removeAttribute(AuthoringConstants.LAMS_AUTHORING_SUCCESS_FLAG); + if (mode.isAuthor()) { + ClearSessionController.logger.debug("In Author mode"); + session.removeAttribute(customiseSessionID); + } + } +} Index: lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/LearningController.java =================================================================== diff -u --- lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/LearningController.java (revision 0) +++ lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/LearningController.java (revision 8bc11142a6db14da1d00d3fd8adfe7d4938ead15) @@ -0,0 +1,1023 @@ +/*************************************************************************** + * 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.tool.vote.web.controller; + +import java.io.IOException; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TimeZone; +import java.util.TreeMap; +import java.util.TreeSet; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.apache.log4j.Logger; +import org.lamsfoundation.lams.learning.web.util.LearningWebUtil; +import org.lamsfoundation.lams.notebook.model.NotebookEntry; +import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; +import org.lamsfoundation.lams.tool.ToolAccessMode; +import org.lamsfoundation.lams.tool.exception.DataMissingException; +import org.lamsfoundation.lams.tool.exception.ToolException; +import org.lamsfoundation.lams.tool.vote.VoteAppConstants; +import org.lamsfoundation.lams.tool.vote.dto.VoteGeneralLearnerFlowDTO; +import org.lamsfoundation.lams.tool.vote.pojos.VoteContent; +import org.lamsfoundation.lams.tool.vote.pojos.VoteQueContent; +import org.lamsfoundation.lams.tool.vote.pojos.VoteQueUsr; +import org.lamsfoundation.lams.tool.vote.pojos.VoteSession; +import org.lamsfoundation.lams.tool.vote.pojos.VoteUsrAttempt; +import org.lamsfoundation.lams.tool.vote.service.IVoteService; +import org.lamsfoundation.lams.tool.vote.util.VoteApplicationException; +import org.lamsfoundation.lams.tool.vote.util.VoteComparator; +import org.lamsfoundation.lams.tool.vote.web.form.VoteLearningForm; +import org.lamsfoundation.lams.usermanagement.dto.UserDTO; +import org.lamsfoundation.lams.util.DateUtil; +import org.lamsfoundation.lams.util.MessageService; +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.beans.factory.annotation.Qualifier; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.context.WebApplicationContext; + +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + +/** + * @author Ozgur Demirtas + */ +@Controller +@RequestMapping("/learning") +public class LearningController implements VoteAppConstants { + private static Logger logger = Logger.getLogger(LearningController.class.getName()); + + @Autowired + private WebApplicationContext applicationContext; + + @Autowired + @Qualifier("lavoteMessageService") + private MessageService messageService; + + @Autowired + @Qualifier("voteService") + private IVoteService voteService; + + @RequestMapping("/viewAllResults") + public String viewAllResults(VoteLearningForm voteLearningForm, HttpServletRequest request) { + VoteGeneralLearnerFlowDTO voteGeneralLearnerFlowDTO = new VoteGeneralLearnerFlowDTO(); + + voteLearningForm.setNominationsSubmited(new Boolean(false).toString()); + voteLearningForm.setMaxNominationCountReached(new Boolean(false).toString()); + voteLearningForm.setMinNominationCountReached(new Boolean(false).toString()); + + voteGeneralLearnerFlowDTO.setNominationsSubmited(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setMaxNominationCountReached(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setMinNominationCountReached(new Boolean(false).toString()); + + LearningController.repopulateRequestParameters(request, voteLearningForm); + + String toolSessionID = request.getParameter(TOOL_SESSION_ID); + logger.info("Tool session ID" + toolSessionID); + voteLearningForm.setToolSessionID(toolSessionID); + + String userID = request.getParameter(USER_ID); + voteLearningForm.setUserID(userID); + + VoteSession voteSession = voteService.getSessionBySessionId(new Long(toolSessionID)); + VoteContent voteContent = voteSession.getVoteContent(); + + voteGeneralLearnerFlowDTO.setActivityTitle(voteContent.getTitle()); + voteGeneralLearnerFlowDTO.setActivityInstructions(voteContent.getInstructions()); + + Long toolContentID = voteContent.getVoteContentId(); + + Long toolSessionUid = voteSession.getUid(); + + VoteQueUsr existingVoteQueUsr = voteService.getVoteUserBySession(new Long(userID), voteSession.getUid()); + + existingVoteQueUsr.setFinalScreenRequested(true); + voteService.updateVoteUser(existingVoteQueUsr); + + Set userAttempts = voteService.getAttemptsForUserAndSession(existingVoteQueUsr.getUid(), + toolSessionUid); + request.setAttribute(LIST_GENERAL_CHECKED_OPTIONS_CONTENT, userAttempts); + + voteService.prepareChartData(request, toolContentID, toolSessionUid, voteGeneralLearnerFlowDTO); + + voteGeneralLearnerFlowDTO.setReflection(new Boolean(voteContent.isReflect()).toString()); + //String reflectionSubject = VoteUtils.replaceNewLines(voteContent.getReflectionSubject()); + voteGeneralLearnerFlowDTO.setReflectionSubject(voteContent.getReflectionSubject()); + + voteLearningForm.resetCommands(); + + request.setAttribute(VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); + + LearningWebUtil.putActivityPositionInRequestByToolSessionId(new Long(toolSessionID), request, + applicationContext.getServletContext()); + + return "/learning/AllNominations"; + } + + @RequestMapping("/viewAnswers") + public String viewAnswers(VoteLearningForm voteLearningForm, HttpServletRequest request) { + VoteGeneralLearnerFlowDTO voteGeneralLearnerFlowDTO = new VoteGeneralLearnerFlowDTO(); + + voteLearningForm.setNominationsSubmited(new Boolean(false).toString()); + voteLearningForm.setMaxNominationCountReached(new Boolean(false).toString()); + voteLearningForm.setMinNominationCountReached(new Boolean(false).toString()); + + voteGeneralLearnerFlowDTO.setNominationsSubmited(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setMaxNominationCountReached(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setMinNominationCountReached(new Boolean(false).toString()); + + LearningController.repopulateRequestParameters(request, voteLearningForm); + + String toolSessionID = request.getParameter(TOOL_SESSION_ID); + logger.info("Tool session id :" + toolSessionID); + voteLearningForm.setToolSessionID(toolSessionID); + + String userID = request.getParameter(USER_ID); + logger.info("User id :" + userID); + voteLearningForm.setUserID(userID); + + String revisitingUser = request.getParameter(REVISITING_USER); + voteLearningForm.setRevisitingUser(revisitingUser); + + VoteSession voteSession = voteService.getSessionBySessionId(new Long(toolSessionID)); + VoteContent voteContent = voteSession.getVoteContent(); + + voteGeneralLearnerFlowDTO.setActivityTitle(voteContent.getTitle()); + voteGeneralLearnerFlowDTO.setActivityInstructions(voteContent.getInstructions()); + + if (revisitingUser.equals("true")) { + /* get back login user DTO */ + HttpSession ss = SessionManager.getSession(); + UserDTO toolUser = (UserDTO) ss.getAttribute(AttributeNames.USER); + long userId = toolUser.getUserID().longValue(); + VoteQueUsr voteQueUsr = voteService.getUserByUserId(userId); + + List attempts = voteService.getAttemptsForUser(voteQueUsr.getUid()); + + Map mapQuestionsContent = new TreeMap(new VoteComparator()); + Iterator listIterator = attempts.iterator(); + int order = 0; + while (listIterator.hasNext()) { + VoteUsrAttempt attempt = listIterator.next(); + VoteQueContent voteQueContent = attempt.getVoteQueContent(); + order++; + if (voteQueContent != null) { + mapQuestionsContent.put(new Integer(order).toString(), voteQueContent.getQuestion()); + } + } + request.setAttribute(MAP_GENERAL_CHECKED_OPTIONS_CONTENT, mapQuestionsContent); + } else { + //this is not a revisiting user + logger.info("If not a revisiting user"); + } + + voteLearningForm.resetCommands(); + + request.setAttribute(VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); + LearningWebUtil.putActivityPositionInRequestByToolSessionId(new Long(toolSessionID), request, + applicationContext.getServletContext()); + return "/learning/ViewAnswers"; + } + + @RequestMapping("/redoQuestionsOk") + public String redoQuestionsOk(VoteLearningForm voteLearningForm, HttpServletRequest request) { + + VoteGeneralLearnerFlowDTO voteGeneralLearnerFlowDTO = new VoteGeneralLearnerFlowDTO(); + + LearningController.repopulateRequestParameters(request, voteLearningForm); + + String toolSessionID = request.getParameter(TOOL_SESSION_ID); + logger.info("Tool session id:" + toolSessionID); + voteLearningForm.setToolSessionID(toolSessionID); + + String userID = request.getParameter(USER_ID); + logger.info("User id:" + userID); + voteLearningForm.setUserID(userID); + + String revisitingUser = request.getParameter(REVISITING_USER); + voteLearningForm.setRevisitingUser(revisitingUser); + + voteLearningForm.setNominationsSubmited(new Boolean(false).toString()); + voteLearningForm.setMaxNominationCountReached(new Boolean(false).toString()); + voteLearningForm.setMinNominationCountReached(new Boolean(false).toString()); + + voteGeneralLearnerFlowDTO.setNominationsSubmited(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setMaxNominationCountReached(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setMinNominationCountReached(new Boolean(false).toString()); + + VoteSession voteSession = voteService.getSessionBySessionId(new Long(toolSessionID)); + VoteContent voteContent = voteSession.getVoteContent(); + voteGeneralLearnerFlowDTO.setActivityTitle(voteContent.getTitle()); + voteGeneralLearnerFlowDTO.setActivityInstructions(voteContent.getInstructions()); + + voteGeneralLearnerFlowDTO.setReflection(new Boolean(voteContent.isReflect()).toString()); + //String reflectionSubject = VoteUtils.replaceNewLines(voteContent.getReflectionSubject()); + voteGeneralLearnerFlowDTO.setReflectionSubject(voteContent.getReflectionSubject()); + + voteLearningForm.resetCommands(); + + request.setAttribute(VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); + return redoQuestions(voteLearningForm, request); + } + + @RequestMapping("/learnerFinished") + public String learnerFinished(VoteLearningForm voteLearningForm, HttpServletRequest request) { + VoteGeneralLearnerFlowDTO voteGeneralLearnerFlowDTO = new VoteGeneralLearnerFlowDTO(); + + voteLearningForm.setNominationsSubmited(new Boolean(false).toString()); + voteLearningForm.setMaxNominationCountReached(new Boolean(false).toString()); + voteLearningForm.setMinNominationCountReached(new Boolean(false).toString()); + + voteGeneralLearnerFlowDTO.setNominationsSubmited(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setMaxNominationCountReached(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setMinNominationCountReached(new Boolean(false).toString()); + + LearningController.repopulateRequestParameters(request, voteLearningForm); + + String toolSessionID = request.getParameter(TOOL_SESSION_ID); + logger.info("Tool Session id :" + toolSessionID); + voteLearningForm.setToolSessionID(toolSessionID); + + VoteSession voteSession = voteService.getSessionBySessionId(new Long(toolSessionID)); + String userID = request.getParameter(USER_ID); + logger.info("User id:" + userID); + voteLearningForm.setUserID(userID); + + VoteQueUsr voteQueUsr = voteService.getVoteUserBySession(new Long(userID), voteSession.getUid()); + + voteQueUsr.setResponseFinalised(true); + if (!voteSession.getVoteContent().isShowResults()) { + // if not isShowResults then we will have skipped the final screen. + voteQueUsr.setFinalScreenRequested(true); + } + voteService.updateVoteUser(voteQueUsr); + + String revisitingUser = request.getParameter(REVISITING_USER); + voteLearningForm.setRevisitingUser(revisitingUser); + + VoteContent voteContent = voteSession.getVoteContent(); + + voteGeneralLearnerFlowDTO.setActivityTitle(voteContent.getTitle()); + voteGeneralLearnerFlowDTO.setActivityInstructions(voteContent.getInstructions()); + + voteGeneralLearnerFlowDTO.setReflection(new Boolean(voteContent.isReflect()).toString()); + //String reflectionSubject = VoteUtils.replaceNewLines(voteContent.getReflectionSubject()); + voteGeneralLearnerFlowDTO.setReflectionSubject(voteContent.getReflectionSubject()); + + request.setAttribute(VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); + + String nextUrl = null; + try { + nextUrl = voteService.leaveToolSession(new Long(toolSessionID), new Long(userID)); + } catch (DataMissingException e) { + logger.error("failure getting nextUrl: " + e); + voteLearningForm.resetCommands(); + //throw new ServletException(e); + return "/learningIndex"; + } catch (ToolException e) { + logger.error("failure getting nextUrl: " + e); + voteLearningForm.resetCommands(); + //throw new ServletException(e); + return "/learningIndex"; + } catch (Exception e) { + logger.error("unknown exception getting nextUrl: " + e); + voteLearningForm.resetCommands(); + //throw new ServletException(e); + return "/learningIndex"; + } + + voteLearningForm.resetCommands(); + + /* pay attention here */ + return "redirect:" + nextUrl; + } + + @RequestMapping("/continueOptionsCombined") + public String continueOptionsCombined(VoteLearningForm voteLearningForm, HttpServletRequest request) { + + VoteGeneralLearnerFlowDTO voteGeneralLearnerFlowDTO = new VoteGeneralLearnerFlowDTO(); + + LearningController.repopulateRequestParameters(request, voteLearningForm); + + String toolSessionID = request.getParameter(TOOL_SESSION_ID); + logger.info("Tool session id:" + toolSessionID); + voteLearningForm.setToolSessionID(toolSessionID); + + String userID = request.getParameter(USER_ID); + logger.info("User id:" + userID); + voteLearningForm.setUserID(userID); + + String maxNominationCount = request.getParameter(MAX_NOMINATION_COUNT); + voteLearningForm.setMaxNominationCount(maxNominationCount); + + String minNominationCount = request.getParameter(MIN_NOMINATION_COUNT); + voteLearningForm.setMinNominationCount(minNominationCount); + + String userEntry = request.getParameter(USER_ENTRY); + voteLearningForm.setUserEntry(userEntry); + + VoteSession session = voteService.getSessionBySessionId(new Long(toolSessionID)); + voteLearningForm.setNominationsSubmited(new Boolean(false).toString()); + voteLearningForm.setMaxNominationCountReached(new Boolean(false).toString()); + voteLearningForm.setMinNominationCountReached(new Boolean(false).toString()); + + voteGeneralLearnerFlowDTO.setNominationsSubmited(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setMaxNominationCountReached(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setMinNominationCountReached(new Boolean(false).toString()); + + Collection voteDisplayOrderIds = voteLearningForm.votesAsCollection(); + + // check number of votes + int castVoteCount = voteDisplayOrderIds != null ? voteDisplayOrderIds.size() : 0; + if ((userEntry != null) && (userEntry.length() > 0)) { + ++castVoteCount; + } + + int intMaxNominationCount = 0; + if (maxNominationCount != null) { + intMaxNominationCount = new Integer(maxNominationCount).intValue(); + } + + if (castVoteCount > intMaxNominationCount) { + voteLearningForm.setMaxNominationCountReached(new Boolean(true).toString()); + voteGeneralLearnerFlowDTO.setMaxNominationCountReached(new Boolean(true).toString()); + MultiValueMap errorMap = new LinkedMultiValueMap<>(); + errorMap.add("GLOBAL", messageService.getMessage("error.maxNominationCount.reached")); + request.setAttribute("errorMap", errorMap); + logger.error("You have selected too many nominations."); + return "/learning/AnswersContent"; + } + + VoteContent voteContent = session.getVoteContent(); + + voteGeneralLearnerFlowDTO.setActivityTitle(voteContent.getTitle()); + voteGeneralLearnerFlowDTO.setActivityInstructions(voteContent.getInstructions()); + + Long toolContentID = voteContent.getVoteContentId(); + Long voteContentUid = voteContent.getUid(); + + boolean userEntryAvailable = false; + if ((userEntry != null) && (userEntry.length() > 0)) { + userEntryAvailable = true; + } + + Long toolSessionUid = session.getUid(); + + VoteQueUsr user = voteService.getVoteUserBySession(new Long(userID), session.getUid()); + if (user == null) { + throw new VoteApplicationException( + "User with userId= " + userID + " and sessionUid= " + session.getUid() + " doesn't exist."); + } + + voteService.removeAttemptsForUserandSession(user.getUid(), session.getUid()); + + /* + * to minimize changes to working code, convert the String[] array to the mapGeneralCheckedOptionsContent + * structure + */ + Map mapGeneralCheckedOptionsContent = voteService.buildQuestionMap(voteContent, + voteDisplayOrderIds); + + if (mapGeneralCheckedOptionsContent.size() > 0) { + voteService.createAttempt(user, mapGeneralCheckedOptionsContent, "", session, voteContentUid); + } + + if ((mapGeneralCheckedOptionsContent.size() == 0 && (userEntryAvailable == true))) { + Map mapLeanerCheckedOptionsContent = new TreeMap(new VoteComparator()); + + if (userEntry.length() > 0) { + voteService.createAttempt(user, mapLeanerCheckedOptionsContent, userEntry, session, voteContentUid); + } + } + + if ((mapGeneralCheckedOptionsContent.size() > 0) && (userEntryAvailable == true)) { + Map mapLeanerCheckedOptionsContent = new TreeMap(new VoteComparator()); + + if (userEntry.length() > 0) { + voteService.createAttempt(user, mapLeanerCheckedOptionsContent, userEntry, session, voteContentUid); + } + } + + /* put the map in the request ready for the next screen */ + request.setAttribute(MAP_GENERAL_CHECKED_OPTIONS_CONTENT, mapGeneralCheckedOptionsContent); + voteLearningForm.setMapGeneralCheckedOptionsContent(mapGeneralCheckedOptionsContent); + voteGeneralLearnerFlowDTO.setMapGeneralCheckedOptionsContent(mapGeneralCheckedOptionsContent); + + voteLearningForm.setNominationsSubmited(new Boolean(true).toString()); + voteGeneralLearnerFlowDTO.setNominationsSubmited(new Boolean(true).toString()); + + voteService.prepareChartData(request, toolContentID, toolSessionUid, voteGeneralLearnerFlowDTO); + + voteGeneralLearnerFlowDTO.setReflection(new Boolean(voteContent.isReflect()).toString()); + voteGeneralLearnerFlowDTO.setReflectionSubject(voteContent.getReflectionSubject()); + + voteLearningForm.resetCommands(); + request.setAttribute(VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); + + return "/learning/IndividualLearnerResults"; + } + + @RequestMapping("/redoQuestions") + public String redoQuestions(VoteLearningForm voteLearningForm, HttpServletRequest request) { + + VoteGeneralLearnerFlowDTO voteGeneralLearnerFlowDTO = new VoteGeneralLearnerFlowDTO(); + + LearningController.repopulateRequestParameters(request, voteLearningForm); + + String toolSessionID = request.getParameter(TOOL_SESSION_ID); + voteLearningForm.setToolSessionID(toolSessionID); + + String userID = request.getParameter(USER_ID); + voteLearningForm.setUserID(userID); + + String revisitingUser = request.getParameter(REVISITING_USER); + voteLearningForm.setRevisitingUser(revisitingUser); + + VoteSession voteSession = voteService.getSessionBySessionId(new Long(toolSessionID)); + + VoteContent voteContent = voteSession.getVoteContent(); + + voteGeneralLearnerFlowDTO.setActivityTitle(voteContent.getTitle()); + voteGeneralLearnerFlowDTO.setActivityInstructions(voteContent.getInstructions()); + + voteLearningForm.setNominationsSubmited(new Boolean(false).toString()); + voteLearningForm.setMaxNominationCountReached(new Boolean(false).toString()); + + voteGeneralLearnerFlowDTO.setNominationsSubmited(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setMaxNominationCountReached(new Boolean(false).toString()); + + Map mapQuestionsContent = voteService.buildQuestionMap(voteContent, null); + request.setAttribute(MAP_QUESTION_CONTENT_LEARNER, mapQuestionsContent); + + Map mapGeneralCheckedOptionsContent = new TreeMap(new VoteComparator()); + request.setAttribute(MAP_GENERAL_CHECKED_OPTIONS_CONTENT, mapGeneralCheckedOptionsContent); + + voteLearningForm.setUserEntry(""); + + voteGeneralLearnerFlowDTO.setReflection(new Boolean(voteContent.isReflect()).toString()); + voteGeneralLearnerFlowDTO.setReflectionSubject(voteContent.getReflectionSubject()); + voteLearningForm.resetCommands(); + request.setAttribute(VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); + + return "/learning/AnswersContent"; + } + + @RequestMapping(path = "/checkLeaderProgress", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + @ResponseBody + public String checkLeaderProgress(HttpServletRequest request) throws IOException { + + Long toolSessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); + + VoteSession session = voteService.getSessionBySessionId(toolSessionId); + VoteQueUsr leader = session.getGroupLeader(); + logger.info("Leader :" + leader); + + boolean isLeaderResponseFinalized = leader.isResponseFinalised(); + + ObjectNode objectNode = JsonNodeFactory.instance.objectNode(); + objectNode.put("isLeaderResponseFinalized", isLeaderResponseFinalized); + return objectNode.toString(); + } + + @RequestMapping(path = "/submitReflection", method = RequestMethod.POST) + public String submitReflection(VoteLearningForm voteLearningForm, HttpServletRequest request) { + + LearningController.repopulateRequestParameters(request, voteLearningForm); + + String toolSessionIDString = request.getParameter(AttributeNames.PARAM_TOOL_SESSION_ID); + voteLearningForm.setToolSessionID(toolSessionIDString); + Long toolSessionID = new Long(toolSessionIDString); + + String userIDString = request.getParameter("userID"); + voteLearningForm.setUserID(userIDString); + Integer userID = new Integer(userIDString); + + String reflectionEntry = request.getParameter(ENTRY_TEXT); + + // check for existing notebook entry + NotebookEntry entry = voteService.getEntry(toolSessionID, CoreNotebookConstants.NOTEBOOK_TOOL, MY_SIGNATURE, + userID); + + if (entry == null) { + // create new entry + voteService.createNotebookEntry(toolSessionID, CoreNotebookConstants.NOTEBOOK_TOOL, MY_SIGNATURE, userID, + reflectionEntry); + } else { + // update existing entry + entry.setEntry(reflectionEntry); + entry.setLastModified(new Date()); + voteService.updateEntry(entry); + } + + voteLearningForm.resetUserActions(); /* resets all except submitAnswersContent */ + return learnerFinished(voteLearningForm, request); + } + + @RequestMapping("/forwardtoReflection") + public String forwardtoReflection(VoteLearningForm voteLearningForm, HttpServletRequest request) { + String toolSessionID = request.getParameter(AttributeNames.PARAM_TOOL_SESSION_ID); + logger.info("toolSessionID:" + toolSessionID); + VoteSession voteSession = voteService.getSessionBySessionId(new Long(toolSessionID)); + + VoteContent voteContent = voteSession.getVoteContent(); + VoteGeneralLearnerFlowDTO voteGeneralLearnerFlowDTO = new VoteGeneralLearnerFlowDTO(); + voteGeneralLearnerFlowDTO.setActivityTitle(voteContent.getTitle()); + + voteGeneralLearnerFlowDTO.setReflectionSubject(voteContent.getReflectionSubject()); + + String userID = request.getParameter("userID"); + logger.info("User Id :" + userID); + voteLearningForm.setUserID(userID); + + NotebookEntry notebookEntry = voteService.getEntry(new Long(toolSessionID), CoreNotebookConstants.NOTEBOOK_TOOL, + MY_SIGNATURE, new Integer(userID)); + + if (notebookEntry != null) { + String notebookEntryPresentable = notebookEntry.getEntry(); + voteGeneralLearnerFlowDTO.setNotebookEntry(notebookEntryPresentable); + voteLearningForm.setEntryText(notebookEntryPresentable); + } + + request.setAttribute(VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); + + voteLearningForm.resetCommands(); + + LearningWebUtil.putActivityPositionInRequestByToolSessionId(new Long(toolSessionID), request, + applicationContext.getServletContext()); + + return "/learning/Notebook"; + } + + private static void repopulateRequestParameters(HttpServletRequest request, VoteLearningForm voteLearningForm) { + String toolSessionID = request.getParameter(TOOL_SESSION_ID); + voteLearningForm.setToolSessionID(toolSessionID); + + String userID = request.getParameter(USER_ID); + voteLearningForm.setUserID(userID); + + String revisitingUser = request.getParameter(REVISITING_USER); + voteLearningForm.setRevisitingUser(revisitingUser); + + String previewOnly = request.getParameter(PREVIEW_ONLY); + voteLearningForm.setPreviewOnly(previewOnly); + + String maxNominationCount = request.getParameter(MAX_NOMINATION_COUNT); + voteLearningForm.setMaxNominationCount(maxNominationCount); + + String minNominationCount = request.getParameter(MIN_NOMINATION_COUNT); + voteLearningForm.setMinNominationCount(minNominationCount); + + String useSelectLeaderToolOuput = request.getParameter(USE_SELECT_LEADER_TOOL_OUTPUT); + voteLearningForm.setUseSelectLeaderToolOuput(useSelectLeaderToolOuput); + + String allowTextEntry = request.getParameter(ALLOW_TEXT_ENTRY); + voteLearningForm.setAllowTextEntry(allowTextEntry); + + String showResults = request.getParameter(SHOW_RESULTS); + voteLearningForm.setShowResults(showResults); + + String lockOnFinish = request.getParameter(LOCK_ON_FINISH); + voteLearningForm.setLockOnFinish(lockOnFinish); + + String reportViewOnly = request.getParameter(REPORT_VIEW_ONLY); + voteLearningForm.setReportViewOnly(reportViewOnly); + + String userEntry = request.getParameter(USER_ENTRY); + voteLearningForm.setUserEntry(userEntry); + + String groupLeaderName = request.getParameter(ATTR_GROUP_LEADER_NAME); + voteLearningForm.setGroupLeaderName(groupLeaderName); + + String groupLeaderUserId = request.getParameter(ATTR_GROUP_LEADER_USER_ID); + voteLearningForm.setGroupLeaderUserId(groupLeaderUserId); + + boolean isUserLeader = WebUtil.readBooleanParam(request, "userLeader"); + voteLearningForm.setIsUserLeader(isUserLeader); + } + + /* + * By now, the passed tool session id MUST exist in the db through the calling of: public void + * createToolSession(Long toolSessionID, Long toolContentId) by the container. + * + * + * make sure this session exists in tool's session table by now. + */ + @RequestMapping("/start") + public String start(VoteLearningForm voteLearningForm, HttpServletRequest request) { + + VoteGeneralLearnerFlowDTO voteGeneralLearnerFlowDTO = new VoteGeneralLearnerFlowDTO(); + + voteLearningForm.setRevisitingUser(new Boolean(false).toString()); + voteLearningForm.setUserEntry(""); + voteLearningForm.setCastVoteCount(0); + voteLearningForm.setMaxNominationCountReached(new Boolean(false).toString()); + + voteGeneralLearnerFlowDTO.setRevisitingUser(new Boolean(false).toString()); + voteGeneralLearnerFlowDTO.setUserEntry(""); + voteGeneralLearnerFlowDTO.setCastVoteCount("0"); + voteGeneralLearnerFlowDTO.setMaxNominationCountReached(new Boolean(false).toString()); + + boolean validateParameters = LearningController.validateParameters(request, voteLearningForm); + if (!validateParameters) { + return "/error"; + } + + String toolSessionID = voteLearningForm.getToolSessionID(); + + /* + * by now, we made sure that the passed tool session id exists in the db as a new record Make sure we can + * retrieve it and the relavent content + */ + + VoteSession voteSession = voteService.getSessionBySessionId(new Long(toolSessionID)); + + if (voteSession == null) { + + logger.error("error: The tool expects voteSession."); + return "/error"; + } + + /* + * find out what content this tool session is referring to get the content for this tool session Each passed + * tool session id points to a particular content. Many to one mapping. + */ + VoteContent voteContent = voteSession.getVoteContent(); + if (voteContent == null) { + + logger.error("error: The tool expects voteContent."); + MultiValueMap errorMap = new LinkedMultiValueMap<>(); + errorMap.add("GLOBAL", messageService.getMessage("error.content.doesNotExist")); + request.setAttribute("errorMap", errorMap); + return "/error"; + } + + /* + * The content we retrieved above must have been created before in Authoring time. And the passed tool session + * id already refers to it. + */ + LearningController.setupAttributes(request, voteContent, voteLearningForm, voteGeneralLearnerFlowDTO); + + voteLearningForm.setToolContentID(voteContent.getVoteContentId().toString()); + voteGeneralLearnerFlowDTO.setToolContentID(voteContent.getVoteContentId().toString()); + + voteLearningForm.setToolContentUID(voteContent.getUid().toString()); + voteGeneralLearnerFlowDTO.setToolContentUID(voteContent.getUid().toString()); + + voteGeneralLearnerFlowDTO.setReflection(new Boolean(voteContent.isReflect()).toString()); + //String reflectionSubject = VoteUtils.replaceNewLines(voteContent.getReflectionSubject()); + voteGeneralLearnerFlowDTO.setReflectionSubject(voteContent.getReflectionSubject()); + + String mode = voteLearningForm.getLearningMode(); + voteGeneralLearnerFlowDTO.setLearningMode(mode); + + String userId = voteLearningForm.getUserID(); + NotebookEntry notebookEntry = voteService.getEntry(new Long(toolSessionID), CoreNotebookConstants.NOTEBOOK_TOOL, + VoteAppConstants.MY_SIGNATURE, new Integer(userId)); + if (notebookEntry != null) { + //String notebookEntryPresentable = VoteUtils.replaceNewLines(notebookEntry.getEntry()); + voteGeneralLearnerFlowDTO.setNotebookEntry(notebookEntry.getEntry()); + } + + Map mapQuestions = voteService.buildQuestionMap(voteContent, null); + request.setAttribute(VoteAppConstants.MAP_QUESTION_CONTENT_LEARNER, mapQuestions); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); + + VoteQueUsr user = null; + if ((mode != null) && mode.equals(ToolAccessMode.TEACHER.toString())) { + // monitoring mode - user is specified in URL + // user may be null if the user was force completed. + user = getSpecifiedUser(toolSessionID, WebUtil.readIntParam(request, AttributeNames.PARAM_USER_ID, false)); + } else { + user = getCurrentUser(toolSessionID); + } + + // check if there is submission deadline + Date submissionDeadline = voteContent.getSubmissionDeadline(); + + if (submissionDeadline != null) { + + request.setAttribute(VoteAppConstants.ATTR_SUBMISSION_DEADLINE, submissionDeadline); + HttpSession ss = SessionManager.getSession(); + UserDTO learnerDto = (UserDTO) ss.getAttribute(AttributeNames.USER); + TimeZone learnerTimeZone = learnerDto.getTimeZone(); + Date tzSubmissionDeadline = DateUtil.convertToTimeZoneFromDefault(learnerTimeZone, submissionDeadline); + Date currentLearnerDate = DateUtil.convertToTimeZoneFromDefault(learnerTimeZone, new Date()); + voteGeneralLearnerFlowDTO.setSubmissionDeadline(tzSubmissionDeadline); + + // calculate whether deadline has passed, and if so forward to "submissionDeadline" + if (currentLearnerDate.after(tzSubmissionDeadline)) { + return "/learning/submissionDeadline"; + } + } + + LearningWebUtil.putActivityPositionInRequestByToolSessionId(new Long(toolSessionID), request, + applicationContext.getServletContext()); + + /* find out if the content is being modified at the moment. */ + if (voteContent.isDefineLater()) { + + return "/learning/defineLater"; + } + + //process group leader + VoteQueUsr groupLeader = null; + if (voteContent.isUseSelectLeaderToolOuput()) { + groupLeader = voteService.checkLeaderSelectToolForSessionLeader(user, new Long(toolSessionID)); + + // forwards to the leaderSelection page + if (groupLeader == null && !mode.equals(ToolAccessMode.TEACHER.toString())) { + + Set groupUsers = voteSession.getVoteQueUsers(); + request.setAttribute(ATTR_GROUP_USERS, groupUsers); + request.setAttribute(TOOL_SESSION_ID, toolSessionID); + request.setAttribute(ATTR_CONTENT, voteContent); + + return "/learning/WaitForLeader"; + } + + // check if leader has submitted all answers + if (groupLeader.isResponseFinalised() && !mode.equals(ToolAccessMode.TEACHER.toString())) { + + // in case user joins the lesson after leader has answers some answers already - we need to make sure + // he has the same scratches as leader + voteService.copyAnswersFromLeader(user, groupLeader); + + user.setFinalScreenRequested(true); + user.setResponseFinalised(true); + voteService.updateVoteUser(user); + } + + // store group leader information + voteLearningForm.setGroupLeaderName(groupLeader.getFullname()); + voteLearningForm.setGroupLeaderUserId( + groupLeader.getQueUsrId() != null ? groupLeader.getQueUsrId().toString() : ""); + boolean isUserLeader = voteService.isUserGroupLeader(user, new Long(toolSessionID)); + voteLearningForm.setIsUserLeader(isUserLeader); + } + + if (mode.equals("teacher")) { + + Long sessionUid = user.getVoteSessionId(); + putMapQuestionsContentIntoRequest(request, voteService, user); + Set userAttempts = voteService.getAttemptsForUserAndSessionUseOpenAnswer(user.getUid(), sessionUid); + request.setAttribute(VoteAppConstants.LIST_GENERAL_CHECKED_OPTIONS_CONTENT, userAttempts); + + // since this is progress view, present a screen which can not be edited + voteLearningForm.setReportViewOnly(new Boolean(true).toString()); + voteGeneralLearnerFlowDTO.setReportViewOnly(new Boolean(true).toString()); + + voteService.prepareChartData(request, voteContent.getVoteContentId(), voteSession.getUid(), + voteGeneralLearnerFlowDTO); + + boolean isGroupedActivity = voteService.isGroupedActivity(new Long(voteLearningForm.getToolContentID())); + request.setAttribute("isGroupedActivity", isGroupedActivity); + + return "/learning/ExitLearning"; + } + + /* + * the user's session id AND user id exists in the tool tables goto this screen if the OverAll Results scren has + * been already called up by this user + */ + if (user.isFinalScreenRequested()) { + Long sessionUid = user.getVoteSessionId(); + VoteSession voteUserSession = voteService.getVoteSessionByUID(sessionUid); + String userSessionId = voteUserSession.getVoteSessionId().toString(); + + if (toolSessionID.toString().equals(userSessionId)) { + // the learner has already responsed to this content, just generate a read-only report. Use redo + // questions for this + putMapQuestionsContentIntoRequest(request, voteService, user); + + boolean isResponseFinalised = user.isResponseFinalised(); + if (isResponseFinalised) { + // since the response is finalised present a screen which can not be edited + voteLearningForm.setReportViewOnly(new Boolean(true).toString()); + voteGeneralLearnerFlowDTO.setReportViewOnly(new Boolean(true).toString()); + } + + Set userAttempts = voteService.getAttemptsForUserAndSessionUseOpenAnswer(user.getUid(), + sessionUid); + request.setAttribute(VoteAppConstants.LIST_GENERAL_CHECKED_OPTIONS_CONTENT, userAttempts); + + voteService.prepareChartData(request, voteContent.getVoteContentId(), voteSession.getUid(), + voteGeneralLearnerFlowDTO); + + String isContentLockOnFinish = voteLearningForm.getLockOnFinish(); + if (isContentLockOnFinish.equals(new Boolean(true).toString()) && isResponseFinalised == true) { + // user with session id: userSessionId should not redo votes. session is locked + return "/learning/ExitLearning"; + } + + voteLearningForm.setRevisitingUser(new Boolean(true).toString()); + voteGeneralLearnerFlowDTO.setRevisitingUser(new Boolean(true).toString()); + request.setAttribute(VoteAppConstants.VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); + + if (isContentLockOnFinish.equals(new Boolean(false).toString()) && isResponseFinalised == true) { + // isContentLockOnFinish is false, enable redo of votes + return "/learning/RevisitedAllNominations"; + } + + return "/learning/AllNominations"; + } + } + // presenting standard learner screen.. + return "/learning/AnswersContent"; + } + + /** + * Build the attempts map and put it in the request, based on the supplied user. If the user is null then the map + * will be set but it will be empty TODO This shouldn't go in the request, it should go in our special session map. + */ + private void putMapQuestionsContentIntoRequest(HttpServletRequest request, IVoteService voteService, + VoteQueUsr user) { + List attempts = null; + if (user != null) { + attempts = voteService.getAttemptsForUser(user.getUid()); + } + Map localMapQuestionsContent = new TreeMap(new VoteComparator()); + + if (attempts != null) { + + Iterator listIterator = attempts.iterator(); + int order = 0; + while (listIterator.hasNext()) { + VoteUsrAttempt attempt = listIterator.next(); + VoteQueContent voteQueContent = attempt.getVoteQueContent(); + order++; + if (voteQueContent != null) { + String entry = voteQueContent.getQuestion(); + + String questionUid = attempt.getVoteQueContent().getUid().toString(); + if (entry != null) { + if (entry.equals("sample nomination") && questionUid.equals("1")) { + localMapQuestionsContent.put(new Integer(order).toString(), attempt.getUserEntry()); + } else { + localMapQuestionsContent.put(new Integer(order).toString(), voteQueContent.getQuestion()); + } + } + } + } + } + + request.setAttribute(VoteAppConstants.MAP_GENERAL_CHECKED_OPTIONS_CONTENT, localMapQuestionsContent); + } + + /** + * sets up session scope attributes based on content linked to the passed tool session id + * setupAttributes(HttpServletRequest request, VoteContent voteContent) + * + * @param request + * @param voteContent + */ + private static void setupAttributes(HttpServletRequest request, VoteContent voteContent, + VoteLearningForm voteLearningForm, VoteGeneralLearnerFlowDTO voteGeneralLearnerFlowDTO) { + + Map mapGeneralCheckedOptionsContent = new TreeMap(new VoteComparator()); + request.setAttribute(VoteAppConstants.MAP_GENERAL_CHECKED_OPTIONS_CONTENT, mapGeneralCheckedOptionsContent); + + voteLearningForm.setActivityTitle(voteContent.getTitle()); + voteLearningForm.setActivityInstructions(voteContent.getInstructions()); + voteLearningForm.setMaxNominationCount(voteContent.getMaxNominationCount()); + voteLearningForm.setMinNominationCount(voteContent.getMinNominationCount()); + voteLearningForm.setUseSelectLeaderToolOuput(new Boolean(voteContent.isUseSelectLeaderToolOuput()).toString()); + voteLearningForm.setAllowTextEntry(new Boolean(voteContent.isAllowText()).toString()); + voteLearningForm.setShowResults(new Boolean(voteContent.isShowResults()).toString()); + voteLearningForm.setLockOnFinish(new Boolean(voteContent.isLockOnFinish()).toString()); + + voteGeneralLearnerFlowDTO.setActivityTitle(voteContent.getTitle()); + voteGeneralLearnerFlowDTO.setActivityInstructions(voteContent.getInstructions()); + voteGeneralLearnerFlowDTO.setMaxNominationCount(voteContent.getMaxNominationCount()); + voteGeneralLearnerFlowDTO.setMinNominationCount(voteContent.getMinNominationCount()); + voteGeneralLearnerFlowDTO + .setUseSelectLeaderToolOuput(new Boolean(voteContent.isUseSelectLeaderToolOuput()).toString()); + voteGeneralLearnerFlowDTO.setAllowTextEntry(new Boolean(voteContent.isAllowText()).toString()); + voteGeneralLearnerFlowDTO.setLockOnFinish(new Boolean(voteContent.isLockOnFinish()).toString()); + voteGeneralLearnerFlowDTO.setActivityTitle(voteContent.getTitle()); + voteGeneralLearnerFlowDTO.setActivityInstructions(voteContent.getInstructions()); + } + + private static boolean validateParameters(HttpServletRequest request, VoteLearningForm voteLearningForm) { + /* + * obtain and setup the current user's data + */ + + String userID = ""; + HttpSession ss = SessionManager.getSession(); + + if (ss != null) { + UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); + if (user != null && user.getUserID() != null) { + userID = user.getUserID().toString(); + logger.info("User Id : " + userID); + voteLearningForm.setUserID(userID); + } + } + + /* + * process incoming tool session id and later derive toolContentId from it. + */ + String strToolSessionId = request.getParameter(AttributeNames.PARAM_TOOL_SESSION_ID); + long toolSessionID = 0; + if (strToolSessionId == null || strToolSessionId.length() == 0) { + + // persistInRequestError(request, "error.toolSessionId.required"); + logger.error("error.toolSessionId.required"); + return false; + } else { + try { + toolSessionID = new Long(strToolSessionId).longValue(); + voteLearningForm.setToolSessionID(new Long(toolSessionID).toString()); + } catch (NumberFormatException e) { + + // persistInRequestError(request, "error.sessionId.numberFormatException"); + logger.error("add error.sessionId.numberFormatException to ActionMessages."); + return false; + } + } + + /* mode can be learner, teacher or author */ + String mode = request.getParameter(VoteAppConstants.MODE); + + if (mode == null || mode.length() == 0) { + + logger.error("mode missing: "); + return false; + } + + if (!mode.equals("learner") && !mode.equals("teacher") && !mode.equals("author")) { + + logger.error("mode invalid: "); + return false; + } + voteLearningForm.setLearningMode(mode); + + return true; + } + + private VoteQueUsr getCurrentUser(String toolSessionId) { + + // get back login user DTO + HttpSession ss = SessionManager.getSession(); + UserDTO toolUser = (UserDTO) ss.getAttribute(AttributeNames.USER); + Long userId = new Long(toolUser.getUserID().longValue()); + + VoteSession session = voteService.getSessionBySessionId(new Long(toolSessionId)); + VoteQueUsr user = voteService.getVoteUserBySession(userId, session.getUid()); + if (user == null) { + String userName = toolUser.getLogin(); + String fullName = toolUser.getFirstName() + " " + toolUser.getLastName(); + + user = new VoteQueUsr(userId, userName, fullName, session, new TreeSet()); + voteService.createVoteQueUsr(user); + } + + return user; + } + + private VoteQueUsr getSpecifiedUser(String toolSessionId, Integer userId) { + VoteSession session = voteService.getSessionBySessionId(new Long(toolSessionId)); + VoteQueUsr user = voteService.getVoteUserBySession(new Long(userId.intValue()), session.getUid()); + if (user == null) { + logger.error("Unable to find specified user for Vote activity. Screens are likely to fail. SessionId=" + + new Long(toolSessionId) + " UserId=" + userId); + } + return user; + } +} \ No newline at end of file Index: lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/MonitoringController.java =================================================================== diff -u --- lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/MonitoringController.java (revision 0) +++ lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/MonitoringController.java (revision 8bc11142a6db14da1d00d3fd8adfe7d4938ead15) @@ -0,0 +1,512 @@ +/*************************************************************************** + * 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.tool.vote.web.controller; + +import java.util.Date; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.SortedSet; +import java.util.TimeZone; +import java.util.TreeMap; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.apache.log4j.Logger; +import org.lamsfoundation.lams.tool.vote.VoteAppConstants; +import org.lamsfoundation.lams.tool.vote.dto.OpenTextAnswerDTO; +import org.lamsfoundation.lams.tool.vote.dto.SummarySessionDTO; +import org.lamsfoundation.lams.tool.vote.dto.VoteGeneralAuthoringDTO; +import org.lamsfoundation.lams.tool.vote.dto.VoteGeneralMonitoringDTO; +import org.lamsfoundation.lams.tool.vote.dto.VoteMonitoredUserDTO; +import org.lamsfoundation.lams.tool.vote.dto.VoteQuestionDTO; +import org.lamsfoundation.lams.tool.vote.pojos.VoteContent; +import org.lamsfoundation.lams.tool.vote.pojos.VoteQueContent; +import org.lamsfoundation.lams.tool.vote.pojos.VoteUsrAttempt; +import org.lamsfoundation.lams.tool.vote.service.IVoteService; +import org.lamsfoundation.lams.tool.vote.util.VoteComparator; +import org.lamsfoundation.lams.tool.vote.web.form.VoteMonitoringForm; +import org.lamsfoundation.lams.usermanagement.dto.UserDTO; +import org.lamsfoundation.lams.util.DateUtil; +import org.lamsfoundation.lams.util.WebUtil; +import org.lamsfoundation.lams.web.session.SessionManager; +import org.lamsfoundation.lams.web.util.AttributeNames; +import org.lamsfoundation.lams.web.util.SessionMap; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.util.HtmlUtils; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + +/** + * @author Ozgur Demirtas + */ +@Controller +@RequestMapping("/monitoring") +public class MonitoringController implements VoteAppConstants { + private static Logger logger = Logger.getLogger(MonitoringController.class.getName()); + + @Autowired + @Qualifier("voteService") + private IVoteService voteService; + + @RequestMapping(path = "/hideOpenVote", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + @ResponseBody + public String hideOpenVote(HttpServletRequest request) { + return toggleHideShow(request, false); + } + + @RequestMapping(path = "/showOpenVote", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + @ResponseBody + public String showOpenVote(HttpServletRequest request) { + return toggleHideShow(request, true); + } + + private String toggleHideShow(HttpServletRequest request, boolean show) { + Long currentUid = WebUtil.readLongParam(request, "currentUid"); + logger.info("Current Uid" + currentUid); + + VoteUsrAttempt voteUsrAttempt = voteService.getAttemptByUID(currentUid); + + voteUsrAttempt.setVisible(show); + voteService.updateVoteUsrAttempt(voteUsrAttempt); + String nextActionMethod; + if (show) { + nextActionMethod = "hideOptionVote"; + voteService.showOpenVote(voteUsrAttempt); + } else { + nextActionMethod = "showOpenVote"; + voteService.hideOpenVote(voteUsrAttempt); + } + + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.put("currentUid", currentUid); + responseJSON.put("nextActionMethod", nextActionMethod); + return responseJSON.toString(); + } + + @RequestMapping("/getVoteNomination") + public String getVoteNomination(VoteMonitoringForm voteMonitoringForm, HttpServletRequest request) { + + voteMonitoringForm.setVoteService(voteService); + + VoteGeneralMonitoringDTO voteGeneralMonitoringDTO = new VoteGeneralMonitoringDTO(); + MonitoringController.repopulateRequestParameters(request, voteMonitoringForm, voteGeneralMonitoringDTO); + + Long questionUid = WebUtil.readLongParam(request, VoteAppConstants.ATTR_QUESTION_UID, false); + Long sessionUid = WebUtil.readLongParam(request, VoteAppConstants.ATTR_SESSION_UID, true); + + VoteQueContent nomination = voteService.getQuestionByUid(questionUid); + request.setAttribute("nominationText", nomination.getQuestion()); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_MONITORING_DTO, voteGeneralMonitoringDTO); + request.setAttribute(VoteAppConstants.ATTR_QUESTION_UID, questionUid); + if (sessionUid != null) { + request.setAttribute(VoteAppConstants.ATTR_SESSION_UID, sessionUid); + } + return "/monitoring/VoteNominationViewer"; + } + + @RequestMapping(path = "/getVoteNominationsJSON", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + @ResponseBody + public String getVoteNominationsJSON(HttpServletRequest request) { + + Long sessionUid = WebUtil.readLongParam(request, VoteAppConstants.ATTR_SESSION_UID, true); + if (sessionUid == 0L) { + sessionUid = null; + logger.info("Setting sessionUid to null"); + } + + Long questionUid = WebUtil.readLongParam(request, VoteAppConstants.ATTR_QUESTION_UID, false); + + // paging parameters of tablesorter + int size = WebUtil.readIntParam(request, "size"); + int page = WebUtil.readIntParam(request, "page"); + Integer sortByName = WebUtil.readIntParam(request, "column[0]", true); + Integer sortByDate = WebUtil.readIntParam(request, "column[1]", true); + String searchString = request.getParameter("fcol[0]"); + + int sorting = VoteAppConstants.SORT_BY_DEFAULT; + if (sortByName != null) { + sorting = sortByName.equals(0) ? VoteAppConstants.SORT_BY_NAME_ASC : VoteAppConstants.SORT_BY_NAME_DESC; + } else if (sortByDate != null) { + sorting = sortByDate.equals(0) ? VoteAppConstants.SORT_BY_DATE_ASC : VoteAppConstants.SORT_BY_DATE_DESC; + } + + //return user list according to the given sessionID + List users = voteService.getUserAttemptsForTablesorter(sessionUid, questionUid, page, size, sorting, + searchString); + + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.put("total_rows", voteService.getCountUsersBySession(sessionUid, questionUid, searchString)); + + for (Object[] userAndAnswers : users) { + + ObjectNode responseRow = JsonNodeFactory.instance.objectNode(); + responseRow.put(VoteAppConstants.ATTR_USER_ID, (Integer) userAndAnswers[0]); + responseRow.put(VoteAppConstants.ATTR_USER_NAME, HtmlUtils.htmlEscape((String) userAndAnswers[2])); + responseRow.put(VoteAppConstants.ATTR_ATTEMPT_TIME, + DateUtil.convertToStringForJSON((Date) userAndAnswers[3], request.getLocale())); + responseRow.put(VoteAppConstants.ATTR_ATTEMPT_TIME_TIMEAGO, + DateUtil.convertToStringForTimeagoJSON((Date) userAndAnswers[3])); + responseRow.put(VoteAppConstants.ATTR_PORTRAIT_ID, (Integer) userAndAnswers[4]); + rows.add(responseRow); + } + responseJSON.set("rows", rows); + return responseJSON.toString(); + } + + @RequestMapping(path = "/getReflectionsJSON", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + @ResponseBody + public String getReflectionsJSON(HttpServletRequest request) { + + Long sessionUid = WebUtil.readLongParam(request, VoteAppConstants.ATTR_SESSION_UID, true); + + // paging parameters of tablesorter + int size = WebUtil.readIntParam(request, "size"); + int page = WebUtil.readIntParam(request, "page"); + Integer sortByName = WebUtil.readIntParam(request, "column[0]", true); + String searchString = request.getParameter("fcol[0]"); + + int sorting = VoteAppConstants.SORT_BY_DEFAULT; + if (sortByName != null) { + sorting = sortByName.equals(0) ? VoteAppConstants.SORT_BY_NAME_ASC : VoteAppConstants.SORT_BY_NAME_DESC; + } + + //return user list according to the given sessionID + List users = voteService.getUserReflectionsForTablesorter(sessionUid, page, size, sorting, + searchString); + + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.put("total_rows", voteService.getCountUsersBySession(sessionUid, null, searchString)); + + for (Object[] userAndReflection : users) { + ObjectNode responseRow = JsonNodeFactory.instance.objectNode(); + responseRow.put(VoteAppConstants.ATTR_USER_ID, (Integer) userAndReflection[0]); + responseRow.put(VoteAppConstants.ATTR_USER_NAME, HtmlUtils.htmlEscape((String) userAndReflection[2])); + if (userAndReflection.length > 3 && userAndReflection[3] != null) { + String reflection = HtmlUtils.htmlEscape((String) userAndReflection[3]); + responseRow.put(VoteAppConstants.NOTEBOOK, reflection.replaceAll("\n", "
")); + } + if (userAndReflection.length > 4) { + responseRow.put(VoteAppConstants.ATTR_PORTRAIT_ID, (Integer) userAndReflection[4]); + } + rows.add(responseRow); + } + responseJSON.set("rows", rows); + return responseJSON.toString(); + } + + @RequestMapping("/statistics") + public String statistics(HttpServletRequest request) { + Long toolContentID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); + + request.setAttribute("isGroupedActivity", voteService.isGroupedActivity(toolContentID)); + request.setAttribute(VoteAppConstants.VOTE_STATS_DTO, voteService.getStatisticsBySession(toolContentID)); + return "/monitoring/Stats"; + } + + @RequestMapping(path = "/getOpenTextNominationsJSON", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + @ResponseBody + public String getOpenTextNominationsJSON(HttpServletRequest request) { + + Long sessionUid = WebUtil.readLongParam(request, VoteAppConstants.ATTR_SESSION_UID, true); + if (sessionUid == 0L) { + logger.info("Setting sessionUid to null"); + sessionUid = null; + } + + Long contentUid = WebUtil.readLongParam(request, VoteAppConstants.TOOL_CONTENT_UID, false); + + // paging parameters of tablesorter + int size = WebUtil.readIntParam(request, "size"); + int page = WebUtil.readIntParam(request, "page"); + Integer sortByEntry = WebUtil.readIntParam(request, "column[0]", true); + Integer sortByName = WebUtil.readIntParam(request, "column[1]", true); + Integer sortByDate = WebUtil.readIntParam(request, "column[2]", true); + Integer sortByVisible = WebUtil.readIntParam(request, "column[3]", true); + String searchStringVote = request.getParameter("fcol[0]"); + String searchStringUsername = request.getParameter("fcol[1]"); + + int sorting = VoteAppConstants.SORT_BY_DEFAULT; + if (sortByEntry != null) { + sorting = sortByEntry.equals(0) ? VoteAppConstants.SORT_BY_ENTRY_ASC : VoteAppConstants.SORT_BY_ENTRY_DESC; + } + if (sortByName != null) { + sorting = sortByName.equals(0) ? VoteAppConstants.SORT_BY_NAME_ASC : VoteAppConstants.SORT_BY_NAME_DESC; + } else if (sortByDate != null) { + sorting = sortByDate.equals(0) ? VoteAppConstants.SORT_BY_DATE_ASC : VoteAppConstants.SORT_BY_DATE_DESC; + } else if (sortByVisible != null) { + sorting = sortByVisible.equals(0) ? VoteAppConstants.SORT_BY_VISIBLE_ASC + : VoteAppConstants.SORT_BY_VISIBLE_DESC; + } + + //return user list according to the given sessionID + List users = voteService.getUserOpenTextAttemptsForTablesorter(sessionUid, contentUid, page, + size, sorting, searchStringVote, searchStringUsername); + + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.put("total_rows", voteService.getCountUsersForOpenTextEntries(sessionUid, contentUid, + searchStringVote, searchStringUsername)); + + for (OpenTextAnswerDTO userAndAttempt : users) { + ObjectNode responseRow = JsonNodeFactory.instance.objectNode(); + + responseRow.put("uid", userAndAttempt.getUserUid()); + responseRow.put(VoteAppConstants.ATTR_USER_NAME, HtmlUtils.htmlEscape(userAndAttempt.getFullName())); + + responseRow.put("userEntryUid", userAndAttempt.getUserEntryUid()); + responseRow.put("userEntry", HtmlUtils.htmlEscape(userAndAttempt.getUserEntry())); + responseRow.put(VoteAppConstants.ATTR_ATTEMPT_TIME, + DateUtil.convertToStringForJSON(userAndAttempt.getAttemptTime(), request.getLocale())); + responseRow.put(VoteAppConstants.ATTR_ATTEMPT_TIME_TIMEAGO, + DateUtil.convertToStringForTimeagoJSON(userAndAttempt.getAttemptTime())); + responseRow.put("visible", userAndAttempt.isVisible()); + responseRow.put("portraitId", userAndAttempt.getPortraitId()); + + rows.add(responseRow); + } + responseJSON.set("rows", rows); + return responseJSON.toString(); + } + + /* + * Possible error: forward "learnerNotebook" is not listed in Struts + * + * @RequestMapping("/openNotebook") + * public ActionForward openNotebook(HttpServletRequest request) throws IOException, ServletException, ToolException + * { + * String userId = request.getParameter("userId"); + * + * String userName = request.getParameter("userName"); + * + * String sessionId = request.getParameter("sessionId"); + * + * NotebookEntry notebookEntry = voteService.getEntry(new Long(sessionId), CoreNotebookConstants.NOTEBOOK_TOOL, + * VoteAppConstants.MY_SIGNATURE, new Integer(userId)); + * + * VoteGeneralLearnerFlowDTO voteGeneralLearnerFlowDTO = new VoteGeneralLearnerFlowDTO(); + * if (notebookEntry != null) { + * //String notebookEntryPresentable = VoteUtils.replaceNewLines(notebookEntry.getEntry()); + * voteGeneralLearnerFlowDTO.setNotebookEntry(notebookEntry.getEntry()); + * voteGeneralLearnerFlowDTO.setUserName(userName); + * } + * request.setAttribute(VoteAppConstants.VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); + * + * return mapping.findForward(VoteAppConstants.LEARNER_NOTEBOOK); + * } + */ + @RequestMapping(path = "/setSubmissionDeadline", produces = MediaType.TEXT_PLAIN_VALUE) + @ResponseBody + public String setSubmissionDeadline(HttpServletRequest request) { + Long contentID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); + VoteContent voteContent = voteService.getVoteContent(contentID); + + Long dateParameter = WebUtil.readLongParam(request, VoteAppConstants.ATTR_SUBMISSION_DEADLINE, true); + Date tzSubmissionDeadline = null; + String formattedDate = ""; + if (dateParameter != null) { + Date submissionDeadline = new Date(dateParameter); + HttpSession ss = SessionManager.getSession(); + org.lamsfoundation.lams.usermanagement.dto.UserDTO teacher = (org.lamsfoundation.lams.usermanagement.dto.UserDTO) ss + .getAttribute(AttributeNames.USER); + TimeZone teacherTimeZone = teacher.getTimeZone(); + tzSubmissionDeadline = DateUtil.convertFromTimeZoneToDefault(teacherTimeZone, submissionDeadline); + formattedDate = DateUtil.convertToStringForJSON(tzSubmissionDeadline, request.getLocale()); + } + voteContent.setSubmissionDeadline(tzSubmissionDeadline); + voteService.updateVote(voteContent); + return formattedDate; + } + + @RequestMapping("/start") + public String start(VoteMonitoringForm voteMonitoringForm, HttpServletRequest request) { + + VoteGeneralAuthoringDTO voteGeneralAuthoringDTO = new VoteGeneralAuthoringDTO(); + VoteGeneralMonitoringDTO voteGeneralMonitoringDTO = new VoteGeneralMonitoringDTO(); + request.setAttribute(VoteAppConstants.VOTE_GENERAL_AUTHORING_DTO, voteGeneralAuthoringDTO); + request.setAttribute(VoteAppConstants.VOTE_GENERAL_MONITORING_DTO, voteGeneralMonitoringDTO); + + boolean validateParameters = validateParameters(request, voteMonitoringForm); + if (!validateParameters) { + return "/error"; + } + + // initialiseMonitoringData + voteGeneralMonitoringDTO.setRequestLearningReport(Boolean.FALSE.toString()); + + /* we have made sure TOOL_CONTENT_ID is passed */ + String toolContentID = voteMonitoringForm.getToolContentID(); + logger.warn("Make sure ToolContentId is passed" + toolContentID); + VoteContent voteContent = voteService.getVoteContent(new Long(toolContentID)); + + if (voteContent == null) { + + logger.error("Vote Content does not exist"); + voteGeneralMonitoringDTO.setUserExceptionContentDoesNotExist(Boolean.TRUE.toString()); + return "/error"; + } + + voteGeneralMonitoringDTO.setActivityTitle(voteContent.getTitle()); + voteGeneralMonitoringDTO.setActivityInstructions(voteContent.getInstructions()); + + /* this section is related to summary tab. Starts here. */ + + SortedSet sessionDTOs = voteService.getMonitoringSessionDTOs(new Long(toolContentID)); + request.setAttribute("sessionDTOs", sessionDTOs); + + request.setAttribute(VoteAppConstants.VOTE_GENERAL_MONITORING_DTO, voteGeneralMonitoringDTO); + + // setting up the advanced summary for LDEV-1662 + request.setAttribute("useSelectLeaderToolOuput", voteContent.isUseSelectLeaderToolOuput()); + request.setAttribute("lockOnFinish", voteContent.isLockOnFinish()); + request.setAttribute("allowText", voteContent.isAllowText()); + request.setAttribute("maxNominationCount", voteContent.getMaxNominationCount()); + request.setAttribute("minNominationCount", voteContent.getMinNominationCount()); + request.setAttribute("showResults", voteContent.isShowResults()); + request.setAttribute("reflect", voteContent.isReflect()); + request.setAttribute("reflectionSubject", voteContent.getReflectionSubject()); + request.setAttribute("toolContentID", voteContent.getVoteContentId()); + + // setting up the SubmissionDeadline + if (voteContent.getSubmissionDeadline() != null) { + Date submissionDeadline = voteContent.getSubmissionDeadline(); + HttpSession ss = SessionManager.getSession(); + UserDTO teacher = (UserDTO) ss.getAttribute(AttributeNames.USER); + TimeZone teacherTimeZone = teacher.getTimeZone(); + Date tzSubmissionDeadline = DateUtil.convertToTimeZoneFromDefault(teacherTimeZone, submissionDeadline); + request.setAttribute(VoteAppConstants.ATTR_SUBMISSION_DEADLINE, tzSubmissionDeadline.getTime()); + // use the unconverted time, as convertToStringForJSON() does the timezone conversion if needed + request.setAttribute(VoteAppConstants.ATTR_SUBMISSION_DEADLINE_DATESTRING, + DateUtil.convertToStringForJSON(submissionDeadline, request.getLocale())); + } + + voteMonitoringForm.setCurrentTab("1"); + voteGeneralMonitoringDTO.setCurrentTab("1"); + + if (sessionDTOs.size() > 0) { + + voteGeneralMonitoringDTO.setUserExceptionContentInUse(Boolean.TRUE.toString()); + } + + /* + * get the nominations section is needed for the Edit tab's View Only mode, starts here + */ + SessionMap sessionMap = new SessionMap<>(); + sessionMap.put(VoteAppConstants.ACTIVITY_TITLE_KEY, voteContent.getTitle()); + sessionMap.put(VoteAppConstants.ACTIVITY_INSTRUCTIONS_KEY, voteContent.getInstructions()); + + voteMonitoringForm.setHttpSessionID(sessionMap.getSessionID()); + request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); + + List listQuestionDTO = new LinkedList(); + + Iterator queIterator = voteContent.getVoteQueContents().iterator(); + while (queIterator.hasNext()) { + VoteQuestionDTO voteQuestionDTO = new VoteQuestionDTO(); + + VoteQueContent voteQueContent = queIterator.next(); + if (voteQueContent != null) { + + voteQuestionDTO.setQuestion(voteQueContent.getQuestion()); + voteQuestionDTO.setDisplayOrder(new Integer(voteQueContent.getDisplayOrder()).toString()); + listQuestionDTO.add(voteQuestionDTO); + } + } + + request.setAttribute(VoteAppConstants.LIST_QUESTION_DTO, listQuestionDTO); + sessionMap.put(VoteAppConstants.LIST_QUESTION_DTO, listQuestionDTO); + + // this section is needed for Edit Activity screen + voteGeneralAuthoringDTO.setActivityTitle(voteGeneralMonitoringDTO.getActivityTitle()); + voteGeneralAuthoringDTO.setActivityInstructions(voteGeneralMonitoringDTO.getActivityInstructions()); + + MonitoringController.repopulateRequestParameters(request, voteMonitoringForm, voteGeneralMonitoringDTO); + + boolean isGroupedActivity = voteService.isGroupedActivity(new Long(toolContentID)); + request.setAttribute("isGroupedActivity", isGroupedActivity); + request.setAttribute("isAllowText", voteContent.isAllowText()); + + return "/monitoring/MonitoringMaincontent"; + } + + private boolean validateParameters(HttpServletRequest request, VoteMonitoringForm voteMonitoringForm) { + String strToolContentId = request.getParameter(AttributeNames.PARAM_TOOL_CONTENT_ID); + + if ((strToolContentId == null) || (strToolContentId.length() == 0)) { + + return false; + } else { + try { + voteMonitoringForm.setToolContentID(strToolContentId); + } catch (NumberFormatException e) { + logger.error("Number Format Exception"); + + return false; + } + } + return true; + } + + public static Map convertToVoteMonitoredUserDTOMap(List list) { + Map map = new TreeMap(new VoteComparator()); + + Iterator listIterator = list.iterator(); + Long mapIndex = new Long(1); + + while (listIterator.hasNext()) { + ; + VoteMonitoredUserDTO data = listIterator.next(); + + map.put(mapIndex.toString(), data); + mapIndex = new Long(mapIndex.longValue() + 1); + } + return map; + } + + public static void repopulateRequestParameters(HttpServletRequest request, VoteMonitoringForm voteMonitoringForm, + VoteGeneralMonitoringDTO voteGeneralMonitoringDTO) { + + String toolContentID = request.getParameter(VoteAppConstants.TOOL_CONTENT_ID); + voteMonitoringForm.setToolContentID(toolContentID); + voteGeneralMonitoringDTO.setToolContentID(toolContentID); + + String responseId = request.getParameter(VoteAppConstants.RESPONSE_ID); + voteMonitoringForm.setResponseId(responseId); + voteGeneralMonitoringDTO.setResponseId(responseId); + + String currentUid = request.getParameter(VoteAppConstants.CURRENT_UID); + voteMonitoringForm.setCurrentUid(currentUid); + } +} Index: lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/VoteChartGeneratorController.java =================================================================== diff -u --- lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/VoteChartGeneratorController.java (revision 0) +++ lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/VoteChartGeneratorController.java (revision 8bc11142a6db14da1d00d3fd8adfe7d4938ead15) @@ -0,0 +1,111 @@ +/*************************************************************************** + * 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.tool.vote.web.controller; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang.StringUtils; +import org.lamsfoundation.lams.tool.vote.dto.SessionDTO; +import org.lamsfoundation.lams.tool.vote.dto.VoteGeneralLearnerFlowDTO; +import org.lamsfoundation.lams.tool.vote.pojos.VoteContent; +import org.lamsfoundation.lams.tool.vote.pojos.VoteSession; +import org.lamsfoundation.lams.tool.vote.service.IVoteService; +import org.lamsfoundation.lams.tool.vote.util.VoteUtils; +import org.lamsfoundation.lams.util.WebUtil; +import org.lamsfoundation.lams.web.util.AttributeNames; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + +/** + * Prepares data for charts. + * + * @author Marcin Cieslak + */ +@Controller +public class VoteChartGeneratorController { + @Autowired + @Qualifier("voteService") + private IVoteService voteService; + + @RequestMapping(path = "/chartGenerator", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + @ResponseBody + public String start(HttpServletRequest request) { + String currentSessionId = request.getParameter("currentSessionId"); + + Map nominationNames = new HashMap<>(); + Map nominationVotes = new HashMap<>(); + + //request for the all session summary + if ("0".equals(currentSessionId)) { + long toolContentID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); + LinkedList sessionDTOs = voteService.getSessionDTOs(toolContentID); + + // check allSessionsSummary exists + SessionDTO allSessionsSummary = sessionDTOs.getFirst(); + if ("0".equals(allSessionsSummary.getSessionId())) { + nominationNames = allSessionsSummary.getMapStandardNominationsHTMLedContent(); + nominationVotes = allSessionsSummary.getMapStandardRatesContent(); + + //replace all html tags + for (Long index : nominationNames.keySet()) { + String name = nominationNames.get(index); + String noHTMLNomination = VoteUtils.stripHTML(name); + nominationNames.put(index, noHTMLNomination); + } + } + + //sessionId should not be blank + } else if (!StringUtils.isBlank(currentSessionId)) { + VoteSession voteSession = voteService.getSessionBySessionId(new Long(currentSessionId)); + VoteContent voteContent = voteSession.getVoteContent(); + + VoteGeneralLearnerFlowDTO voteGeneralLearnerFlowDTO = voteService.prepareChartData(request, + voteContent.getVoteContentId(), voteSession.getUid(), new VoteGeneralLearnerFlowDTO()); + + nominationNames = voteGeneralLearnerFlowDTO.getMapStandardNominationsContent(); + nominationVotes = voteGeneralLearnerFlowDTO.getMapStandardRatesContent(); + } + + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + for (Long index : nominationNames.keySet()) { + ObjectNode nomination = JsonNodeFactory.instance.objectNode(); + // nominations' names and values go separately + nomination.put("name", nominationNames.get(index)); + nomination.put("value", nominationVotes.get(index)); + responseJSON.withArray("data").add(nomination); + } + + return responseJSON.toString(); + } +} \ No newline at end of file Index: lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/VotePedagogicalPlannerController.java =================================================================== diff -u --- lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/VotePedagogicalPlannerController.java (revision 0) +++ lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/controller/VotePedagogicalPlannerController.java (revision 8bc11142a6db14da1d00d3fd8adfe7d4938ead15) @@ -0,0 +1,116 @@ +/**************************************************************** + * 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 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.tool.vote.web.controller; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang.StringUtils; +import org.lamsfoundation.lams.tool.vote.pojos.VoteContent; +import org.lamsfoundation.lams.tool.vote.pojos.VoteQueContent; +import org.lamsfoundation.lams.tool.vote.service.IVoteService; +import org.lamsfoundation.lams.tool.vote.web.form.VotePedagogicalPlannerForm; +import org.lamsfoundation.lams.util.MessageService; +import org.lamsfoundation.lams.util.WebUtil; +import org.lamsfoundation.lams.web.util.AttributeNames; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Controller; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/pedagogicalPlanner") +public class VotePedagogicalPlannerController { + @Autowired + @Qualifier("voteService") + private IVoteService voteService; + + @Autowired + @Qualifier("lavoteMessageService") + private MessageService messageService; + + @RequestMapping("/initPedagogicalPlannerForm") + public String initPedagogicalPlannerForm(VotePedagogicalPlannerForm plannerForm, HttpServletRequest request) { + Long toolContentID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); + VoteContent voteContent = voteService.getVoteContent(toolContentID); + plannerForm.fillForm(voteContent); + String contentFolderId = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); + plannerForm.setContentFolderID(contentFolderId); + return "/authoring/pedagogicalPlannerForm"; + } + + @RequestMapping("/saveOrUpdatePedagogicalPlannerForm") + public String saveOrUpdatePedagogicalPlannerForm(VotePedagogicalPlannerForm plannerForm, + HttpServletRequest request) { + MultiValueMap errorMap = plannerForm.validate(messageService); + if (errorMap.isEmpty()) { + VoteContent voteContent = voteService.getVoteContent(plannerForm.getToolContentID()); + voteContent.setInstructions(plannerForm.getInstructions()); + + int nominationIndex = 1; + String nomination = null; + + do { + nomination = plannerForm.getNomination(nominationIndex - 1); + if (StringUtils.isEmpty(nomination)) { + plannerForm.removeNomination(nominationIndex - 1); + } else { + if (nominationIndex <= voteContent.getVoteQueContents().size()) { + VoteQueContent voteQueContent = voteService.getQuestionByDisplayOrder((long) nominationIndex, + voteContent.getUid()); + voteQueContent.setQuestion(nomination); + voteService.saveOrUpdateVoteQueContent(voteQueContent); + + } else { + VoteQueContent voteQueContent = new VoteQueContent(); + voteQueContent.setDisplayOrder(nominationIndex); + voteQueContent.setVoteContent(voteContent); + voteQueContent.setVoteContentId(voteContent.getVoteContentId()); + voteQueContent.setQuestion(nomination); + voteService.saveOrUpdateVoteQueContent(voteQueContent); + } + nominationIndex++; + } + } while (nominationIndex <= plannerForm.getNominationCount()); + if (nominationIndex <= voteContent.getVoteQueContents().size()) { + voteService.removeQuestionsFromCache(voteContent); + voteService.removeVoteContentFromCache(voteContent); + for (; nominationIndex <= voteContent.getVoteQueContents().size(); nominationIndex++) { + VoteQueContent voteQueContent = voteService.getQuestionByDisplayOrder((long) nominationIndex, + voteContent.getUid()); + voteService.removeVoteQueContent(voteQueContent); + } + } + } else { + request.setAttribute("errorMap", errorMap); + } + return "/authoring/pedagogicalPlannerForm"; + } + + @RequestMapping("/createPedagogicalPlannerQuestion") + public String createPedagogicalPlannerQuestion(VotePedagogicalPlannerForm plannerForm) { + plannerForm.setNomination(plannerForm.getNominationCount().intValue(), ""); + return "/authoring/pedagogicalPlannerForm"; + } +} \ No newline at end of file