Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McAppConstants.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McAppConstants.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McAppConstants.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,403 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc; + +/** + * @author Ozgur Demirtas + * Defines constants used throughout the application + */ +public interface McAppConstants { + /* + * Currently we are hardcoding the default content id. + * This will be replaced when the deploy logic automatically assigns a default content id in the deploy script. + */ + + public static final String MY_SIGNATURE ="lamc11"; + public static final long DEFAULT_CONTENT_ID =0; + public static final long DEFAULT_QUE_CONTENT_ID =1; + + public static final String ROOT ="root"; + public static final String ROOT_PATH ="rootPath"; + public static final String PATH_TO_LAMS ="pathToLams"; + + + /* + * temporarily refers to an existing content id for an incoming tool session id, won't need it in deployment environment + */ + public static final long THE_MOCKED_CONTENT_ID =1803739427456570536L; + public static final String TOOL_SERVICE ="tool_service"; + public static final String ERROR ="error"; + public static final String ERROR_LIST ="errorList"; + + /* + * indicates which mode the tool runs under between Authoring, Learning, Monitoring + */ + public static final String TARGET_MODE ="targetMode"; + public static final String TARGET_MODE_AUTHORING ="Authoring"; + public static final String TARGET_MODE_LEARNING ="Learning"; + public static final String TARGET_MODE_MONITORING ="Monitoring"; + public static final String TARGET_MODE_EXPORT_PORTFOLIO ="ExportPortfolio"; + + public static final String AUTHORING_STARTER ="starter"; + public static final String LEARNING_STARTER ="learningStarter"; + public static final String MONITORING_STARTER ="monitoringStarter"; + + /* these constants are from org.lamsfoundation.lams.web.util.AttributeNames */ + public static final String USER = "user"; + public static final String TOOL_CONTENT_ID = "toolContentID"; + public static final String TOOL_CONTENT_UID = "toolContentUID"; + public static final String TOOL_SESSION_ID = "toolSessionID"; + public static final String MODE = "mode"; + public static final String USER_ID = "userID"; + public static final String ACTIVITY_ID = "activityID"; + public static final String CURRENT_TAB = "currentTab"; + public static final String MAX_QUESTION_INDEX = "maxQuestionIndex"; + + + /* + * Mock constants below are temporary until the tool gets a User object from the container. + */ + public static final Integer MOCK_USER_ID = new Integer(111); + public static final String MOCK_USER_NAME ="Ozgur"; + public static final String MOCK_USER_LASTNAME ="Demirtas"; + public static final String MOCK_LOGIN_NAME ="ozgur"; + + /* + * refers to number of questions presented initially, we have a single record for default content + */ + public static final Long INITIAL_QUESTION_COUNT =new Long(1); + public static final long MAX_QUESTION_COUNT =20; + public static final long MAX_OPTION_COUNT =10; + public static final int MAX_ATTEMPTY_HISTORY =30; + + + + /* + * Struts level constants + */ + public static final String LOAD ="load"; + public static final String LOAD_QUESTIONS ="load"; + public static final String LOAD_STARTER ="starter"; + public static final String LOAD_LEARNER ="loadLearner"; + public static final String INDIVIDUAL_REPORT ="individualReport"; + public static final String VIEW_SUMMARY ="viewSummary"; + public static final String REDO_QUESTIONS ="redoQuestions"; + public static final String SINGLE_QUESTION_ANSWERS ="singleQuestionAnswers"; + public static final String RESULTS_SUMMARY ="resultsSummary"; + + public static final String ALL_INSTRUCTIONS ="allInstructions"; + public static final String EDIT_OPTS_CONTENT ="editOptsContent"; + public static final String ADD_OPTS_CONTENT ="addOptsContent"; + public static final String REMOVE_OPTS_CONTENT ="removeOptsContent"; + public static final String USER_ACTION ="userAction"; + + + public static final String AUTHORING_BASIC ="authoringBasic"; + public static final boolean MODE_OPTIONAL = false; + public static final String DISABLE_TOOL ="disabled"; + public static final String IS_DEFINE_LATER ="isDefineLater"; + + /* + * authoring mode controllers + */ + public static final String IS_ADD_QUESTION ="isAddQuestion"; + public static final String IS_REMOVE_QUESTION ="isRemoveQuestion"; + public static final String IS_REMOVE_CONTENT ="isRemoveContent"; + + public static final String QUESTIONS_SEQUENCED ="questionsSequenced"; + + /* + * tab controllers, constants for authoring page html tabs, used within jsp + */ + public static final String CHOICE ="choice"; + public static final String CHOICE_TYPE_BASIC ="choiceTypeBasic"; + public static final String CHOICE_TYPE_ADVANCED ="choiceTypeAdvanced"; + public static final String CHOICE_TYPE_INSTRUCTIONS ="choiceTypeInstructions"; + public static final String EDIT_OPTIONS_MODE ="editOptionsMode"; + public static final String SUBMIT_SUCCESS ="submitSuccess"; + public static final String FILE_CONTENT ="fileContent"; + public static final String LOAD_FILE_CONTENT ="loadFileContent"; + public static final String FILE_CONTENT_READY ="fileContentReady"; + public static final String FILE_NAME ="fileName"; + + + /* + * authoring mode constants + */ + public static final String MAP_QUESTIONS_CONTENT ="mapQuestionsContent"; + public static final String MAP_OPTIONS_CONTENT ="mapOptionsContent"; + public static final String MAP_DEFAULTOPTIONS_CONTENT ="mapDefaultOptionsContent"; + public static final String MAP_DISABLED_QUESTIONS ="mapDisabledQuestions"; + public static final String MAP_GENERAL_OPTIONS_CONTENT ="mapGeneralOptionsContent"; + public static final String MAP_GENERAL_SELECTED_OPTIONS_CONTENT ="mapGeneralSelectedOptionsContent"; + public static final String MAP_STARTUP_GENERAL_OPTIONS_CONTENT ="mapStartupGeneralOptionsContent"; + public static final String MAP_STARTUP_GENERAL_SELECTED_OPTIONS_CONTENT ="mapStartupGeneralSelectedOptionsContent"; + public static final String MAP_STARTUP_GENERAL_OPTIONS_QUEID ="mapStartupGeneralOptionsQueId"; + + public static final String MAP_GENERAL_CHECKED_OPTIONS_CONTENT ="mapGeneralCheckedOptionsContent"; + public static final String MAP_LEARNER_QUESTIONS_CONTENT ="mapLearnerQuestionsContent"; + public static final String MAP_LEARNER_CHECKED_OPTIONS_CONTENT ="mapLearnerCheckedOptionsContent"; + public static final String MAP_LEARNER_ASSESSMENT_RESULTS ="mapLearnerAssessmentResults"; + public static final String MAP_LEARNER_FEEDBACK_INCORRECT ="mapLeanerFeedbackIncorrect"; + public static final String MAP_LEARNER_FEEDBACK_CORRECT ="mapLeanerFeedbackCorrect"; + public static final String MAP_QUESTION_WEIGHTS ="mapQuestionWeights"; + public static final String MAP_QUE_ATTEMPTS ="mapQueAttempts"; + public static final String MAP_QUE_CORRECT_ATTEMPTS ="mapQueCorrectAttempts"; + public static final String MAP_QUE_INCORRECT_ATTEMPTS ="mapQueIncorrectAttempts"; + + + public static final String MAP_WEIGHTS ="mapWeights"; + public static final String MAP_CHECKBOX_STATES ="mapCheckBoxStates"; + public static final String MAP_SELECTED_OPTIONS ="mapSelectedOptions"; + public static final String MAP_FEEDBACK_INCORRECT ="mapFeedbackIncorrect"; + public static final String MAP_FEEDBACK_CORRECT ="mapFeedbackCorrect"; + + + public static final String SELECTED_QUESTION_CONTENT_UID ="selectedQuestionContentUid"; + public static final String SELECTED_QUESTION ="selectedQuestion"; + public static final String SELECTED_QUESTION_INDEX ="selectedQuestionIndex"; + public static final String DEFAULT_QUESTION_UID ="defaultQuestionUid"; + + + public static final String MAP_QUESTION_CONTENT ="mapQuestionContent"; + public static final String DEFAULT_QUESTION_CONTENT ="defaultQuestionContent"; + public static final String TITLE ="title"; + public static final String INSTRUCTIONS ="instructions"; + public static final String CREATED_BY ="createdBy"; + public static final String CREATION_DATE ="creationDate"; + public static final String USERNAME_VISIBLE ="usernameVisible"; + public static final String RUN_OFFLINE ="runOffline"; + public static final String DEFINE_LATER ="defineLater"; + public static final String SYNCH_IN_MONITOR ="synchInMonitor"; + public static final String RETRIES ="retries"; + public static final String PASSMARK ="passMark"; + public static final String SHOW_FEEDBACK ="showFeedback"; + public static final String USER_PASSED ="userPassed"; + public static final String VIEW_ANSWERS ="viewAnswers"; + + + public static final String ONLINE_INSTRUCTIONS ="onlineInstructions"; + public static final String OFFLINE_INSTRUCTIONS ="offlineInstructions"; + public static final String END_LEARNING_MESSSAGE ="endLearningMessage"; + public static final String CONTENT_LOCKED ="contentLocked"; + public static final String CONTENT_IN_USE ="contentInUse"; + public static final String ON ="ON"; + public static final String OFF ="OFF"; + public static final String IS_USERNAME_VISIBLE_MONITORING ="isUsernameVisibleMonitoring"; + public static final String IS_SYNCH_INMONITOR_MONITORING ="isSynchInMonitorMonitoring"; + public static final String IS_QUESTIONS_SEQUENCED_MONITORING ="isQuestionsSequencedMonitoring"; + + + public static final String RICHTEXT_FEEDBACK_CORRECT ="richTextFeedbackCorrect"; + public static final String RICHTEXT_FEEDBACK_INCORRECT ="richTextFeedbackInCorrect"; + public static final String RICHTEXT_OFFLINEINSTRUCTIONS ="richTextOfflineInstructions"; + public static final String RICHTEXT_ONLINEINSTRUCTIONS ="richTextOnlineInstructions"; + public static final String RICHTEXT_REPORT_TITLE ="richTextReportTitle"; + public static final String RICHTEXT_END_LEARNING_MSG ="richTextEndLearningMsg"; + public static final String RICHTEXT_TITLE ="richTextTitle"; + public static final String RICHTEXT_INSTRUCTIONS ="richTextInstructions"; + public static final String RICHTEXT_BLANK ="

 

"; + public static final String THE_OFFLINE_FILE ="theOfflineFile"; + public static final String THE_ONLINE_FILE ="theOnlineFile"; + public static final String THE_OFFLINE_FILENAME ="theOfflineFileName"; + public static final String THE_ONLINE_FILENAME ="theOnlineFileName"; + public static final String SUBMIT_OFFLINE_FILE ="submitOfflineFile"; + public static final String SUBMIT_ONLINE_FILE ="submitOnlineFile"; + public static final String LIST_UPLOADED_OFFLINE_FILES ="listUploadedOfflineFiles"; + public static final String LIST_UPLOADED_ONLINE_FILES ="listUploadedOnlineFiles"; + public static final String LIST_UPLOADED_OFFLINE_FILENAMES ="listUploadedOfflineFileNames"; + public static final String LIST_UPLOADED_ONLINE_FILENAMES ="listUploadedOnlineFileNames"; + public static final String LIST_UPLOADED_OFFLINE_FILES_UUID ="listUploadedOfflineFilesUuid"; + public static final String LIST_UPLOADED_OFFLINE_FILES_NAME ="listUploadedOfflineFilesName"; + public static final String LIST_UPLOADED_ONLINE_FILES_UUID ="listUploadedOnlineFilesUuid"; + public static final String LIST_UPLOADED_ONLINE_FILES_NAME ="listUploadedOnlineFilesName"; + public static final String POPULATED_UPLOADED_FILESDATA ="populateUploadedFilesData"; + + public static final String COUNT_SESSION_COMPLETE ="countSessionComplete"; + public static final String TOP_MARK ="topMark"; + public static final String LOWEST_MARK ="lowestMark"; + public static final String AVERAGE_MARK ="averageMark"; + + + /* + * the author's current content id + */ + + + /* + * the learner or monitoring environment provides toolSessionId + */ + public final long ONE_DAY =60 * 60 * 1000 * 24; + public final static String NOT_ATTEMPTED ="NOT_ATTEMPTED"; + public final static String INCOMPLETE ="INCOMPLETE"; + public static final String COMPLETED ="COMPLETED"; + + public static final String MAP_TOOL_SESSIONS ="mapToolSessions"; + public static final String RESPONSE_INDEX ="responseIndex"; + public static final Integer MAX_TOOL_SESSION_COUNT =new Integer(500); + public static final String IS_TOOL_SESSION_CHANGED ="isToolSessionChanged"; + public static final String USER_EXCEPTION_WRONG_FORMAT ="userExceptionWrongFormat"; + public static final String USER_EXCEPTION_UNCOMPATIBLE_IDS ="userExceptionUncompatibleIds"; + public static final String USER_EXCEPTION_NUMBERFORMAT ="userExceptionNumberFormat"; + public static final String USER_EXCEPTION_CONTENT_DOESNOTEXIST ="userExceptionContentDoesNotExist"; + public static final String USER_EXCEPTION_TOOLSESSION_DOESNOTEXIST ="userExceptionToolSessionDoesNotExist"; + public static final String USER_EXCEPTION_CONTENTID_REQUIRED ="userExceptionContentIdRequired"; + public static final String USER_EXCEPTION_TOOLSESSIONID_REQUIRED ="userExceptionToolSessionIdRequired"; + public static final String USER_EXCEPTION_DEFAULTCONTENT_NOT_AVAILABLE ="userExceptionDefaultContentNotAvailable"; + public static final String USER_EXCEPTION_DEFAULTQUESTIONCONTENT_NOT_AVAILABLE ="userExceptionDefaultQuestionContentNotAvailable"; + public static final String USER_EXCEPTION_DEFAULTOPTIONSCONTENT_NOT_AVAILABLE ="userExceptionDefaultOptionsContentNotAvailable"; + + public static final String USER_EXCEPTION_USERID_NOTAVAILABLE ="userExceptionUserIdNotAvailable"; + public static final String USER_EXCEPTION_USERID_NOTNUMERIC ="userExceptionUserIdNotNumeric"; + public static final String USER_EXCEPTION_ONLYCONTENT_ANDNOSESSIONS ="userExceptionOnlyContentAndNoSessions"; + public static final String USER_EXCEPTION_USERID_EXISTING ="userExceptionUserIdExisting"; + public static final String USER_EXCEPTION_USER_DOESNOTEXIST ="userExceptionUserDoesNotExist"; + public static final String USER_EXCEPTION_MONITORINGTAB_CONTENTID_REQUIRED ="userExceptionMonitoringTabContentIdRequired"; + public static final String USER_EXCEPTION_DEFAULTCONTENT_NOTSETUP ="userExceptionDefaultContentNotSetup"; + public static final String USER_EXCEPTION_NO_TOOL_SESSIONS ="userExceptionNoToolSessions"; + + /* + * export portfolio constants + */ + public static final String LEARNER ="learner"; + public static final String TEACHER ="teacher"; + public static final String USER_EXCEPTION_MODE_REQUIRED ="userExceptionModeRequired"; + public static final String PORTFOLIO_REPORT ="portfolioReport"; + public static final String PORTFOLIO_REQUEST ="portfolioRequest"; + public static final int MAX_GROUPS_COUNT =250; + + /* + * user actions + */ + public static final String ADD_NEW_QUESTION ="addNewQuestion"; + public static final String REMOVE_QUESTION ="removeQuestion"; + public static final String REMOVE_ALL_CONTENT ="removeAllContent"; + public static final String SUBMIT_ALL_CONTENT ="submitAllContent"; + public static final String SUBMIT_TAB_DONE ="submitTabDone"; + + public static final String OPTION_OFF ="false"; + + /* learner mode contants */ + public static final String MAP_QUESTION_CONTENT_LEARNER ="mapQuestionContentLearner"; + public static final String CURRENT_QUESTION_INDEX ="currentQuestionIndex"; + public static final String TOTAL_QUESTION_COUNT ="totalQuestionCount"; + public static final String LEARNER_MARK ="learnerMark"; + public static final String LEARNER_BEST_MARK ="learnerBestMark"; + public static final String LEARNER_LAST_ATTEMPT_ORDER ="learnerLastAttemptOrder"; + public static final String LEARNER_MARK_ATLEAST ="learnerMarkAtLeast"; + public static final String MAP_ANSWERS ="mapAnswers"; + public static final String CURRENT_ANSWER ="currentAnswer"; + public static final String USER_FEEDBACK ="userFeedback"; + public static final String REPORT_TITLE ="reportTitle"; + public static final String MONITORING_REPORT_TITLE ="monitoringReportTitle"; + public static final String REPORT_TITLE_LEARNER ="reportTitleLearner"; + public static final String END_LEARNING_MESSAGE ="endLearningMessage"; + public static final String TOTAL_COUNT_REACHED ="totalCountReached"; + + + public static final String IS_TOOL_ACTIVITY_OFFLINE ="isToolActivityOffline"; + public static final String IS_USERNAME_VISIBLE ="isUsernameVisible"; + public static final String IS_CONTENT_IN_USE ="isContentInUse"; + public static final String IS_RETRIES ="isRetries"; + public static final String IS_SHOW_FEEDBACK ="isShowFeedback"; + public static final String IS_SHOW_LEARNERS_REPORT ="isShowLearnersReport"; + public static final String IS_ALL_SESSIONS_COMPLETED ="isAllSessionsCompleted"; + public static final String CHECK_ALL_SESSIONS_COMPLETED ="checkAllSessionsCompleted"; + public static final String FROM_TOOL_CONTENT_ID ="fromToolContentId"; + public static final String TO_TOOL_CONTENT_ID ="toToolContentId"; + public static final String LEARNER_REPORT ="learnerReport"; + public static final String MAP_USER_RESPONSES ="mapUserResponses"; + public static final String MAP_MAIN_REPORT ="mapMainReport"; + public static final String MAP_STATS ="mapStats"; + public static final String ACTIVITY_TITLE ="activityTitle"; + public static final String ACTIVITY_INSTRUCTIONS ="activityInstructions"; + + /* + * Monitoring Mode constants + */ + public static final String REPORT_TITLE_MONITOR ="reportTitleMonitor"; + public static final String MONITOR_USER_ID ="userId"; + public static final String MONITORING_REPORT ="monitoringReport"; + public static final String MONITORING_ERROR ="monitoringError"; + public static final String MAP_MONITORING_QUESTIONS ="mapMonitoringQuestions"; + public static final String SUMMARY_TOOL_SESSIONS ="summaryToolSessions"; + public static final String CURRENT_MONITORED_TOOL_SESSION ="currentMonitoredToolSession"; + public static final String CHOICE_MONITORING ="choiceMonitoring"; + public static final String CHOICE_TYPE_MONITORING_SUMMARY ="choiceTypeMonitoringSummary"; + public static final String CHOICE_TYPE_MONITORING_INSTRUCTIONS ="choiceTypeMonitoringInstructions"; + public static final String CHOICE_TYPE_MONITORING_EDITACTIVITY ="choiceTypeMonitoringEditActivity"; + public static final String CHOICE_TYPE_MONITORING_STATS ="choiceTypeMonitoringStats"; + public static final String MONITORING_INSTRUCTIONS_VISITED ="monitoringInstructionsVisited"; + public static final String MONITORING_EDITACTIVITY_VISITED ="monitoringEditActivityVisited"; + public static final String MONITORING_STATS_VISITED ="monitoringStatsVisited"; + public static final String DATAMAP_EDITABLE ="dataMapEditable"; + public static final String DATAMAP_EDITABLE_RESPONSE_ID ="dataMapEditableResponseId"; + public static final String DATAMAP_HIDDEN_RESPONSE_ID ="dataMapHiddenResponseId"; + public static final String MONITORED_CONTENT_ID ="monitoredContentId"; + public static final String START_MONITORING_SUMMARY_REQUEST ="startMonitoringSummaryRequest"; + public static final String STOP_RENDERING_QUESTIONS ="stopRenderingQuestions"; + public static final String EDITACTIVITY_EDITMODE ="editActivityEditMode"; + public static final String FORM_INDEX ="formIndex"; + public static final String RENDER_MONITORING_EDITACTIVITY ="renderMonitoringEditActivity"; + public static final String NO_AVAILABLE_SESSIONS ="noAvailableSessions"; + public static final String INITIAL_MONITORING_TOOL_CONTENT_ID ="initialMonitoringToolContentId"; + public static final String IS_MONITORING_DEFINE_LATER ="isMonitoringDefineLater"; + public static final String NO_TOOL_SESSIONS_AVAILABLE ="noToolSessionAvailable"; + public static final String ORIGINAL_TOOL_SESSIONS ="originalToolSessions"; + + public static final String MONITORED_OFFLINE_INSTRUCTIONS ="monitoredOfflineInstructions"; + public static final String MONITORED_ONLINE_INSTRUCTIONS ="monitoredOnlineInstructions"; + public static final String MONITORING_INSTRUCTIONS_UPDATE_MESSAGE ="monitoringInstructionsUpdateMessage"; + + /* + * Monitor and Learning common constants - used in jsp reporting + */ + public static final String FULLNAME ="fullName"; + public static final String ANSWER ="answer"; + public static final String ATIME ="aTime"; + public static final String FORMATTED_ATIME ="formattedAtime"; + public static final String RESPONSE_ID ="responseId"; + public static final String RESPONSE_HIDDEN ="responseHidden"; + public static final String CURRENTLEARNER_FULLNAME ="currentLearnerFullname"; + public static final String ATTR_USERDATA ="qa_user"; + public static final String TIMEZONE ="timeZone"; + public static final String TIMEZONE_ID ="timeZoneId"; + + /* + * following tell whether author prefers to have the questions listed all in one page or listed sequentially. The default is all in one page. + */ + public static final String QUESTION_LISTING_MODE ="questionListingMode"; + public static final String QUESTION_LISTING_MODE_SEQUENTIAL ="questionListingModeSequential"; + public static final String QUESTION_LISTING_MODE_COMBINED ="questionListingModeCombined"; + + public static final String FEEDBACK_TYPE_SEQUENTIAL ="You will be presented a total of : "; + public static final String FEEDBACK_TYPE_COMBINED ="You are being presented a total of : "; + public static final String QUESTIONS =" questions."; + + /* + * constants redundant for the moment + */ + public static final String DISPLAY_QUESTIONS ="display"; + public static final String SUBMIT_QUESTIONS ="submit"; + public static final String VIEW_INDIVIDUAL_SUMMARY ="view"; +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McApplicationException.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McApplicationException.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McApplicationException.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,73 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc; + + +/** + *

This exception wraps all basic exception occured in the mcq tool. It is + * not suppose to be try and catched in any level. The struts should be taking + * care of handling this exception.

+ * +* @author Ozgur Demirtas + * + */ +public class McApplicationException extends RuntimeException +{ + /** + * Default Constructor + */ + public McApplicationException() + { + super(); + } + + /** + * Constructor for customized error message + * @param message + */ + public McApplicationException(String message) + { + super(message); + } + + /** + * Constructor for wrapping the throwable object + * @param cause + */ + public McApplicationException(Throwable cause) + { + super(cause); + } + + /** + * Constructor for wrapping both the customized error message and + * throwable exception object. + * @param message + * @param cause + */ + public McApplicationException(String message, Throwable cause) + { + super(message, cause); + } + +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McComparator.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McComparator.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McComparator.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,50 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc; + +import java.io.Serializable; +import java.util.Comparator; + +/** + * @author Ozgur Demirtas + * A comparator implementation that can be used as a constructor to collections. + * The TreeMap in the web layer makes use of it. + * + */ +public class McComparator implements Comparator, Serializable { + + public int compare(Object o1, Object o2) { + String s1 = (String)o1; + String s2 = (String)o2; + + int key1=new Long(s1).intValue(); + int key2=new Long(s2).intValue(); + //logger.debug(logger + " " + this.getClass().getName() + "comparing key1 and key2:" + key1 + " and " + key2); + return key1 - key2; + } + + public boolean equals(Object o) { + String s = (String)o; + return compare(this, o)==0; + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McContent.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McContent.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McContent.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,427 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc; + +import java.io.Serializable; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + *

Persistent object/bean that defines the content for the MCQ tool. + * Provides accessors and mutators to get/set attributes + * It maps to database table: tl_lamc11_content + *

+ * + * @author Ozgur Demirtas + */ +public class McContent implements Serializable { + + /** identifier field */ + private Long uid; + + /** persistent field */ + private Long mcContentId; + + /** nullable persistent field */ + private String title; + + /** nullable persistent field */ + private String instructions; + + /** nullable persistent field */ + private boolean defineLater; + + /** nullable persistent field */ + private boolean runOffline; + + /** nullable persistent field */ + private String creationDate; + + /** nullable persistent field */ + private Date updateDate; + + /** nullable persistent field */ + private boolean questionsSequenced; + + /** nullable persistent field */ + private boolean usernameVisible; + + /** nullable persistent field */ + private String reportTitle; + + /** nullable persistent field */ + private String monitoringReportTitle; + + /** nullable persistent field */ + private long createdBy; + + /** nullable persistent field */ + private boolean synchInMonitor; + + /** nullable persistent field */ + private boolean contentInUse; + + /** nullable persistent field */ + private String offlineInstructions; + + /** nullable persistent field */ + private String onlineInstructions; + + /** nullable persistent field */ + private String endLearningMessage; + + /** nullable persistent field */ + private boolean retries; + + private boolean showReport; + + + /** nullable persistent field */ + private Integer passMark; + + /** nullable persistent field */ + private boolean showFeedback; + + + /** persistent field */ + private Set mcQueContents; + + /** persistent field */ + private Set mcSessions; + + /** full constructor */ + public McContent(Long mcContentId, String title, String instructions, boolean defineLater, boolean runOffline, String creationDate, Date updateDate, boolean questionsSequenced, boolean usernameVisible, String reportTitle, String monitoringReportTitle, long createdBy, boolean synchInMonitor, boolean contentInUse, String offlineInstructions, String onlineInstructions, String endLearningMessage, Integer passMark, boolean showFeedback, boolean retries, Set mcQueContents, Set mcSessions) { + this.mcContentId = mcContentId; + this.title = title; + this.instructions = instructions; + this.defineLater = defineLater; + this.runOffline = runOffline; + this.creationDate = creationDate; + this.updateDate = updateDate; + this.questionsSequenced = questionsSequenced; + this.usernameVisible = usernameVisible; + this.reportTitle = reportTitle; + this.monitoringReportTitle = monitoringReportTitle; + this.createdBy = createdBy; + this.synchInMonitor = synchInMonitor; + this.contentInUse = contentInUse; + this.offlineInstructions = offlineInstructions; + this.onlineInstructions = onlineInstructions; + this.endLearningMessage = endLearningMessage; + this.passMark = passMark; + this.retries=retries; + this.showFeedback = showFeedback; + this.mcQueContents = mcQueContents; + this.mcSessions = mcSessions; + } + + /** default constructor */ + public McContent() { + } + + /** minimal constructor */ + public McContent(Long mcContentId, Set mcQueContents, Set mcSessions) { + this.mcContentId = mcContentId; + this.mcQueContents = mcQueContents; + this.mcSessions = mcSessions; + } + + + /** + * gets called as part of the copyToolContent + * + * Copy Construtor to create a new mc content instance. Note that we + * don't copy the mc session data here because the mc session + * will be created after we copied tool content. + * @param mc the original mc content. + * @param newContentId the new mc content id. + * @return the new mc content object. + */ + public static McContent newInstance(McContent mc, + Long newContentId) + { + McContent newContent = new McContent( + newContentId, + mc.getTitle(), + mc.getInstructions(), + mc.isDefineLater(), + mc.isRunOffline(), + mc.getCreationDate(), + mc.getUpdateDate(), + mc.isQuestionsSequenced(), + mc.isUsernameVisible(), + mc.getReportTitle(), + mc.getMonitoringReportTitle(), + mc.getCreatedBy(), + mc.isSynchInMonitor(), + mc.isContentInUse(), + mc.getOfflineInstructions(), + mc.getOnlineInstructions(), + mc.getEndLearningMessage(), + mc.getPassMark(), + mc.isRetries(), + mc.isShowFeedback(), + new TreeSet(), + new TreeSet()); + newContent.setMcQueContents(mc.deepCopyMcQueContent(newContent)); + return newContent; + } + + /** + * gets called as part of the copyToolContent + * + * @param newQaContent + * @return + */ + public Set deepCopyMcQueContent(McContent newQaContent) + { + Set newMcQueContent = new TreeSet(); + for (Iterator i = this.getMcQueContents().iterator(); i.hasNext();) + { + McQueContent queContent = (McQueContent) i.next(); + newMcQueContent.add(McQueContent.newInstance(queContent, + newQaContent, + null)); + } + return newMcQueContent; + } + + public Long getUid() { + return this.uid; + } + + public void setUid(Long uid) { + this.uid = uid; + } + + public Long getMcContentId() { + return this.mcContentId; + } + + public void setMcContentId(Long mcContentId) { + this.mcContentId = mcContentId; + } + + public String getTitle() { + return this.title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getInstructions() { + return this.instructions; + } + + public void setInstructions(String instructions) { + this.instructions = instructions; + } + + public boolean isDefineLater() { + return this.defineLater; + } + + public void setDefineLater(boolean defineLater) { + this.defineLater = defineLater; + } + + public boolean isRunOffline() { + return this.runOffline; + } + + public void setRunOffline(boolean runOffline) { + this.runOffline = runOffline; + } + + public String getCreationDate() { + return this.creationDate; + } + + public void setCreationDate(String creationDate) { + this.creationDate = creationDate; + } + + public Date getUpdateDate() { + return this.updateDate; + } + + public void setUpdateDate(Date updateDate) { + this.updateDate = updateDate; + } + + public boolean isQuestionsSequenced() { + return this.questionsSequenced; + } + + public void setQuestionsSequenced(boolean questionsSequenced) { + this.questionsSequenced = questionsSequenced; + } + + public boolean isUsernameVisible() { + return this.usernameVisible; + } + + public void setUsernameVisible(boolean usernameVisible) { + this.usernameVisible = usernameVisible; + } + + public String getReportTitle() { + return this.reportTitle; + } + + public void setReportTitle(String reportTitle) { + this.reportTitle = reportTitle; + } + + public String getMonitoringReportTitle() { + return this.monitoringReportTitle; + } + + public void setMonitoringReportTitle(String monitoringReportTitle) { + this.monitoringReportTitle = monitoringReportTitle; + } + + public long getCreatedBy() { + return this.createdBy; + } + + public void setCreatedBy(long createdBy) { + this.createdBy = createdBy; + } + + public boolean isSynchInMonitor() { + return this.synchInMonitor; + } + + public void setSynchInMonitor(boolean synchInMonitor) { + this.synchInMonitor = synchInMonitor; + } + + public boolean isContentInUse() { + return this.contentInUse; + } + + public void setContentInUse(boolean contentInUse) { + this.contentInUse = contentInUse; + } + + public String getOfflineInstructions() { + return this.offlineInstructions; + } + + public void setOfflineInstructions(String offlineInstructions) { + this.offlineInstructions = offlineInstructions; + } + + public String getOnlineInstructions() { + return this.onlineInstructions; + } + + public void setOnlineInstructions(String onlineInstructions) { + this.onlineInstructions = onlineInstructions; + } + + public String getEndLearningMessage() { + return this.endLearningMessage; + } + + public void setEndLearningMessage(String endLearningMessage) { + this.endLearningMessage = endLearningMessage; + } + + public Integer getPassMark() { + return this.passMark; + } + + public void setPassMark(Integer passMark) { + this.passMark = passMark; + } + + public boolean isShowFeedback() { + return this.showFeedback; + } + + public void setShowFeedback(boolean showFeedback) { + this.showFeedback = showFeedback; + } + + + public Set getMcQueContents() { + if (this.mcQueContents == null) + setMcQueContents(new HashSet()); + return this.mcQueContents; + } + + + public void setMcQueContents(Set mcQueContents) { + this.mcQueContents = mcQueContents; + } + + public Set getMcSessions() { + if (this.mcSessions == null) + setMcSessions(new HashSet()); + return this.mcSessions; + } + + public void setMcSessions(Set mcSessions) { + this.mcSessions = mcSessions; + } + + public String toString() { + return new ToStringBuilder(this) + .append("uid", getUid()) + .toString(); + } + + /** + * @return Returns the retries. + */ + public boolean isRetries() { + return retries; + } + /** + * @param retries The retries to set. + */ + public void setRetries(boolean retries) { + this.retries = retries; + } + + /** + * @return Returns the showReport. + */ + public boolean isShowReport() { + return showReport; + } + /** + * @param showReport The showReport to set. + */ + public void setShowReport(boolean showReport) { + this.showReport = showReport; + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McOptsContent.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McOptsContent.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McOptsContent.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,165 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.lang.builder.ToStringBuilder; + + +/** + *

Persistent object/bean that defines the content for the MCQ tool. + * Provides accessors and mutators to get/set attributes + * It maps to database table: tl_lamc11_options_content + *

+ * + * @author Ozgur Demirtas + */ +public class McOptsContent implements Serializable { + + /** identifier field */ + private Long uid; + + private Long mcQueOptionId; + + /** nullable persistent field */ + private boolean correctOption; + + /** nullable persistent field */ + private String mcQueOptionText; + + /** non persistent field */ + private Long mcQueContentId; + + /** persistent field */ + private org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent; + + /** persistent field */ + private Set mcUsrAttempts; + + + public McOptsContent(Long mcQueOptionId, boolean correctOption, String mcQueOptionText, org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent, Set mcUsrAttempts) { + this.mcQueOptionId=mcQueOptionId; + this.correctOption = correctOption; + this.mcQueOptionText = mcQueOptionText; + this.mcQueContent = mcQueContent; + this.mcUsrAttempts=mcUsrAttempts; + } + + + public McOptsContent(boolean correctOption, String mcQueOptionText, org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent, Set mcUsrAttempts) { + this.correctOption = correctOption; + this.mcQueOptionText = mcQueOptionText; + this.mcQueContent = mcQueContent; + this.mcUsrAttempts=mcUsrAttempts; + } + + + /** default constructor */ + public McOptsContent() { + } + + public Long getUid() { + return this.uid; + } + + public void setUid(Long uid) { + this.uid = uid; + } + + + public boolean isCorrectOption() { + return this.correctOption; + } + + public void setCorrectOption(boolean correctOption) { + this.correctOption = correctOption; + } + + public String getMcQueOptionText() { + return this.mcQueOptionText; + } + + public void setMcQueOptionText(String mcQueOptionText) { + this.mcQueOptionText = mcQueOptionText; + } + + public org.lamsfoundation.lams.tool.mc.McQueContent getMcQueContent() { + return this.mcQueContent; + } + + public void setMcQueContent(org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent) { + this.mcQueContent = mcQueContent; + } + + + public String toString() { + return new ToStringBuilder(this) + .append("uid", getUid()) + .toString(); + } + + /** + * @return Returns the mcQueOptionId. + */ + public Long getMcQueOptionId() { + return mcQueOptionId; + } + /** + * @param mcQueOptionId The mcQueOptionId to set. + */ + public void setMcQueOptionId(Long mcQueOptionId) { + this.mcQueOptionId = mcQueOptionId; + } + /** + * @return Returns the mcUsrAttempts. + */ + + + public Set getMcUsrAttempts() { + if (this.mcUsrAttempts == null) + setMcUsrAttempts(new HashSet()); + return this.mcUsrAttempts; + } + /** + * @param mcUsrAttempts The mcUsrAttempts to set. + */ + public void setMcUsrAttempts(Set mcUsrAttempts) { + this.mcUsrAttempts = mcUsrAttempts; + } + + /** + * @return Returns the mcQueContentId. + */ + public Long getMcQueContentId() { + return mcQueContentId; + } + /** + * @param mcQueContentId The mcQueContentId to set. + */ + public void setMcQueContentId(Long mcQueContentId) { + this.mcQueContentId = mcQueContentId; + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McQueContent.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McQueContent.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McQueContent.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,322 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.commons.lang.builder.ToStringBuilder; + + +/** + *

Persistent object/bean that defines the question content for the MCQ tool. + * Provides accessors and mutators to get/set attributes + * It maps to database table: tl_lamc11_que_content + *

+ * + * @author Ozgur Demirtas + */ +public class McQueContent implements Serializable { + + /** identifier field */ + private Long uid; + + /** persistent field */ + private Long mcQueContentId; + + /** nullable persistent field */ + private String question; + + /** nullable persistent field */ + private Integer displayOrder; + + /** nullable persistent field */ + private Integer weight; + + /** persistent field */ + private boolean disabled; + + private String feedbackCorrect; + + private String feedbackIncorrect; + + + /** non persistent field */ + private Long mcContentId; + + /** persistent field */ + private org.lamsfoundation.lams.tool.mc.McContent mcContent; + + /** persistent field */ + private Set mcUsrAttempts; + + /** persistent field */ + private Set mcOptionsContents; + + /** full constructor */ + public McQueContent(Long mcQueContentId, String question, Integer displayOrder, McContent mcContent, Set mcUsrAttempts, Set mcOptionsContents) { + this.mcQueContentId = mcQueContentId; + this.question = question; + this.displayOrder = displayOrder; + this.mcContent=mcContent; + this.mcUsrAttempts = mcUsrAttempts; + this.mcOptionsContents = mcOptionsContents; + } + + public McQueContent(String question, Integer displayOrder, McContent mcContent, Set mcUsrAttempts, Set mcOptionsContents) { + this.question = question; + this.displayOrder = displayOrder; + this.mcContent=mcContent; + this.mcUsrAttempts = mcUsrAttempts; + this.mcOptionsContents = mcOptionsContents; + } + + public McQueContent(String question, Integer displayOrder, Integer weight, boolean disabled, McContent mcContent, Set mcUsrAttempts, Set mcOptionsContents) { + this.question = question; + this.displayOrder = displayOrder; + this.weight = weight; + this.disabled = disabled; + this.mcContent=mcContent; + this.mcUsrAttempts = mcUsrAttempts; + this.mcOptionsContents = mcOptionsContents; + } + + public McQueContent(String question, Integer displayOrder, Integer weight, boolean disabled, String feedbackIncorrect, String feedbackCorrect, McContent mcContent, Set mcUsrAttempts, Set mcOptionsContents) { + this.question = question; + this.displayOrder = displayOrder; + this.weight = weight; + this.disabled = disabled; + this.feedbackIncorrect = feedbackIncorrect; + this.feedbackCorrect = feedbackCorrect; + this.mcContent=mcContent; + this.mcUsrAttempts = mcUsrAttempts; + this.mcOptionsContents = mcOptionsContents; + } + + + public McQueContent(String question, Integer displayOrder, Integer weight, String feedbackCorrect, String feedbackIncorrect, boolean disabled, McContent mcContent, Set mcUsrAttempts, Set mcOptionsContents) { + this.question = question; + this.displayOrder = displayOrder; + this.weight = weight; + this.disabled = disabled; + this.feedbackCorrect=feedbackCorrect; + this.feedbackIncorrect=feedbackIncorrect; + this.mcContent=mcContent; + this.mcUsrAttempts = mcUsrAttempts; + this.mcOptionsContents = mcOptionsContents; + } + + + public McQueContent(Long mcQueContentId, String question, Integer displayOrder, Set mcUsrAttempts, Set mcOptionsContents) { + this.mcQueContentId = mcQueContentId; + this.question = question; + this.displayOrder = displayOrder; + this.mcUsrAttempts = mcUsrAttempts; + this.mcOptionsContents = mcOptionsContents; + } + + public McQueContent(Long mcQueContentId, String question, Integer displayOrder, Integer weight, Set mcUsrAttempts, Set mcOptionsContents) { + this.mcQueContentId = mcQueContentId; + this.question = question; + this.displayOrder = displayOrder; + this.weight=weight; + this.mcUsrAttempts = mcUsrAttempts; + this.mcOptionsContents = mcOptionsContents; + } + + + + public McQueContent(String question, Integer displayOrder, Set mcUsrAttempts, Set mcOptionsContents) { + this.question = question; + this.displayOrder = displayOrder; + this.mcUsrAttempts = mcUsrAttempts; + this.mcOptionsContents = mcOptionsContents; + } + + + + /** default constructor */ + public McQueContent() { + } + + /** minimal constructor */ + public McQueContent(Long mcQueContentId, org.lamsfoundation.lams.tool.mc.McContent mcContent, Set mcUsrAttempts, Set mcOptionsContents) { + this.mcQueContentId = mcQueContentId; + this.mcContent = mcContent; + this.mcUsrAttempts = mcUsrAttempts; + this.mcOptionsContents = mcOptionsContents; + } + + + /** + * gets called by copyToolContent + * + * Copy constructor + * @param queContent the original qa question content + * @return the new qa question content object + */ + public static McQueContent newInstance(McQueContent queContent, + McContent newMcContent, + McQueContent parentQuestion) + { + McQueContent newQueContent = new McQueContent(queContent.getQuestion(), + queContent.getDisplayOrder(), + queContent.getWeight(), + queContent.isDisabled(), + newMcContent, + new TreeSet(), + new TreeSet()); + return newQueContent; + } + + public Long getUid() { + return this.uid; + } + + public void setUid(Long uid) { + this.uid = uid; + } + + public Long getMcQueContentId() { + return this.mcQueContentId; + } + + public void setMcQueContentId(Long mcQueContentId) { + this.mcQueContentId = mcQueContentId; + } + + public String getQuestion() { + return this.question; + } + + public void setQuestion(String question) { + this.question = question; + } + + public Integer getDisplayOrder() { + return this.displayOrder; + } + + public void setDisplayOrder(Integer displayOrder) { + this.displayOrder = displayOrder; + } + + public org.lamsfoundation.lams.tool.mc.McContent getMcContent() { + return this.mcContent; + } + + public void setMcContent(org.lamsfoundation.lams.tool.mc.McContent mcContent) { + this.mcContent = mcContent; + } + + public Set getMcUsrAttempts() { + if (this.mcUsrAttempts == null) + setMcUsrAttempts(new HashSet()); + return this.mcUsrAttempts; + } + + + public void setMcUsrAttempts(Set mcUsrAttempts) { + this.mcUsrAttempts = mcUsrAttempts; + } + + + public Set getMcOptionsContents() { + if (this.mcOptionsContents == null) + setMcOptionsContents(new HashSet()); + return this.mcOptionsContents; + } + + public void setMcOptionsContents(Set mcOptionsContents) { + this.mcOptionsContents = mcOptionsContents; + } + + public String toString() { + return new ToStringBuilder(this) + .append("uid", getUid()) + .toString(); + } + + /** + * @return Returns the mcContentId. + */ + public Long getMcContentId() { + return mcContentId; + } + /** + * @param mcContentId The mcContentId to set. + */ + public void setMcContentId(Long mcContentId) { + this.mcContentId = mcContentId; + } + /** + * @return Returns the disabled. + */ + public boolean isDisabled() { + return disabled; + } + /** + * @param disabled The disabled to set. + */ + public void setDisabled(boolean disabled) { + this.disabled = disabled; + } + /** + * @return Returns the weight. + */ + public Integer getWeight() { + return weight; + } + /** + * @param weight The weight to set. + */ + public void setWeight(Integer weight) { + this.weight = weight; + } + /** + * @return Returns the feedbackCorrect. + */ + public String getFeedbackCorrect() { + return feedbackCorrect; + } + /** + * @param feedbackCorrect The feedbackCorrect to set. + */ + public void setFeedbackCorrect(String feedbackCorrect) { + this.feedbackCorrect = feedbackCorrect; + } + /** + * @return Returns the feedbackIncorrect. + */ + public String getFeedbackIncorrect() { + return feedbackIncorrect; + } + /** + * @param feedbackIncorrect The feedbackIncorrect to set. + */ + public void setFeedbackIncorrect(String feedbackIncorrect) { + this.feedbackIncorrect = feedbackIncorrect; + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McQueUsr.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McQueUsr.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McQueUsr.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,138 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.lang.builder.ToStringBuilder; + + +/** + *

Persistent object/bean that defines the user for the MCQ tool. + * Provides accessors and mutators to get/set attributes + * It maps to database table: tl_lamc11_que_usr + *

+ * + * @author Ozgur Demirtas + */ +public class McQueUsr implements Serializable { + + /** identifier field */ + private Long uid; + + /** persistent field */ + private Long queUsrId; + + /** nullable persistent field */ + private String username; + + /** nullable persistent field */ + private String fullname; + + + /** nullable persistent field */ + private org.lamsfoundation.lams.tool.mc.McSession mcSession; + + /** persistent field */ + private Set mcUsrAttempts; + + /** full constructor */ + public McQueUsr(Long queUsrId, String username, String fullname, org.lamsfoundation.lams.tool.mc.McSession mcSession, Set mcUsrAttempts) { + this.queUsrId = queUsrId; + this.username = username; + this.fullname = fullname; + this.mcSession = mcSession; + this.mcUsrAttempts = mcUsrAttempts; + } + + /** default constructor */ + public McQueUsr() { + } + + /** minimal constructor */ + public McQueUsr(Long queUsrId, Set mcUsrAttempts) { + this.queUsrId = queUsrId; + this.mcUsrAttempts = mcUsrAttempts; + } + + public Long getUid() { + return this.uid; + } + + public void setUid(Long uid) { + this.uid = uid; + } + + public Long getQueUsrId() { + return this.queUsrId; + } + + public void setQueUsrId(Long queUsrId) { + this.queUsrId = queUsrId; + } + + public String getUsername() { + return this.username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getFullname() { + return this.fullname; + } + + public void setFullname(String fullname) { + this.fullname = fullname; + } + + + public org.lamsfoundation.lams.tool.mc.McSession getMcSession() { + return this.mcSession; + } + + public void setMcSession(org.lamsfoundation.lams.tool.mc.McSession mcSession) { + this.mcSession = mcSession; + } + + public Set getMcUsrAttempts() { + if (this.mcUsrAttempts == null) + setMcUsrAttempts(new HashSet()); + return this.mcUsrAttempts; + } + + + public void setMcUsrAttempts(Set mcUsrAttempts) { + this.mcUsrAttempts = mcUsrAttempts; + } + + public String toString() { + return new ToStringBuilder(this) + .append("uid", getUid()) + .toString(); + } + +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McResources.properties =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McResources.properties (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McResources.properties (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,208 @@ +# Project lams_tool_lamc11 +#Authoring mode resources +label.authoring.mc =Multiple Choice +label.authoring.mc.basic =Please define the questions. +label.mc.questions =Multiple Choice Questions +label.authoring.mc.basic.editOptions =Please define the question and/or its options. +label.authoring.title =Title +label.authoring.instructions =Instructions +label.Questions =Questions +label.weight =Weight +label.action =Action +label.actions =Actions +label.addNewQuestion =Add New Question +label.moveDown =Down + +label.add.question =Add Question +label.add.option =Add Option +label.mc.options =Candidate Answers +label.fileContent =File Content +label.assessment =Assessment +label.learner.message =Answer the questions until you reach the passmark. +label.withRetries =Multiple Choice with Retries +label.withoutRetries =Multiple Choice without Retries +label.individual.results.withRetries =Results for Multiple Choice with Retries +label.individual.results.withoutRetries =Results for Multiple Choice without Retries +label.viewAnswers =Previous Answers +label.withRetries.results.summary =Multiple Choice with Retries Summary +label.withoutRetries.results.summary =Multiple Choice without Retries Summary +label.learnersFinished =learners have finished. Minimum passmark is +label.topMark =Top Mark: +label.avMark =Average Mark: +label.loMark =Lowest Mark: + +label.mark =Mark: +label.you.answered =You answered: +label.redo.questions =Redo Questions +label.view.summary =View Summary +label.view.answers =View Answers +label.finished =Finished +label.attempt =Attempt + + +button.basic =Basic +button.uploadFile =Upload Package +button.preview =Preview +button.advanced =Advanced +button.instructions =Instructions +button.done =Done +tool.icon.name =MC +button.add =Add +button.addNewQuestion =Add +button.remove =Delete +button.removeQuestion =Delete +button.removeAllContent =Remove Content +button.submitAllContent =Submit +button.submit =Submit +button.done =Done +button.getNextQuestion =Next +button.next =Next +button.nextQuestion =Next Question +button.continue =Continue +button.getPreviousQuestion =Previous +button.editQuestion =Edit +label.percent =% +label.option =Option +label.option1 =Option 1 +label.options =Options +label.option.correct =Correct +label.candidateAnswers =Candidate Answers +label.isCorrect =Correct? + + +label.monitoringReport.title =Monitoring Report Title +label.question.only =Question +label.question =Question: +label.question1 =Question 1 +radiobox.defineLater =Define Later +radiobox.synchInMonitor =Sync in Monitor +radiobox.forceOffline =Force Offline +radiobox.usernameVisible =Username Visible +radiobox.questionsSequenced =Questions Sequenced +radiobox.passmark =Pass Mark +radiobox.showFeedback =Show Feedback +radiobox.sln =Show Learner's Report +radiobox.onepq =1 page per question +radiobox.retries =Allow Retries +label.report.title =Report Title +label.report.endLearningMessage =End of Activity Message + +label.offlineInstructions =Offline Instructions +label.onlineInstructions =Online Instructions +label.offlineFiles =Offline Files: +label.onlineFiles =Online Files: +label.upload =Upload +label.uploadedOfflineFiles =Uploaded Offline Files: +label.uploadedOnlineFiles =Uploaded Online Files: +option.on =ON +option.off =OFF +option.correct =Correct +option.incorrect =Incorrect +label.feedback.incorrect =Feedback if answered incorrectly: +label.feedback.correct =Feedback if answered correctly: +label.learner.redo =Are you sure you want to answer the questions again? +label.learner.bestMark =Your best mark so far is +label.outof =out of +label.mustGet =Must get at least +label.toFinish =to finish + + +feedback =Please address the following issues before submit.
+error.default.content.notSetup =The tool initialization error: The tool default content has not been set up properly. +error.questions.submitted.none =Please correct this: No questions have been submitted. +error.question.empty =Please correct this: The question text can not be empty. +error.weights.empty =Please correct this: The question weights can not be empty. +error.checkBoxes.empty =Please correct this: No candidate answer has been selected. +error.weights.zero =Please correct this: The question weights can not be 0. +error.weights.notInteger =Please correct this: The question weights must be an integer. +error.question.weight.total =Please correct this: The total question weight:100 has been reached. +error.answers.duplicate =Please correct this: The candidate answers must be unique. +error.emptyQuestion =Please enter the question text. The chosen question can not be empty. +error.title =Please correct this: The field "Title" is mandatory.
+error.instructions =Please correct this: The field "Instructions" is mandatory.
+error.reportTitle =Please correct this: The field "Report Title (Advanced)" is mandatory.
+error.defaultquestion.empty =Please correct this: The first question can not be empty.
+error.passMark.empty =Please correct this: Pass Mark can not be empty. +options.count.zero =Please correct this: There must be at least one candidate answer. +error.passmark.notInteger =Please correct this: Pass Mark can only be an integer. +error.weights.total.invalid =Please correct this: The total weight must equal 100. +error.file.notPersisted =An error occurred: The file is not viewable yet. Please save all the content first and check back. +error.learningUser.notAvailable =Tool Activity Error! Can't continue. Tool Activity expects a user id. + +submit.successful =The content has been created successfully. + +error.question.addNotAllowed.thisScreen = The question text can not be modified in this screen since it has options attached . Please use the "Options" button to edit the question text. +error.question.removeNotAllowed.thisScreen = The question can not be removed since one or more of the question texts has been modified. Please try again without any text modifications. + +error.selectedIndex.empty =Can not continue. Please select the correct answer and click "Done". +error.content.locked =The content has been locked since it is being used by one mor more learners.
The modification of the content is not allowed. +error.content.inUse =The modification of the content is not allowed since one or more students has attempted the activity. +error.content.beingModified =The content creation is not allowed since the same content is being modified. +error.content.unstableState =The content is in an unstable state since it has been left editable while monitored.
Please use this screen to redefine the content. +error.defaultContent.notAvailable =Tool Activity Error! Can't continue
The the default content for the Tool Activity has not been set up. +error.defaultQuestionContent.notAvailable =Tool Activity Error! Can't continue
The the default question content for the Tool Activity has not been set up. +error.defaultOptionsContent.notAvailable =Tool Activity Error! Can't continue
The the default options content for the Tool Activity has not been set up. + + +#Learning mode resources +label.learning.qa =Answers for Q/A +label.question =Question +label.answers =Answers: +button.endLearning =Finish +label.learning.user =User +label.learning.attemptTime =Attempt Date/Time +label.learning.timezone =Time-Zone +label.learning.response =Response +label.learning.forceOfflineMessage =This is setup to be carried out offline. Plase see your instructor for details. +error.defineLater =Sorry, this activity's content is not ready yet.
Please wait for your teacher to make the content ready. +error.toolSessionId.required =Tool Activity Error! Can't continue
URL is not complete. The Tool Activity requires a toolSession id. +error.contentId.required =Tool Activity Error! Can't continue
URL is not complete. The Tool Activity requires a content id. +error.authoringUser.notAvailable =Tool Activity Error! Can't continue. Tool Activity expects a user id. +error.userId.required =Tool Activity Error! Can't continue
URL is not complete. The Tool Activity requires a user id. +error.userId.notNumeric =Tool Activity Error! Can't continue. The user id passed to the Tool Activity must be numerical. +error.userId.existing =Tool Activity Error! Can't continue. The user id passed to the Tool Activity refers to a student that has already used the activity.
Each learner activity should be associated with a unique userId. +error.defaultContent.notSetup =Tool Activity Error! Can't continue. The default content for the tool has not been setup properly. +error.mode.required =Tool Activity Error! Can't continue
URL is not complete. The Tool Activity requires a mode. + +#Monitoring mode resources +button.startLesson =Start Lesson +button.deleteLesson =Delete Lesson +button.contributeLesson =Contribute -> Report +button.forceComplete =Force Complete +error.synchInMonitor =The report is available only after all the students finish their activities.
+ Some of the students has not completed the activity yet. However, those students may be forced to complete. +error.monitorReportTitle =The field "Monitor Report Title (Advanced)" is mandatory.
+error.noStudentActivity =Sorry, the report can not be generated.
No student has attempted the activity yet. +error.contentAndToolSession.notCompatible =Tool Activity Error! Can't continue. The content id and tool session(s) passed to the tool activity are not compatible with each other.
The Tool Activity expects that each of the passed tool sessions refer to the same passed content id. +error.toolSessions.wrongFormat =Tool Activity Error! Can't continue. No valid tool sessions has been passed to the Tool Activity.
The expected format is: TOOLURL?toolContentId=A&toolSessionId1=B&toolSessionId2=C&toolSessionId3=D&... +error.numberFormatException =Tool Activity Error! Can't continue. The content id and tool session id(s) passed to the Tool Activity must be numerical. +error.contentId.numberFormatException =Tool Activity Error! Can't continue. The content id passed to the Tool Activity must be numerical. +error.sessionId.numberFormatException =Tool Activity Error! Can't continue. The toolSession id passed to the Tool Activity must be numerical. +error.content.doesNotExist =Tool Activity Error! Can't continue. The content id passed to the Tool Activity does not refer to an existing content. +error.toolSessions.doesNotExist =Tool Activity Error! Can't continue. One of the toolsession ids passed to the Tool Activity does not refer to an existing tool session. +error.toolSession.doesNotExist =Tool Activity Error! Can't continue. The toolsession id passed to the Tool Activity does not refer to an existing tool session. +error.content.onlyContentAndNoSessions =A report can not be generated since no tool sessions has been passed to the Tool Activity. +error.content.noToolSessions =A report can not be generated since there has not been any student activity on this content. +error.user.doesNotExist =Tool Activity Error! Can't continue. The user id passed to the Tool Activity does not refer to an existing user. +error.tab.contentId.required =Sorry, the screen is not available. The Tool Activity requires a content id. +monitoring.feedback.instructionUpdate =The content has been updated successfully. + + + +group.label =Group +button.summary =Summary +button.editActivity =Edit Activity +button.stats =Stats +label.edit =Edit +label.update =Update +label.hide =Hide +label.unHide =UnHide +label.hidden =Hidden +label.stats.totalLearners =Total count of learners: +label.stats.allGroups =All Groups: +label.stats.totalAllGroups =Total count of all learners: + +#=========================Error Messages===========================# +error.system.qa=A system exception has occured. Please contact Lams International technical support at 95806666. The error to report is\:
{0}
+ + Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McSession.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McSession.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McSession.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,190 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc; + +import java.io.Serializable; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.lang.builder.ToStringBuilder; + + +/** + *

Persistent object/bean that defines the content for the MCQ tool. + * Provides accessors and mutators to get/set attributes + * It maps to database table: tl_lamc11_session + *

+ * + * @author Ozgur Demirtas + */ +public class McSession implements Serializable { + + public final static String INCOMPLETE = "INCOMPLETE"; + + public static final String COMPLETED = "COMPLETED"; + + /** identifier field */ + private Long uid; + + /** persistent field */ + private Long mcSessionId; + + /** nullable persistent field */ + private Date sessionStartDate; + + /** nullable persistent field */ + private Date sessionEndDate; + + /** nullable persistent field */ + private String sessionStatus; + + /** nullable persistent field */ + private Long mcContentId; + + /** nullable persistent field */ + private org.lamsfoundation.lams.tool.mc.McContent mcContent; + + /** persistent field */ + private Set mcQueUsers; + + /** full constructor */ + public McSession(Long mcSessionId, Date sessionStartDate, Date sessionEndDate, String sessionStatus, org.lamsfoundation.lams.tool.mc.McContent mcContent, Set mcQueUsers) { + this.mcSessionId = mcSessionId; + this.sessionStartDate = sessionStartDate; + this.sessionEndDate = sessionEndDate; + this.sessionStatus = sessionStatus; + this.mcContent = mcContent; + this.mcQueUsers = mcQueUsers; + } + + public McSession(Long mcSessionId, Date sessionStartDate, String sessionStatus, org.lamsfoundation.lams.tool.mc.McContent mcContent, Set mcQueUsers) { + this.mcSessionId = mcSessionId; + this.sessionStartDate = sessionStartDate; + this.sessionStatus = sessionStatus; + this.mcContent = mcContent; + this.mcQueUsers = mcQueUsers; + } + + + /** default constructor */ + public McSession() { + } + + /** minimal constructor */ + public McSession(Long mcSessionId, Set mcQueUsers) { + this.mcSessionId = mcSessionId; + this.mcQueUsers = mcQueUsers; + } + + public Long getUid() { + return this.uid; + } + + public void setUid(Long uid) { + this.uid = uid; + } + + public Long getMcSessionId() { + return this.mcSessionId; + } + + public void setMcSessionId(Long mcSessionId) { + this.mcSessionId = mcSessionId; + } + + + public Long getMcContentId() { + return this.mcContentId; + } + + public void setMcContentId(Long mcContentId) { + this.mcContentId = mcContentId; + } + + public org.lamsfoundation.lams.tool.mc.McContent getMcContent() { + return this.mcContent; + } + + public void setMcContent(org.lamsfoundation.lams.tool.mc.McContent mcContent) { + this.mcContent = mcContent; + } + + public String toString() { + return new ToStringBuilder(this) + .append("uid", getUid()) + .toString(); + } + + /** + * @return Returns the sessionEndDate. + */ + public Date getSessionEndDate() { + return sessionEndDate; + } + /** + * @param sessionEndDate The sessionEndDate to set. + */ + public void setSessionEndDate(Date sessionEndDate) { + this.sessionEndDate = sessionEndDate; + } + /** + * @return Returns the sessionStartDate. + */ + public Date getSessionStartDate() { + return sessionStartDate; + } + /** + * @param sessionStartDate The sessionStartDate to set. + */ + public void setSessionStartDate(Date sessionStartDate) { + this.sessionStartDate = sessionStartDate; + } + /** + * @return Returns the sessionStatus. + */ + public String getSessionStatus() { + return sessionStatus; + } + /** + * @param sessionStatus The sessionStatus to set. + */ + public void setSessionStatus(String sessionStatus) { + this.sessionStatus = sessionStatus; + } + /** + * @return Returns the mcQueUsers. + */ + + public Set getMcQueUsers() { + if (this.mcQueUsers == null) + setMcQueUsers(new HashSet()); + return this.mcQueUsers; + } + /** + * @param mcQueUsers The mcQueUsers to set. + */ + public void setMcQueUsers(Set mcQueUsers) { + this.mcQueUsers = mcQueUsers; + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McStringComparator.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McStringComparator.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McStringComparator.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,51 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + + +package org.lamsfoundation.lams.tool.mc; + +import java.io.Serializable; +import java.util.Comparator; + +import org.apache.log4j.Logger; + +/** + * @author Ozgur Demirtas + * * A comparator implementation that can be used as a constructor to collections. + * The TreeMap in the web layer makes use of it. + * + */ +public class McStringComparator implements Comparator, Serializable { + static Logger logger = Logger.getLogger(McStringComparator.class.getName()); + + public int compare(Object o1, Object o2) { + String s1 = (String)o1; + String s2 = (String)o2; + + return s1.compareTo(s2); + } + + public boolean equals(Object o) { + String s = (String)o; + return compare(this, o)==0; + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McUploadedFile.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McUploadedFile.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McUploadedFile.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,185 @@ +/* + *Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * + *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; either version 2 of the License, or + *(at your option) any later version. + * + *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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + *USA + * + *http://www.gnu.org/licenses/gpl.txt + */ +package org.lamsfoundation.lams.tool.mc; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + *

Persistent object/bean that defines the uploaded file for the MCQ tool. + * Provides accessors and mutators to get/set attributes + * It maps to database table: tl_lamc11_uploadedFile + *

+ * + * @author Ozgur Demirtas + */ +public class McUploadedFile implements Serializable +{ + /** identifier field */ + private Long uid; + + /** persistent field */ + private String uuid; + + /** persistent field */ + private boolean fileOnline; + + /** persistent field */ + private String filename; + + + private Long mcContentId; + + /** persistent field */ + private McContent mcContent; + + public McUploadedFile(){}; + + /** full constructor */ + public McUploadedFile(Long uid, + String uuid, + boolean fileOnline, + String filename, + McContent mcContent) + { + this.uid=uid; + this.uuid = uuid; + this.fileOnline = fileOnline; + this.filename = filename; + this.mcContent=mcContent; + } + + public McUploadedFile(String uuid, + boolean fileOnline, + String filename, + McContent mcContent) + { + this.uuid = uuid; + this.fileOnline = fileOnline; + this.filename = filename; + this.mcContent=mcContent; + } + + public McUploadedFile(String uuid, + boolean fileOnline, + String filename, + Long mcContentId) + { + this.uuid = uuid; + this.fileOnline = fileOnline; + this.filename = filename; + this.mcContentId=mcContentId; +} + + + public String toString() { + return new ToStringBuilder(this) + .append("uuid: ", getUuid()) + .toString(); + } + + + /** + * @return Returns the mcContent. + */ + public McContent getMcContent() { + return mcContent; + } + /** + * @param mcContent The mcContent to set. + */ + public void setMcContent(McContent mcContent) { + this.mcContent = mcContent; + } + /** + * @return Returns the mcContentId. + */ + public Long getMcContentId() { + return mcContentId; + } + /** + * @param mcContentId The mcContentId to set. + */ + public void setMcContentId(Long mcContentId) { + this.mcContentId = mcContentId; + } + /** + * @return Returns the uid. + */ + public Long getSubmissionId() { + return uid; + } + /** + * @param uid The uid to set. + */ + public void setSubmissionId(Long uid) { + this.uid = uid; + } + /** + * @return Returns the uuid. + */ + public String getUuid() { + return uuid; + } + /** + * @param uuid The uuid to set. + */ + public void setUuid(String uuid) { + this.uuid = uuid; + } + /** + * @return Returns the fileOnline. + */ + public boolean isFileOnline() { + return fileOnline; + } + /** + * @param fileOnline The fileOnline to set. + */ + public void setFileOnline(boolean fileOnline) { + this.fileOnline = fileOnline; + } + /** + * @return Returns the uid. + */ + public Long getUid() { + return uid; + } + /** + * @param uid The uid to set. + */ + public void setUid(Long uid) { + this.uid = uid; + } + /** + * @return Returns the filename. + */ + public String getFilename() { + return filename; + } + /** + * @param filename The filename to set. + */ + public void setFilename(String filename) { + this.filename = filename; + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McUsrAttempt.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McUsrAttempt.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McUsrAttempt.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,277 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc; + +import java.io.Serializable; +import java.util.Date; +import org.apache.commons.lang.builder.ToStringBuilder; + + +/** + *

Persistent object/bean that defines the user attempt for the MCQ tool. + * Provides accessors and mutators to get/set attributes + * It maps to database table: tl_lamc11_usr_attempt + *

+ * + * @author Ozgur Demirtas + */ +public class McUsrAttempt implements Serializable { + + /** identifier field */ + private Long uid; + + /** persistent field */ + private Long attemptId; + + /** nullable persistent field */ + private Date attemptTime; + + /** nullable persistent field */ + private String timeZone; + + private Integer mark; + + private boolean attemptCorrect; + + private boolean passed; + + private Integer attemptOrder; + + private Long queUsrId; + + private Long mcQueContentId; + + /** persistent field */ + private org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent; + + /** persistent field */ + private org.lamsfoundation.lams.tool.mc.McQueUsr mcQueUsr; + + /** persistent field */ + private org.lamsfoundation.lams.tool.mc.McOptsContent mcOptionsContent; + + /** full constructor */ + public McUsrAttempt(Long attemptId, Date attemptTime, String timeZone, org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent, + org.lamsfoundation.lams.tool.mc.McQueUsr mcQueUsr, org.lamsfoundation.lams.tool.mc.McOptsContent mcOptionsContent) { + this.attemptId = attemptId; + this.attemptTime = attemptTime; + this.timeZone = timeZone; + this.mcQueContent = mcQueContent; + this.mcQueUsr = mcQueUsr; + this.mcOptionsContent = mcOptionsContent; + } + + public McUsrAttempt(Date attemptTime, String timeZone, org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent, + org.lamsfoundation.lams.tool.mc.McQueUsr mcQueUsr, org.lamsfoundation.lams.tool.mc.McOptsContent mcOptionsContent) { + this.attemptTime = attemptTime; + this.timeZone = timeZone; + this.mcQueContent = mcQueContent; + this.mcQueUsr = mcQueUsr; + this.mcOptionsContent = mcOptionsContent; + } + + public McUsrAttempt(Date attemptTime, String timeZone, org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent, + org.lamsfoundation.lams.tool.mc.McQueUsr mcQueUsr, org.lamsfoundation.lams.tool.mc.McOptsContent mcOptionsContent, Integer mark, boolean passed) { + this.attemptTime = attemptTime; + this.timeZone = timeZone; + this.mcQueContent = mcQueContent; + this.mcQueUsr = mcQueUsr; + this.mcOptionsContent = mcOptionsContent; + this.mark = mark; + this.passed = passed; + } + + public McUsrAttempt(Date attemptTime, String timeZone, org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent, + org.lamsfoundation.lams.tool.mc.McQueUsr mcQueUsr, org.lamsfoundation.lams.tool.mc.McOptsContent mcOptionsContent, Integer mark, boolean passed, Integer attemptOrder) { + this.attemptTime = attemptTime; + this.timeZone = timeZone; + this.mcQueContent = mcQueContent; + this.mcQueUsr = mcQueUsr; + this.mcOptionsContent = mcOptionsContent; + this.mark = mark; + this.passed = passed; + this.attemptOrder=attemptOrder; + } + + public McUsrAttempt(Date attemptTime, String timeZone, org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent, + org.lamsfoundation.lams.tool.mc.McQueUsr mcQueUsr, org.lamsfoundation.lams.tool.mc.McOptsContent mcOptionsContent, Integer mark, boolean passed, Integer attemptOrder, boolean attemptCorrect) { + this.attemptTime = attemptTime; + this.timeZone = timeZone; + this.mcQueContent = mcQueContent; + this.mcQueUsr = mcQueUsr; + this.mcOptionsContent = mcOptionsContent; + this.mark = mark; + this.passed = passed; + this.attemptOrder=attemptOrder; + this.attemptCorrect=attemptCorrect; + } + + + /** default constructor */ + public McUsrAttempt() { + } + + /** minimal constructor */ + public McUsrAttempt(Long attemptId, org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent, org.lamsfoundation.lams.tool.mc.McQueUsr mcQueUsr, org.lamsfoundation.lams.tool.mc.McOptsContent mcOptionsContent) { + this.attemptId = attemptId; + this.mcQueContent = mcQueContent; + this.mcQueUsr = mcQueUsr; + this.mcOptionsContent = mcOptionsContent; + } + + public Long getUid() { + return this.uid; + } + + public void setUid(Long uid) { + this.uid = uid; + } + + public Long getAttemptId() { + return this.attemptId; + } + + public void setAttemptId(Long attemptId) { + this.attemptId = attemptId; + } + + public Date getAttemptTime() { + return this.attemptTime; + } + + public void setAttemptTime(Date attemptTime) { + this.attemptTime = attemptTime; + } + + public String getTimeZone() { + return this.timeZone; + } + + public void setTimeZone(String timeZone) { + this.timeZone = timeZone; + } + + public org.lamsfoundation.lams.tool.mc.McQueContent getMcQueContent() { + return this.mcQueContent; + } + + public void setMcQueContent(org.lamsfoundation.lams.tool.mc.McQueContent mcQueContent) { + this.mcQueContent = mcQueContent; + } + + public org.lamsfoundation.lams.tool.mc.McQueUsr getMcQueUsr() { + return this.mcQueUsr; + } + + public void setMcQueUsr(org.lamsfoundation.lams.tool.mc.McQueUsr mcQueUsr) { + this.mcQueUsr = mcQueUsr; + } + + public org.lamsfoundation.lams.tool.mc.McOptsContent getMcOptionsContent() { + return this.mcOptionsContent; + } + + public void setMcOptionsContent(org.lamsfoundation.lams.tool.mc.McOptsContent mcOptionsContent) { + this.mcOptionsContent = mcOptionsContent; + } + + public String toString() { + return new ToStringBuilder(this) + .append("uid", getUid()) + .toString(); + } + + /** + * @return Returns the mark. + */ + public Integer getMark() { + return mark; + } + /** + * @param mark The mark to set. + */ + public void setMark(Integer mark) { + this.mark = mark; + } + /** + * @return Returns the passed. + */ + public boolean isPassed() { + return passed; + } + /** + * @param passed The passed to set. + */ + public void setPassed(boolean passed) { + this.passed = passed; + } + /** + * @return Returns the queUsrId. + */ + public Long getQueUsrId() { + return queUsrId; + } + /** + * @param queUsrId The queUsrId to set. + */ + public void setQueUsrId(Long queUsrId) { + this.queUsrId = queUsrId; + } + /** + * @return Returns the attemptOrder. + */ + public Integer getAttemptOrder() { + return attemptOrder; + } + /** + * @param attemptOrder The attemptOrder to set. + */ + public void setAttemptOrder(Integer attemptOrder) { + this.attemptOrder = attemptOrder; + } + /** + * @return Returns the mcQueContentId. + */ + public Long getMcQueContentId() { + return mcQueContentId; + } + /** + * @param mcQueContentId The mcQueContentId to set. + */ + public void setMcQueContentId(Long mcQueContentId) { + this.mcQueContentId = mcQueContentId; + } + + /** + * @return Returns the attemptCorrect. + */ + public boolean isAttemptCorrect() { + return attemptCorrect; + } + /** + * @param attemptCorrect The attemptCorrect to set. + */ + public void setAttemptCorrect(boolean attemptCorrect) { + this.attemptCorrect = attemptCorrect; + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McUtils.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McUtils.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/McUtils.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,814 @@ +/* + * Created on 21/04/2005 + * + */ +package org.lamsfoundation.lams.tool.mc; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.text.DateFormat; +import java.util.Date; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Random; +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.apache.struts.upload.FormFile; +import org.lamsfoundation.lams.contentrepository.NodeKey; +import org.lamsfoundation.lams.tool.mc.service.IMcService; +import org.lamsfoundation.lams.tool.mc.web.McAuthoringForm; +import org.lamsfoundation.lams.usermanagement.User; +import org.lamsfoundation.lams.usermanagement.dto.UserDTO; +import org.lamsfoundation.lams.web.session.SessionManager; +import org.lamsfoundation.lams.web.util.AttributeNames; + + +/** + * @author Ozgur Demirtas + * Common MCQ utility functions live here. + */ +public abstract class McUtils implements McAppConstants { + + static Logger logger = Logger.getLogger(McUtils.class.getName()); + + /** + * returns the service object from the session cache + * IMcService getToolService(HttpServletRequest request) + * + * @param request + * @return + */ + public static IMcService getToolService(HttpServletRequest request) + { + IMcService mcService=(IMcService)request.getSession().getAttribute(TOOL_SERVICE); + return mcService; + } + + /** + * + * getGMTDateTime(HttpServletRequest request) + * + * @param request + * @return + */ + /* fix this */ + public static Date getGMTDateTime() + { + Date date=new Date(System.currentTimeMillis()); + logger.debug("date: " + date); + return date; + } + + + public static UserDTO getToolUser() + { + /*obtain user object from the session*/ + HttpSession ss = SessionManager.getSession(); + /* get back login user DTO */ + UserDTO toolUser = (UserDTO) ss.getAttribute(AttributeNames.USER); + logger.debug("retrieving toolUser: " + toolUser); + return toolUser; + } + + + public static Long getUserId() + { + UserDTO toolUser=getToolUser(); + long userId=toolUser.getUserID().longValue(); + logger.debug("userId: " + userId); + return new Long(userId); + } + + public static String getUserName() + { + /* double check if username and login is the same */ + UserDTO toolUser=getToolUser(); + String userName=toolUser.getLogin(); + logger.debug("userName: " + userName); + return userName; + } + + public static String getUserFullName() + { + UserDTO toolUser=getToolUser(); + String fullName=toolUser.getFirstName() + " " + toolUser.getLastName(); + logger.debug("fullName: " + fullName); + return fullName; + } + + public static String getFormattedDateString(Date date) + { + logger.debug(logger + " " + " McUtils getFormattedDateString: " + + DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(date)); + return (DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(date)); + } + + public static void persistTimeZone(HttpServletRequest request) + { + TimeZone timeZone=TimeZone.getDefault(); + logger.debug("current timezone: " + timeZone.getDisplayName()); + request.getSession().setAttribute(TIMEZONE, timeZone.getDisplayName()); + logger.debug("current timezone id: " + timeZone.getID()); + request.getSession().setAttribute(TIMEZONE_ID, timeZone.getID()); + } + + public static String getCurrentTimeZone() + { + TimeZone timeZone=TimeZone.getDefault(); + logger.debug("current timezone: " + timeZone.getDisplayName()); + return timeZone.getDisplayName(); + } + + + /** + * existsContent(long toolContentId) + * @param long toolContentId + * @return boolean + * determine whether a specific toolContentId exists in the db + */ + public static boolean existsContent(Long toolContentId, HttpServletRequest request) + { + IMcService mcService =McUtils.getToolService(request); + + McContent mcContent=mcService.retrieveMc(toolContentId); + logger.debug(logger + " " + "McUtils " + "retrieving mcContent: " + mcContent); + if (mcContent == null) + return false; + + return true; + } + + /** + * it is expected that the tool session id already exists in the tool sessions table + * existsSession(long toolSessionId) + * @param toolSessionId + * @return boolean + */ + public static boolean existsSession(Long toolSessionId, HttpServletRequest request) + { + logger.debug("existsSession"); + IMcService mcService =McUtils.getToolService(request); + McSession mcSession=mcService.retrieveMcSession(toolSessionId); + logger.debug("mcSession:" + mcSession); + + if (mcSession == null) + return false; + + return true; + } + + public static void setDefaultSessionAttributes(HttpServletRequest request, McContent defaultMcContent, McAuthoringForm mcAuthoringForm) + { + /*should never be null anyway as default content MUST exist in the db*/ + if (defaultMcContent != null) + { + mcAuthoringForm.setTitle(defaultMcContent.getTitle()); + mcAuthoringForm.setInstructions(defaultMcContent.getInstructions()); + mcAuthoringForm.setOfflineInstructions (defaultMcContent.getOfflineInstructions()); + mcAuthoringForm.setOnlineInstructions (defaultMcContent.getOnlineInstructions()); + + if (defaultMcContent.getPassMark() != null) + mcAuthoringForm.setPassmark((defaultMcContent.getPassMark()).toString()); + else + mcAuthoringForm.setPassmark(new Integer(0).toString()); + + } + } + + + /** + * returns a Map of options + * generateOptionsMap(List listMcOptions) + * + * @param listMcOptions + * @return Map + */ + public static Map generateOptionsMap(List listMcOptions) + { + logger.debug("incoming listMcOptions" + listMcOptions); + Map mapOptionsContent= new TreeMap(new McComparator()); + + Iterator listIterator=listMcOptions.iterator(); + Long mapIndex=new Long(1); + while (listIterator.hasNext()) + { + McOptsContent mcOptionsContent = (McOptsContent)listIterator.next(); + logger.debug("mcOptionsContent:" + mcOptionsContent); + mapOptionsContent.put(mapIndex.toString(),mcOptionsContent.getMcQueOptionText()); + mapIndex=new Long(mapIndex.longValue()+1); + } + logger.debug("generated mcOptionsContent: " + mapOptionsContent); + return mapOptionsContent; + } + + + public static void persistRichText(HttpServletRequest request) + { + String richTextOfflineInstructions=request.getParameter(RICHTEXT_OFFLINEINSTRUCTIONS); + logger.debug("read parameter richTextOfflineInstructions: " + richTextOfflineInstructions); + String richTextOnlineInstructions=request.getParameter(RICHTEXT_ONLINEINSTRUCTIONS); + logger.debug("read parameter richTextOnlineInstructions: " + richTextOnlineInstructions); + + if ((richTextOfflineInstructions != null) && (richTextOfflineInstructions.length() > 0)) + { + request.getSession().setAttribute(RICHTEXT_OFFLINEINSTRUCTIONS,richTextOfflineInstructions); + } + + if ((richTextOnlineInstructions != null) && (richTextOnlineInstructions.length() > 0)) + { + request.getSession().setAttribute(RICHTEXT_ONLINEINSTRUCTIONS,richTextOnlineInstructions); + } + + + String richTextTitle=request.getParameter(RICHTEXT_TITLE); + logger.debug("read parameter richTextTitle: " + richTextTitle); + String richTextInstructions=request.getParameter(RICHTEXT_INSTRUCTIONS); + logger.debug("read parameter richTextInstructions: " + richTextInstructions); + + + if ((richTextTitle != null) && (richTextTitle.length() > 0)) + { + request.getSession().setAttribute(RICHTEXT_TITLE,richTextTitle); + } + + if ((richTextInstructions != null) && (richTextInstructions.length() > 0)) + { + request.getSession().setAttribute(RICHTEXT_INSTRUCTIONS,richTextInstructions); + } + + String richTextFeedbackCorrect=request.getParameter(RICHTEXT_FEEDBACK_CORRECT); + logger.debug("read parameter richTextFeedbackCorrect: " + richTextFeedbackCorrect); + + String richTextFeedbackInCorrect=request.getParameter(RICHTEXT_FEEDBACK_INCORRECT); + logger.debug("read parameter richTextFeedbackInCorrect: " + richTextFeedbackInCorrect); + + if ((richTextFeedbackCorrect != null) && (richTextFeedbackCorrect.length() > 0)) + { + request.getSession().setAttribute(RICHTEXT_FEEDBACK_CORRECT,richTextFeedbackCorrect); + } + + if ((richTextFeedbackInCorrect != null) && (richTextFeedbackInCorrect.length() > 0)) + { + request.getSession().setAttribute(RICHTEXT_FEEDBACK_INCORRECT,richTextFeedbackInCorrect); + } + + + String richTextReportTitle=request.getParameter(RICHTEXT_REPORT_TITLE); + logger.debug("read parameter richTextReportTitle: " + richTextReportTitle); + + String richTextEndLearningMessage=request.getParameter(RICHTEXT_END_LEARNING_MSG); + logger.debug("read parameter richTextEndLearningMessage: " + richTextEndLearningMessage); + + if ((richTextReportTitle != null) && (richTextReportTitle.length() > 0)) + { + request.getSession().setAttribute(RICHTEXT_REPORT_TITLE,richTextReportTitle); + } + + if ((richTextEndLearningMessage != null) && (richTextEndLearningMessage.length() > 0)) + { + request.getSession().setAttribute(RICHTEXT_END_LEARNING_MSG,richTextEndLearningMessage); + } + } + + public static void addFileToContentRepository(HttpServletRequest request, McAuthoringForm mcAuthoringForm, boolean isOfflineFile) + { + logger.debug("attempt addFileToContentRepository, isOfflineFile: " + isOfflineFile); + IMcService mcService =McUtils.getToolService(request); + logger.debug("mcService: " + mcService); + + Boolean populateUploadedFilesData=(Boolean)request.getSession().getAttribute(POPULATED_UPLOADED_FILESDATA); + logger.debug("boolean populateUploadedFilesData: " + populateUploadedFilesData); + + if ((populateUploadedFilesData !=null) && (populateUploadedFilesData.booleanValue())) + { + Long toolContentId=(Long)request.getSession().getAttribute(TOOL_CONTENT_ID); + logger.debug("toolContentId: " + toolContentId); + McContent defaultMcContent=mcService.retrieveMc(toolContentId); + logger.debug("defaultMcContent: " + defaultMcContent); + + populateUploadedFilesMetaDataFromDb(request, defaultMcContent); + logger.debug("done populateUploadedFilesMetaDataFromDb"); + } + + + List listUploadedOfflineFilesUuid = (List) request.getSession().getAttribute(LIST_UPLOADED_OFFLINE_FILES_UUID); + logger.debug("listUploadedOfflineFilesUuid: " + listUploadedOfflineFilesUuid); + + List listUploadedOfflineFilesName = (List) request.getSession().getAttribute(LIST_UPLOADED_OFFLINE_FILES_NAME); + logger.debug("listUploadedOfflineFilesName: " + listUploadedOfflineFilesName); + + List listUploadedOnlineFilesUuid = (List) request.getSession().getAttribute(LIST_UPLOADED_ONLINE_FILES_UUID); + logger.debug("listUploadedOnlineFilesUuid: " + listUploadedOnlineFilesUuid); + + List listUploadedOnlineFilesName = (List) request.getSession().getAttribute(LIST_UPLOADED_ONLINE_FILES_NAME); + logger.debug("listUploadedOnlineFilesName: " + listUploadedOnlineFilesName); + + List listUploadedOfflineFiles= (List) request.getSession().getAttribute(LIST_UPLOADED_OFFLINE_FILES); + logger.debug("listUploadedOfflineFiles: " + listUploadedOfflineFiles); + + List listUploadedOfflineFileNames=(List)request.getSession().getAttribute(LIST_UPLOADED_OFFLINE_FILENAMES); + logger.debug("listUploadedOfflineFiles: " + listUploadedOfflineFiles); + + List listUploadedOnlineFileNames=(List)request.getSession().getAttribute(LIST_UPLOADED_ONLINE_FILENAMES); + logger.debug("listUploadedOnlineFileNames: " + listUploadedOnlineFileNames); + + + if (listUploadedOfflineFileNames == null) + listUploadedOfflineFileNames = new LinkedList(); + logger.debug("listUploadedOfflineFileNames: " + listUploadedOfflineFileNames); + + if (listUploadedOnlineFileNames == null) + listUploadedOnlineFileNames = new LinkedList(); + logger.debug("listUploadedOnlineFileNames: " + listUploadedOnlineFileNames); + + Map allOfflineUuids= new TreeMap(new McComparator()); + if ((listUploadedOfflineFilesUuid != null) && (listUploadedOfflineFilesName != null)) + { + logger.debug("listUploadedOfflineFilesUuid and listUploadedOfflineFilesName are not null"); + Iterator listUploadedOfflineFilesUuidIterator=listUploadedOfflineFilesUuid.iterator(); + int counter=1; + logger.debug("allOfflineUuids: " + allOfflineUuids); + while (listUploadedOfflineFilesUuidIterator.hasNext()) + { + String uuid = (String)listUploadedOfflineFilesUuidIterator.next(); + allOfflineUuids.put(new Integer(counter).toString(), uuid); + counter++; + } + logger.debug("allOfflineUuids: " + allOfflineUuids); + Iterator listUploadedOfflineFilesNameIterator=listUploadedOfflineFilesName.iterator(); + + counter=1; + while (listUploadedOfflineFilesNameIterator.hasNext()) + { + String fileName = (String)listUploadedOfflineFilesNameIterator.next(); + + if (!offLineFileNameExists(request,fileName)) + { + logger.debug("reading with counter: " + new Integer(counter).toString()); + String uuid=(String)allOfflineUuids.get(new Integer(counter).toString()); + logger.debug("parsed uuid: " + uuid); + listUploadedOfflineFiles.add(uuid + '~'+ fileName); + counter++; + } + else + { + logger.debug("offline fileName exists: " +fileName); + } + + } + logger.debug("final listUploadedOfflineFiles: " + listUploadedOfflineFiles); + request.getSession().setAttribute(LIST_UPLOADED_OFFLINE_FILES,listUploadedOfflineFiles); + } + /* + List listUploadedOfflineFileNames = (List) request.getSession().getAttribute(LIST_UPLOADED_OFFLINE_FILENAMES); + logger.debug("listUploadedOfflineFileNames: " + listUploadedOfflineFileNames); + + + List listUploadedOnlineFileNames = (List) request.getSession().getAttribute(LIST_UPLOADED_ONLINE_FILENAMES); + logger.debug("listUploadedOnlineFileNames: " + listUploadedOnlineFileNames); + */ + + + /**holds final online files list */ + List listUploadedOnlineFiles= (List) request.getSession().getAttribute(LIST_UPLOADED_ONLINE_FILES); + logger.debug("listUploadedOnlineFiles: " + listUploadedOnlineFiles); + + Map allOnlineUuids= new TreeMap(new McComparator()); + if ((listUploadedOnlineFilesUuid != null) && (listUploadedOnlineFilesName != null)) + { + logger.debug("listUploadedOnlineFilesUuid and listUploadedOnlineFilesName are not null"); + Iterator listUploadedOnlineFilesUuidIterator=listUploadedOnlineFilesUuid.iterator(); + int counter=1; + logger.debug("allOnlineUuids: " + allOnlineUuids); + while (listUploadedOnlineFilesUuidIterator.hasNext()) + { + String uuid = (String)listUploadedOnlineFilesUuidIterator.next(); + allOnlineUuids.put(new Integer(counter).toString(), uuid); + counter++; + + } + logger.debug("allOnlineUuids: " + allOnlineUuids); + Iterator listUploadedOnlineFilesNameIterator=listUploadedOnlineFilesName.iterator(); + + counter=1; + while (listUploadedOnlineFilesNameIterator.hasNext()) + { + String fileName = (String)listUploadedOnlineFilesNameIterator.next(); + + if (!onLineFileNameExists(request,fileName)) + { + logger.debug("reading with counter: " + new Integer(counter).toString()); + String uuid=(String)allOnlineUuids.get(new Integer(counter).toString()); + logger.debug("parsed uuid: " + uuid); + listUploadedOnlineFiles.add(uuid + '~'+ fileName); + counter++; + } + else + { + logger.debug("online fileName exists: " +fileName); + } + + } + logger.debug("final listUploadedOnlineFiles: " + listUploadedOnlineFiles); + request.getSession().setAttribute(LIST_UPLOADED_ONLINE_FILES,listUploadedOnlineFiles); + } + + + if (isOfflineFile) + { + /* read uploaded file informtion - offline file*/ + logger.debug("retrieve theOfflineFile."); + FormFile theOfflineFile = mcAuthoringForm.getTheOfflineFile(); + logger.debug("retrieved theOfflineFile: " + theOfflineFile); + + String offlineFileName=""; + NodeKey nodeKey=null; + String offlineFileUuid=""; + try + { + InputStream offlineFileInputStream = theOfflineFile.getInputStream(); + logger.debug("retrieved offlineFileInputStream: " + offlineFileInputStream); + offlineFileName=theOfflineFile.getFileName(); + logger.debug("retrieved offlineFileName: " + offlineFileName); + nodeKey=mcService.uploadFileToRepository(offlineFileInputStream, offlineFileName); + logger.debug("repository returned nodeKey: " + nodeKey); + logger.debug("repository returned offlineFileUuid nodeKey uuid: " + nodeKey.getUuid()); + offlineFileUuid=nodeKey.getUuid().toString(); + logger.debug("offline file added to contentRepository"); + logger.debug("using listUploadedOfflineFiles: " + listUploadedOfflineFiles); + listUploadedOfflineFiles.add(offlineFileUuid + "~" + offlineFileName); + logger.debug("listUploadedOfflineFiles updated: " + listUploadedOfflineFiles); + request.getSession().setAttribute(LIST_UPLOADED_OFFLINE_FILES,listUploadedOfflineFiles); + + listUploadedOfflineFileNames.add(offlineFileName); + request.getSession().setAttribute(LIST_UPLOADED_OFFLINE_FILENAMES,listUploadedOfflineFileNames); + } + catch(FileNotFoundException e) + { + logger.debug("exception occured, offline file not found : " + e.getMessage()); + //possibly give warning to user in request scope + } + catch(IOException e) + { + logger.debug("exception occured in offline file transfer: " + e.getMessage()); + //possibly give warning to user in request scope + } + catch(McApplicationException e) + { + logger.debug("exception occured in accessing the repository server: " + e.getMessage()); + //possibly give warning to user in request scope + } + } + else + { + /* read uploaded file information - online file*/ + logger.debug("retrieve theOnlineFile"); + FormFile theOnlineFile = mcAuthoringForm.getTheOnlineFile(); + logger.debug("retrieved theOnlineFile: " + theOnlineFile); + + String onlineFileName=""; + NodeKey nodeKey=null; + String onlineFileUuid=""; + try + { + InputStream onlineFileInputStream = theOnlineFile.getInputStream(); + logger.debug("retrieved onlineFileInputStream: " + onlineFileInputStream); + onlineFileName=theOnlineFile.getFileName(); + logger.debug("retrieved onlineFileName: " + onlineFileName); + nodeKey=mcService.uploadFileToRepository(onlineFileInputStream, onlineFileName); + logger.debug("repository returned nodeKey: " + nodeKey); + logger.debug("repository returned onlineFileUuid nodeKey uuid: " + nodeKey.getUuid()); + onlineFileUuid=nodeKey.getUuid().toString(); + logger.debug("online file added to contentRepository"); + listUploadedOnlineFiles.add(onlineFileUuid + "~" + onlineFileName); + logger.debug("listUploadedOnlineFiles updated: " + listUploadedOnlineFiles); + request.getSession().setAttribute(LIST_UPLOADED_ONLINE_FILES,listUploadedOnlineFiles); + + listUploadedOnlineFileNames.add(onlineFileName); + request.getSession().setAttribute(LIST_UPLOADED_ONLINE_FILENAMES,listUploadedOnlineFileNames); + } + catch(FileNotFoundException e) + { + logger.debug("exception occured, online file not found : " + e.getMessage()); + //possibly give warning to user in request scope + } + catch(IOException e) + { + logger.debug("exception occured in online file transfer: " + e.getMessage()); + //possibly give warning to user in request scope + } + catch(McApplicationException e) + { + logger.debug("exception occured in accessing the repository server: " + e.getMessage()); + //possibly give warning to user in request scope + } + } + + + if ((populateUploadedFilesData != null) && (populateUploadedFilesData.booleanValue())) + { + logger.debug("removing ofline + online file list attributes"); + request.getSession().removeAttribute(LIST_UPLOADED_OFFLINE_FILES_UUID); + request.getSession().removeAttribute(LIST_UPLOADED_OFFLINE_FILES_NAME); + request.getSession().removeAttribute(LIST_UPLOADED_ONLINE_FILES_UUID); + request.getSession().removeAttribute(LIST_UPLOADED_ONLINE_FILES_NAME); + } + } + + + public static void configureContentRepository(HttpServletRequest request, IMcService mcService) + { + logger.debug("attempt configureContentRepository"); + + logger.debug("calling configureContentRepository()"); + mcService.configureContentRepository(); + logger.debug("configureContentRepository ran successfully"); + } + + public static void populateUploadedFilesData(HttpServletRequest request, McContent defaultMcContent) + { + populateUploadedFilesMetaDataFromDb(request, defaultMcContent); + request.getSession().setAttribute(POPULATED_UPLOADED_FILESDATA, new Boolean(true)); + } + + public static void populateUploadedFilesMetaDataFromDb(HttpServletRequest request, McContent defaultMcContent) + { + logger.debug("attempt populateUploadedFilesData for: " + defaultMcContent); + IMcService mcService =McUtils.getToolService(request); + logger.debug("mcService: " + mcService); + + /** just for jsp purposes ** + /** read the uploaded offline uuid + file name pair */ + //List listOfflineFilesUuid=new LinkedList(); + //listOfflineFilesUuid=mcService.retrieveMcUploadedOfflineFilesUuid(defaultMcContent); + logger.debug("using defaultMcContent.getUid() " + defaultMcContent.getUid()); + List listOffFilesUuid=mcService.retrieveMcUploadedOfflineFilesUuid(defaultMcContent.getUid()); + + + + logger.debug("initial listOfflineFilesUuid: " + listOffFilesUuid); + request.getSession().removeAttribute(LIST_UPLOADED_OFFLINE_FILES_UUID); + request.getSession().setAttribute(LIST_UPLOADED_OFFLINE_FILES_UUID, listOffFilesUuid); + + /** read the uploaded online uuid + file name pair */ + //List listOnlineFilesUuid=new LinkedList(); + List listOnFilesUuid=mcService.retrieveMcUploadedOnlineFilesUuid(defaultMcContent.getUid()); + logger.debug("initial listOnlineFilesUuid: " + listOnFilesUuid); + request.getSession().removeAttribute(LIST_UPLOADED_ONLINE_FILES_UUID); + request.getSession().setAttribute(LIST_UPLOADED_ONLINE_FILES_UUID, listOnFilesUuid); + + + /** read the uploaded offline uuid + file name pair */ + //List listOfflineFilesName=new LinkedList(); + List listOffFilesName=mcService.retrieveMcUploadedOfflineFilesName(defaultMcContent.getUid()); + logger.debug("initial listOfflineFilesName: " + listOffFilesName); + request.getSession().removeAttribute(LIST_UPLOADED_OFFLINE_FILES_NAME); + request.getSession().setAttribute(LIST_UPLOADED_OFFLINE_FILES_NAME, listOffFilesName); + + + /** read the uploaded online uuid + file name pair */ + //List listOnlineFilesName=new LinkedList(); + List listOnFilesName=mcService.retrieveMcUploadedOnlineFilesName(defaultMcContent.getUid()); + logger.debug("initial listOnlineFilesName: " + listOnFilesName); + request.getSession().removeAttribute(LIST_UPLOADED_ONLINE_FILES_NAME); + request.getSession().setAttribute(LIST_UPLOADED_ONLINE_FILES_NAME, listOnFilesName); + + + request.getSession().removeAttribute(LIST_UPLOADED_OFFLINE_FILENAMES); + request.getSession().removeAttribute(LIST_UPLOADED_ONLINE_FILENAMES); + request.getSession().setAttribute(LIST_UPLOADED_OFFLINE_FILENAMES, listOffFilesName); + request.getSession().setAttribute(LIST_UPLOADED_ONLINE_FILENAMES, listOnFilesName); + } + + public static boolean offLineFileNameExists(HttpServletRequest request,String fileName) + { + logger.debug("checking offLineFileNameExists"); + IMcService mcService =McUtils.getToolService(request); + logger.debug("mcService: " + mcService); + + Long toolContentId=(Long)request.getSession().getAttribute(TOOL_CONTENT_ID); + logger.debug("toolContentId: " + toolContentId); + McContent defaultMcContent=mcService.retrieveMc(toolContentId); + logger.debug("defaultMcContent: " + defaultMcContent); + + /** read the uploaded offline uuid + file name pair */ + //List listOfflineFilesName=new LinkedList(); + List listOffFilesName=mcService.retrieveMcUploadedOfflineFilesName(defaultMcContent.getUid()); + logger.debug("listOfflineFilesName: " + listOffFilesName); + + Iterator listOfflineFilesNameIterator=listOffFilesName.iterator(); + while (listOfflineFilesNameIterator.hasNext()) + { + String currentFileName = (String)listOfflineFilesNameIterator.next(); + logger.debug("currentFileName: " + currentFileName); + if (currentFileName.equalsIgnoreCase(fileName)) + { + logger.debug("existing fileName: " + currentFileName); + return true; + } + } + return false; + } + + public static boolean onLineFileNameExists(HttpServletRequest request,String fileName) + { + logger.debug("checking onLineFileNameExists"); + IMcService mcService =McUtils.getToolService(request); + logger.debug("mcService: " + mcService); + + Long toolContentId=(Long)request.getSession().getAttribute(TOOL_CONTENT_ID); + logger.debug("toolContentId: " + toolContentId); + McContent defaultMcContent=mcService.retrieveMc(toolContentId); + logger.debug("defaultMcContent: " + defaultMcContent); + + /** read the uploaded offline uuid + file name pair */ + //List listOnlineFilesName=new LinkedList(); + List listOnFilesName=mcService.retrieveMcUploadedOnlineFilesName(defaultMcContent.getUid()); + logger.debug("listOnlineFilesName: " + listOnFilesName); + + Iterator listOnlineFilesNameIterator=listOnFilesName.iterator(); + while (listOnlineFilesNameIterator.hasNext()) + { + String currentFileName = (String)listOnlineFilesNameIterator.next(); + logger.debug("currentFileName: " + currentFileName); + if (currentFileName.equalsIgnoreCase(fileName)) + { + logger.debug("existing fileName: " + currentFileName); + return true; + } + + } + return false; + } + + + public static void addUploadedFilesMetaData(HttpServletRequest request, McContent mc) + { + logger.debug("doing addUploadedFilesMetaData..."); + IMcService mcService =McUtils.getToolService(request); + logger.debug("mcService: " + mcService); + + logger.debug("attempt cleaning files meta data from the db"); + mcService.cleanUploadedFilesMetaData(); + logger.debug("cleaned up files meta data from the db"); + + List listUploadedOfflineFiles = (List) request.getSession().getAttribute(LIST_UPLOADED_OFFLINE_FILES); + logger.debug("final listUploadedOfflineFiles: " + listUploadedOfflineFiles); + List listUploadedOnlineFiles = (List) request.getSession().getAttribute(LIST_UPLOADED_ONLINE_FILES); + logger.debug("final listUploadedOnlineFiles: " + listUploadedOnlineFiles); + + try{ + logger.debug("start persisting offline file information to db..."); + Iterator offlineFilesIterator=listUploadedOfflineFiles.iterator(); + while (offlineFilesIterator.hasNext()) + { + String uuidAndFileName=(String) offlineFilesIterator.next(); + logger.debug("iterated uuidAndFileName: " + uuidAndFileName); + if ((uuidAndFileName != null) && (uuidAndFileName.indexOf('~') > 0)) + { + int separator=uuidAndFileName.indexOf('~'); + logger.debug("separator: " + separator); + String uuid=uuidAndFileName.substring(0,separator); + String fileName=uuidAndFileName.substring(separator+1); + logger.debug("using uuid: " + uuid); + logger.debug("using fileName: " + fileName); + mcService.persistFile(uuid,false, fileName,mc); + } + } + logger.debug("all offline files data has been persisted"); + } + catch(Exception e) + { + logger.debug("error persisting offline files data, full error: " + e); + logger.debug("error persisting offline files data, error msg: " + e.getMessage()); + logger.debug("error persisting offline files data: " + listUploadedOfflineFiles); + } + + try{ + logger.debug("start persisting online file information to db..."); + Iterator onlineFilesIterator=listUploadedOnlineFiles.iterator(); + while (onlineFilesIterator.hasNext()) + { + String uuidAndFileName=(String) onlineFilesIterator.next(); + logger.debug("iterated uuidAndFileName: " + uuidAndFileName); + if ((uuidAndFileName != null) && (uuidAndFileName.indexOf('~') > 0)) + { + int separator=uuidAndFileName.indexOf('~'); + logger.debug("separator: " + separator); + String uuid=uuidAndFileName.substring(0,separator); + String fileName=uuidAndFileName.substring(separator+1); + logger.debug("using uuid: " + uuid); + logger.debug("using fileName: " + fileName); + mcService.persistFile(uuid,true, fileName,mc); + } + } + logger.debug("all online files data has been persisted"); + } + catch(Exception e) + { + logger.debug("error persisting offline files data: " + listUploadedOnlineFiles); + } + + } + + + /** + * temporary function + * @return + */ + public static long generateId() + { + Random generator = new Random(); + long longId=generator.nextLong(); + if (longId < 0) longId=longId * (-1) ; + return longId; + } + + /** + * temporary function + * @return + */ + public static int generateIntegerId() + { + Random generator = new Random(); + int intId=generator.nextInt(); + if (intId < 0) intId=intId * (-1) ; + return intId; + } + + + /** + * temporary function + * @return + */ + public static int getCurrentUserId(HttpServletRequest request) throws McApplicationException + { + HttpSession ss = SessionManager.getSession(); + UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); + logger.debug(logger + " " + "McUtils" + " Current user is: " + user + " with id: " + user.getUserID()); + return user.getUserID().intValue(); + } + + + /** + * temporary function + * @return + */ + public static User createMockUser() + { + logger.debug(logger + " " + "McUtils" + " request for new new mock user"); + int randomUserId=generateIntegerId(); + User mockUser=new User(); + mockUser.setUserId(new Integer(randomUserId)); + mockUser.setFirstName(MOCK_USER_NAME + randomUserId); + mockUser.setLastName(MOCK_USER_LASTNAME + randomUserId); + mockUser.setLogin(MOCK_LOGIN_NAME + randomUserId); //we assume login and username refers to the same property + logger.debug(logger + " " + "McUtils" + " created mockuser: " + mockUser); + return mockUser; + } + + /** + * temporary function + * @return + */ + public static User createSimpleUser(Integer userId) + { + User user=new User(); + user.setUserId(userId); + return user; + } + + /** + * temporary function + * @return + */ + public static User createUser(Integer userId) + { + User user=new User(); + user.setUserId(userId); + + int randomUserId=generateIntegerId(); + user.setFirstName(MOCK_USER_NAME + randomUserId); + user.setLastName(MOCK_USER_LASTNAME + randomUserId); + user.setLogin(MOCK_LOGIN_NAME + randomUserId); + return user; + } + + /** + * temporary function + * @return + */ + public static boolean getDefineLaterStatus() + { + return false; + } + +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/Nullable.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/Nullable.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/Nullable.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,41 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc; + + +/** + * Null Object pattern. This interface is defined to avoid the use of NULL. + * The domain object that allows NULL as return value should implement this + * interface. + * + * @author Ozgur Demirtas + * + */ +public interface Nullable +{ + /** + * contract to indicate whether current object is null. + * @return + */ + public boolean isNull(); +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcContentDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcContentDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcContentDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,116 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.dao; + +import java.util.List; + +import org.lamsfoundation.lams.tool.mc.McContent; +import org.lamsfoundation.lams.tool.mc.McSession; + +/** + * @author Ozgur Demirtas + *

Interface for the McContent DAO, defines methods needed to access/modify mc content

+ * + */ +public interface IMcContentDAO { + /** + *

Return the persistent instance of a McContent + * with the given identifier uid, returns null if not found.

+ * + * @param uid an identifier for the McContent instance. + * @return the persistent instance of a McContent or null if not found + */ + public McContent getMcContentByUID(Long uid); + + /** + *

Return the persistent instance of a McContent + * with the given tool content id mcContentId, + * returns null if not found.

+ * + * @param mcContentId The tool content id + * @return the persistent instance of a McContent or null if not found. + */ + public McContent findMcContentById(Long mcContentId); + + /** + *

Returns the persistent instance of McContent + * with the given tool session id mcSessionId, returns null if not found. + * + * @param mcSessionId The tool session id + * @return a persistent instance of McContent or null if not found. + */ + public McContent getMcContentBySession(Long mcSessionId); + + /** + *

Persist the given persistent instance of McContent.

+ * + * @param mcContent The instance of McContent to persist. + */ + public void saveMcContent(McContent mcContent); + + /** + *

Update the given persistent instance of McContent.

+ * + * @param mcContent The instance of McContent to persist. + */ + public void updateMcContent(McContent mcContent); + + /** + *

Delete the given instance of McContent

+ * + * @param mcContent The instance of McContent to delete. + */ + public void removeMc(McContent mcContent); + + + /** + *

Delete the given instance of McContent with the + * given tool content id mcContentId + * + * @param mcContentId The tool content Id. + */ + public void removeMcById(Long mcContentId); + + + /** + *

Deletes all instances of McSession that are associated + * with the given instance of McContent

+ * + * @param mcContent The instance of McContent in which corresponding instances of McSession should be deleted. + */ + public void removeMcSessions(McContent mcContent); + + /** + *

Creates a persistent instance of McSession which is associated + * with the McContent with tool content id mcContentId + *

+ * + * @param mcContentId The tool content id + * @param mcSession The instance of McSession to add + */ + public void addMcSession(Long mcContentId, McSession mcSession); + + public List findAll(Class objClass); + + public void flush(); + } \ No newline at end of file Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcOptionsContentDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcOptionsContentDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcOptionsContentDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,108 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.dao; + +import java.util.List; + +import org.lamsfoundation.lams.tool.mc.McOptsContent; + +/** + * @author Ozgur Demirtas + *

Interface for the McOptionsContent DAO, defines methods needed to access/modify mc options content

+ * + */ +public interface IMcOptionsContentDAO +{ + /** + * *

Return the persistent instance of a McOptsContent + * with the given identifier uid, returns null if not found.

+ * + * @param uid + * @return McOptsContent + */ + public McOptsContent getMcOptionsContentByUID(Long uid); + + + /** + *

Return a list of a McOptsContents + * with the given identifier mcQueContentId, returns null if not found.

+ + * @param mcQueContentId + * @return List + */ + public List findMcOptionsContentByQueId(Long mcQueContentId); + + /** + *

Return the persistent instance of a McOptsContent + * with the given identifiers option, mcQueContentUid returns null if not found.

+ * + * @param option + * @param mcQueContentUid + * @return McOptsContent + */ + public McOptsContent getOptionContentByOptionText(final String option, final Long mcQueContentUid); + + /** + *

Return a list of a persisted McOptsContents + * with the given identifier mcQueContentId, returns null if not found.

+ * + * @param mcQueContentId + * @return List + */ + public List getPersistedSelectedOptions(Long mcQueContentId); + + public List getCorrectOption(Long mcQueContentId); + + /** + *

saves McOptsContent

+ * @param mcOptionsContent + */ + public void saveMcOptionsContent(McOptsContent mcOptionsContent); + + /** + *

updates McOptsContent

+ * @param mcOptionsContent + */ + public void updateMcOptionsContent(McOptsContent mcOptionsContent); + + /** + *

removes McOptsContent

+ * @param mcOptionsContent + */ + public void removeMcOptionsContentByUID(Long uid); + + /** + *

removes McOptsContent

+ * @param mcOptionsContent + */ + public void removeMcOptionsContentByQueId(Long mcQueContentId); + + /** + *

removes McOptsContent

+ * @param mcOptionsContent + */ + public void removeMcOptionsContent(McOptsContent mcOptsContent); +} + + + Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcQueContentDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcQueContentDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcQueContentDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,178 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.dao; + +import java.util.List; + +import org.lamsfoundation.lams.tool.mc.McQueContent; + + +/** + * + * @author Ozgur Demirtas + *

Interface for the McQueContent DAO, defines methods needed to access/modify mc question content

+ * + */ +public interface IMcQueContentDAO +{ + /** + * *

Return the persistent instance of a McQueContent + * with the given identifier uid, returns null if not found.

+ * + * @param uid + * @return McQueContent + */ + public McQueContent getMcQueContentByUID(Long uid); + + /** + * *

Return the persistent instance of a McQueContent + * with the given identifier mcContentId, returns null if not found.

+ * + * @param mcContentId + * @return McQueContent + */ + public McQueContent getToolDefaultQuestionContent(final long mcContentId); + + + + /** + * *

Return the persistent instance of a McQueContent + * with the given identifier question and mcContentUid, returns null if not found.

+ * + * @param question + * @param mcContentUid + * @return McQueContent + */ + public McQueContent getQuestionContentByQuestionText(final String question, final Long mcContentUid); + + /** + * *

Return the persistent instance of a McQueContent + * with the given identifier displayOrder and mcContentUid, returns null if not found.

+ * + * @param displayOrder + * @param mcContentUid + * @return McQueContent + */ + public McQueContent getQuestionContentByDisplayOrder(final Long displayOrder, final Long mcContentUid); + + /** + * *

Return a list of McQueContent + * with the given identifier question and mcContentUid, returns null if not found.

+ * + * @param mcContentUid + * @return List + */ + public List getAllQuestionEntries(final long mcContentId); + + /** + * *

Return a list of McQueContent + * with the given identifier question and mcContentUid, returns null if not found.

+ * + * @param mcContentUid + * @return List + */ + public List refreshQuestionContent(final Long mcContentId); + + /** + * *

removes McQueContent + * with the given identifier question and mcContentUid, returns null if not found.

+ * + * @param mcContentUid + */ + public void cleanAllQuestions(final Long mcContentUid); + + /** + * *

removes McQueContent + * with the given identifier mcContentUid

+ * + * @param mcContentUid + */ + public void cleanAllQuestionsSimple(final Long mcContentUid); + + /** + * *

resets McQueContent + * with the given identifier mcContentUid

+ * + * @param mcContentUid + */ + public void resetAllQuestions(final Long mcContentUid); + + /** + * *

removes McQueContent + * with the given identifier mcContentUid

+ * + * @param mcContentUid + */ + public void removeQuestionContentByMcUid(final Long mcContentUid); + + /** + * *

saves McQueContent + * with the given identifier mcQueContent

+ * + * @param mcQueContent + */ + public void saveMcQueContent(McQueContent mcQueContent); + + /** + * *

updates McQueContent + * with the given identifier mcQueContent

+ * + * @param mcQueContent + */ + public void updateMcQueContent(McQueContent mcQueContent); + + /** + * *

saves McQueContent + * with the given identifier mcQueContent

+ * + * @param mcQueContent + */ + public void saveOrUpdateMcQueContent(McQueContent mcQueContent); + + /** + * *

removes McQueContent + * with the given identifier uid

+ * + * @param uid + */ + public void removeMcQueContentByUID(Long uid); + + /** + * *

removes McQueContent + * with the given identifier mcQueContent

+ * + * @param mcQueContent + * @return + */ + public void removeMcQueContent(McQueContent mcQueContent); + + /** + * *

used to get the next available display order + * with the given identifier mcContentId

+ * + * @param mcQueContent + * @return + */ + public List getNextAvailableDisplayOrder(final long mcContentId); + +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcSessionDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcSessionDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcSessionDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,123 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.dao; + +import java.util.List; + +import org.lamsfoundation.lams.tool.mc.McContent; +import org.lamsfoundation.lams.tool.mc.McQueUsr; +import org.lamsfoundation.lams.tool.mc.McSession; +import org.springframework.orm.hibernate3.HibernateTemplate; + + +/** + * @author Ozgur Demirtas + *

Interface for the McSession DAO, defines methods needed to access/modify mc session

+ * + */ +public interface IMcSessionDAO { + + /** + *

Return the persistent instance of a McSession + * with the given identifier uid, returns null if not found.

+ * + * @param uid an identifier for the McSession object. + * @return the persistent instance of a McSession or null if not found + */ + + public McSession getMcSessionByUID(Long uid); + + /** + *

Return the persistent instance of a McSession + * with the given tool session id mcSessionId, + * returns null if not found.

+ * + * @param mcSessionId The tool session id + * @return the persistent instance of a McSession or null if not found. + */ + public McSession findMcSessionById(Long mcSessionId); + + + + /** + *

Persist the given persistent instance of McSession.

+ * + * @param mcSession The instance of McSession to persist. + */ + public void saveMcSession(McSession mcSession); + + /** + *

Update the given persistent instance of McSession.

+ * + * @param mcContent The instance of McSession to persist. + */ + public void updateMcSession(McSession mcSession); + + /** + *

Delete the given instance of McSession with the + * given identifier uid + * + * @param uid an identifier for the McSession instance. + */ + public void removeMcSessionByUID(Long uid); + + public void removeMcSessionById(Long mcSessionId); + + public void removeMcSession(McSession mcSession); + + + /** + *

Returns the persistent instance of McSession + * associated with the given mc user, with user id userId, + * returns null if not found. + * + * @param userId The mc user id + * @return a persistent instance of McSessions or null if not found. + */ + public McSession getMcSessionByUser(Long userId); + + + + /** + *

Creates and persists an instance of McQueUsr which is associated + * with the McSession with tool session id mcSessionId

+ * + * @param mcSessionId The tool session id + * @param user The instance of McQueUsr + */ + public void addMcUsers(Long mcSessionId, McQueUsr user); + + /** + * Returns a list of tool session ids which are associated with this + * instance of McContent. + + * @param nbContent The instance of McContent in which you want the list of toolSessionIds + * @return a list of tool session Ids + */ + public List getSessionsFromContent(McContent mcContent); + + + public int countSessionComplete(); + + public int countSessionIncomplete(); +} \ No newline at end of file Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcUploadedFileDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcUploadedFileDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcUploadedFileDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,171 @@ +/* + *Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * + *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; either version 2 of the License, or + *(at your option) any later version. + * + *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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + *USA + * + *http://www.gnu.org/licenses/gpl.txt + */ +package org.lamsfoundation.lams.tool.mc.dao; + +import java.util.List; + +import org.lamsfoundation.lams.tool.mc.McUploadedFile; + +/** + * + * @author Ozgur Demirtas + *

Interface for the McUploadedFile DAO, defines methods needed to access/modify mc uploadedFile content

+ * + */ +public interface IMcUploadedFileDAO +{ + /** + * *

Return the persistent instance of a McUploadedFile + * with the given identifier submissionId, returns null if not found.

+ * + * @param submissionId + * @return McUploadedFile + */ + public McUploadedFile loadUploadedFileById(long submissionId); + + /** + * *

updates McUploadedFile + * with the given identifier mcUploadedFile

+ * + * @param mcUploadedFile + * @return McUploadedFile + */ + public void updateUploadFile(McUploadedFile mcUploadedFile); + + /** + * *

saves McUploadedFile + * with the given identifier mcUploadedFile

+ * + * @param mcUploadedFile + * @return + */ + public void saveUploadFile(McUploadedFile mcUploadedFile); + + /** + * *

creates McUploadedFile + * with the given identifier mcUploadedFile

+ * + * @param mcUploadedFile + * @return + */ + public void createUploadFile(McUploadedFile mcUploadedFile); + + /** + * *

Updates McUploadedFile + * with the given identifier mcUploadedFile

+ * + * @param mcUploadedFile + * @return + */ + public void UpdateUploadFile(McUploadedFile mcUploadedFile); + + /** + * *

removes McUploadedFile + * with the given identifier mcUploadedFile

+ * + * @param submissionId + * @return + */ + public void removeUploadFile(Long submissionId); + + /** + * *

deletes McUploadedFile + * with the given identifier mcUploadedFile

+ * + * @param mcUploadedFile + * @return + */ + public void deleteUploadFile(McUploadedFile mcUploadedFile); + + /** + * *

returns file's uuid + * with the given identifier filename

+ * + * @param filename + * @return + */ + public String getFileUuid(String filename); + + /** + * *

returns a list of McUploadedFiles + * with the given identifier mcContentId and fileOnline

+ * + * @param mcContentId + * @param fileOnline + * @return List + */ + public List retrieveMcUploadedFiles(Long mcContentId, boolean fileOnline); + + /** + * *

returns a list of offline McUploadedFiles + * with the given identifier mcContentId

+ * + * @param mcContentId + * @return List + */ + public List retrieveMcUploadedOfflineFilesUuid(Long mcContentId); + + /** + * *

returns a list of online McUploadedFiles + * with the given identifier mcContentId

+ * + * @param mcContentId + * @return List + */ + public List retrieveMcUploadedOnlineFilesUuid(Long mcContentId); + + /** + * *

returns a list of offline McUploadedFile filenames + * with the given identifier mcContentId

+ * + * @param mcContentId + * @return List + */ + public List retrieveMcUploadedOfflineFilesName(Long mcContentId); + + /** + * *

returns a list of online McUploadedFile filenames + * with the given identifier mcContentId

+ * + * @param mcContentId + * @return List + */ + public List retrieveMcUploadedOnlineFilesName(Long mcContentId); + + /** + * *

returns a list of offline McUploadedFile uuid and filenames + * with the given identifier mcContentId

+ * + * @param mcContentId + * @return List + */ + public List retrieveMcUploadedOfflineFilesUuidPlusFilename(Long mcContentId); + + /** + * *

removes files meta data + * + * @param mcContentId + * @return List + */ + public void cleanUploadedFilesMetaData(); + + public void flush(); +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcUserDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcUserDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcUserDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,89 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + + +package org.lamsfoundation.lams.tool.mc.dao; + +import org.lamsfoundation.lams.tool.mc.McQueUsr; +import org.lamsfoundation.lams.tool.mc.McSession; + +/** + * @author Ozgur Demirtas + *

Interface for the McUser DAO, defines methods needed to access/modify user data

+ */ +public interface IMcUserDAO { + + /** + *

Return the persistent instance of a McQueUsr + * with the given identifier uid, returns null if not found.

+ * + * @param uid an identifier for the McQueUsr. + * @return the persistent instance of a McQueUsr or null if not found + */ + public McQueUsr getMcUserByUID(Long uid); + + /** + *

Return the persistent instance of a McQueUsr + * with the given user id userId, + * returns null if not found.

+ * + * @param userId The id of a McQueUsr + * @return the persistent instance of a McQueUsr or null if not found. + */ + public McQueUsr findMcUserById(Long userId); + + public McQueUsr getMcUserBySession(Long userId, Long sessionId); + + public void saveMcUser(McQueUsr mcUser); + + /** + *

Update the given persistent instance of McQueUsr.

+ * + * @param nbUser The instance of McQueUsr to persist. + */ + public void updateMcUser(McQueUsr mcUser); + + /** + *

Delete the given instance of McQueUsr

+ * + * @param nbUser The instance of McQueUsr to delete. + */ + public void removeMcUser(McQueUsr mcUser); + + /** + *

Delete the given instance of McQueUsr with the + * given user id userId + * + * @param userId The mc user id. + */ + public void removeMcUserById(Long userId); + + /** + * Returns the number of users that are in this particular + * session. + * + * @param nbSession + * @return the number of users that are in this session + */ + public int getNumberOfUsers(McSession mcSession); + +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcUsrAttemptDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcUsrAttemptDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/IMcUsrAttemptDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,130 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.dao; + +import java.util.List; + +import org.lamsfoundation.lams.tool.mc.McUsrAttempt; + + +/** + * + * @author Ozgur Demirtas + * *

Interface for the McUsrAttempt DAO, defines methods needed to access/modify user attempt data

+ * + */ +public interface IMcUsrAttemptDAO +{ + /** + * *

Return the persistent instance of a McUsrAttempt + * with the given identifier uid, returns null if not found.

+ * + * @param uid + * @return McQueContent + */ + public McUsrAttempt getMcUserAttemptByUID(Long uid); + + /** + * *

saves McUsrAttempt + * with the given identifier mcUsrAttempt

+ * + * @param uid + * @return + */ + public void saveMcUsrAttempt(McUsrAttempt mcUsrAttempt); + + /** + * *

updates McUsrAttempt + * with the given identifier mcUsrAttempt

+ * + * @param mcUsrAttempt + * @return + */ + public void updateMcUsrAttempt(McUsrAttempt mcUsrAttempt); + + /** + * *

removes McUsrAttempt + * with the given identifier uid

+ * + * @param uid + * @return + */ + public void removeMcUsrAttemptByUID(Long uid); + + /** + * *

removes McUsrAttempt + * with the given identifier mcUsrAttempt

+ * + * @param mcUsrAttempt + * @return + */ + public void removeMcUsrAttempt(McUsrAttempt mcUsrAttempt); + + /** + * *

returns the highest mark of a learner + * with the given identifier queUsrId

+ * + * @param queUsrId + * @return + */ + public List getHighestMark(Long queUsrId); + + /** + * *

returns the highest mark of a learner + * with the given identifier queUsrId

+ * + * @param queUsrId + * @return + */ + public List getHighestAttemptOrder(Long queUsrId); + + /** + * *

returns a list of attempts + * with the given identifiers queUsrId and mcQueContentId

+ * + * @param queUsrId + * @param mcQueContentId + * @return + */ + public List getAttemptForQueContent(final Long queUsrId, final Long mcQueContentId); + + /** + * *

returns a list of attempts + * with the given identifiers queUsrId and mcQueContentId and attemptOrder

+ * + * @param queUsrId + * @param mcQueContentId + * @param attemptOrder + * @return + */ + public List getAttemptByAttemptOrder(final Long queUsrId, final Long mcQueContentId, final Integer attemptOrder); + + /** + * *

returns a list of marks + * + * @return + */ + public List getMarks(); +} + + Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McContentDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McContentDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McContentDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,149 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.dao.hibernate; + +import java.util.List; + +import org.hibernate.FlushMode; +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.lamsfoundation.lams.tool.mc.McContent; +import org.lamsfoundation.lams.tool.mc.McSession; +import org.lamsfoundation.lams.tool.mc.dao.IMcContentDAO; +import org.springframework.orm.hibernate3.HibernateCallback; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.orm.hibernate3.support.HibernateDaoSupport; + +/** + * @author Ozgur Demirtas + *

Hibernate implementation for database access to McContent for the mc tool.

+ */ + +public class McContentDAO extends HibernateDaoSupport implements IMcContentDAO { + private static final String FIND_MC_CONTENT = "from " + McContent.class.getName() + " as mc where content_id=?"; + + private static final String LOAD_MC_BY_SESSION = "select mc from McContent mc left join fetch " + + "mc.mcSessions session where session.mcSessionId=:sessionId"; + + public McContent getMcContentByUID(Long uid) + { + return (McContent) this.getHibernateTemplate().get(McContent.class, uid); + } + + + /** Finds a package via the tool content id. Returns + * null if not found + */ + public McContent findMcContentById(Long mcContentId) + { + String query = "from McContent as mc where mc.mcContentId = ?"; + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(query) + .setLong(0,mcContentId.longValue()) + .list(); + + if(list != null && list.size() > 0){ + McContent mc = (McContent) list.get(0); + return mc; + } + return null; + } + + + public McContent getMcContentBySession(final Long mcSessionId) + { + return (McContent) getHibernateTemplate().execute(new HibernateCallback() + { + + public Object doInHibernate(Session session) throws HibernateException + { + return session.createQuery(LOAD_MC_BY_SESSION) + .setLong("sessionId", + mcSessionId.longValue()) + .uniqueResult(); + } + }); + } + + + + public void saveMcContent(McContent mcContent) + { + this.getHibernateTemplate().save(mcContent); + } + + + public void updateMcContent(McContent mcContent) + { + this.getHibernateTemplate().update(mcContent); + } + + + public void removeMcById(Long mcContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + if ( mcContentId != null) { + List list = getSession().createQuery(FIND_MC_CONTENT) + .setLong(0,mcContentId.longValue()) + .list(); + + if(list != null && list.size() > 0){ + McContent mc = (McContent) list.get(0); + this.getSession().setFlushMode(FlushMode.AUTO); + templ.delete(mc); + templ.flush(); + } + } + } + + public void removeMc(McContent mcContent) + { + this.getHibernateTemplate().delete(mcContent); + } + + + public void removeMcSessions(McContent mcContent) + { + this.getHibernateTemplate().deleteAll(mcContent.getMcSessions()); + } + + + public void addMcSession(Long mcContentId, McSession mcSession) + { + McContent content = findMcContentById(mcContentId); + mcSession.setMcContent(content); + content.getMcSessions().add(mcSession); + this.getHibernateTemplate().saveOrUpdate(mcSession); + this.getHibernateTemplate().saveOrUpdate(content); + } + + public List findAll(Class objClass) { + String query="from obj in class " + objClass.getName(); + return this.getHibernateTemplate().find(query); + } + + public void flush() + { + this.getHibernateTemplate().flush(); + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McOptionsContentDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McOptionsContentDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McOptionsContentDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,153 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ +package org.lamsfoundation.lams.tool.mc.dao.hibernate; + +import java.util.Iterator; +import java.util.List; + +import org.apache.log4j.Logger; +import org.hibernate.FlushMode; +import org.lamsfoundation.lams.tool.mc.McOptsContent; +import org.lamsfoundation.lams.tool.mc.dao.IMcOptionsContentDAO; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.orm.hibernate3.support.HibernateDaoSupport; + + +/** + * @author Ozgur Demirtas + *

Hibernate implementation for database access to McOptionsContent for the mc tool.

+ */ +public class McOptionsContentDAO extends HibernateDaoSupport implements IMcOptionsContentDAO { + static Logger logger = Logger.getLogger(McOptionsContentDAO.class.getName()); + + private static final String FIND_MC_OPTIONS_CONTENT = "from " + McOptsContent.class.getName() + " as mco where mc_que_content_id=?"; + + private static final String LOAD_OPTION_CONTENT_BY_OPTION_TEXT = "from mcOptsContent in class McOptsContent where mcOptsContent.mcQueOptionText=:option and mcOptsContent.mcQueContentId=:mcQueContentUid"; + + private static final String LOAD_PERSISTED_SELECTED_OPTIONS = "from mcOptsContent in class McOptsContent where mcOptsContent.mcQueContentId=:mcQueContentUid and mcOptsContent.correctOption = 1"; + + private static final String LOAD_CORRECT_OPTION = "from mcOptsContent in class McOptsContent where mcOptsContent.mcQueContentId=:mcQueContentUid and mcOptsContent.correctOption = 1"; + + public McOptsContent getMcOptionsContentByUID(Long uid) + { + return (McOptsContent) this.getHibernateTemplate() + .get(McOptsContent.class, uid); + } + + + public List findMcOptionsContentByQueId(Long mcQueContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + if ( mcQueContentId != null) { + List list = getSession().createQuery(FIND_MC_OPTIONS_CONTENT) + .setLong(0,mcQueContentId.longValue()) + .list(); + return list; + } + return null; + } + + + public McOptsContent getOptionContentByOptionText(final String option, final Long mcQueContentUid) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_OPTION_CONTENT_BY_OPTION_TEXT) + .setString("option", option) + .setLong("mcQueContentUid", mcQueContentUid.longValue()) + .list(); + + if(list != null && list.size() > 0){ + McOptsContent mcq = (McOptsContent) list.get(0); + return mcq; + } + return null; + } + + + public List getPersistedSelectedOptions(Long mcQueContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_PERSISTED_SELECTED_OPTIONS) + .setLong("mcQueContentUid", mcQueContentId.longValue()) + .list(); + + return list; + } + + public List getCorrectOption(Long mcQueContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_CORRECT_OPTION) + .setLong("mcQueContentUid", mcQueContentId.longValue()) + .list(); + + return list; + } + + public void saveMcOptionsContent(McOptsContent mcOptsContent) + { + this.getHibernateTemplate().save(mcOptsContent); + } + + public void updateMcOptionsContent(McOptsContent mcOptsContent) + { + this.getHibernateTemplate().update(mcOptsContent); + } + + + public void removeMcOptionsContentByUID(Long uid) + { + McOptsContent mco = (McOptsContent)getHibernateTemplate().get(McOptsContent.class, uid); + this.getHibernateTemplate().delete(mco); + } + + + public void removeMcOptionsContentByQueId(Long mcQueContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(FIND_MC_OPTIONS_CONTENT) + .setLong(0,mcQueContentId.longValue()) + .list(); + + if(list != null && list.size() > 0){ + Iterator listIterator=list.iterator(); + while (listIterator.hasNext()) + { + McOptsContent mcOptsContent=(McOptsContent)listIterator.next(); + this.getSession().setFlushMode(FlushMode.AUTO); + templ.delete(mcOptsContent); + } + } + } + + + public void removeMcOptionsContent(McOptsContent mcOptsContent) + { + this.getSession().setFlushMode(FlushMode.AUTO); + this.getHibernateTemplate().delete(mcOptsContent); + } + + public void flush() + { + this.getHibernateTemplate().flush(); + } +} \ No newline at end of file Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McQueContentDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McQueContentDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McQueContentDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,260 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ +package org.lamsfoundation.lams.tool.mc.dao.hibernate; + +import java.util.Iterator; +import java.util.List; + +import org.apache.log4j.Logger; +import org.hibernate.FlushMode; +import org.lamsfoundation.lams.tool.mc.McQueContent; +import org.lamsfoundation.lams.tool.mc.dao.IMcQueContentDAO; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.orm.hibernate3.support.HibernateDaoSupport; + + +/** + * @author ozgurd + * + *

Hibernate implementation for database access to McQueContent for the mc tool.

+ */ +public class McQueContentDAO extends HibernateDaoSupport implements IMcQueContentDAO { + static Logger logger = Logger.getLogger(McQueContentDAO.class.getName()); + + private static final String LOAD_QUESTION_CONTENT_BY_CONTENT_ID = "from mcQueContent in class McQueContent where mcQueContent.mcContentId=:mcContentId order by mcQueContent.displayOrder"; + + private static final String CLEAN_QUESTION_CONTENT_BY_CONTENT_ID_SIMPLE = "from mcQueContent in class McQueContent where mcQueContent.mcContentId=:mcContentId"; + + private static final String CLEAN_QUESTION_CONTENT_BY_CONTENT_ID = "from mcQueContent in class McQueContent where mcQueContent.mcContentId=:mcContentId and mcQueContent.disabled=true"; + + private static final String REFRESH_QUESTION_CONTENT = "from mcQueContent in class McQueContent where mcQueContent.mcContentId=:mcContentId and mcQueContent.disabled=false order by mcQueContent.displayOrder"; + + private static final String LOAD_QUESTION_CONTENT_BY_QUESTION_TEXT = "from mcQueContent in class McQueContent where mcQueContent.question=:question and mcQueContent.mcContentId=:mcContentUid"; + + private static final String LOAD_QUESTION_CONTENT_BY_DISPLAY_ORDER = "from mcQueContent in class McQueContent where mcQueContent.displayOrder=:displayOrder and mcQueContent.mcContentId=:mcContentUid"; + + private static final String GET_NEXT_AVAILABLE_DISPLAY_ORDER = "from mcQueContent in class McQueContent where mcQueContent.mcContentId=:mcContentId"; + + + public McQueContent getMcQueContentByUID(Long uid) + { + return (McQueContent) this.getHibernateTemplate() + .get(McQueContent.class, uid); + } + + + public McQueContent getToolDefaultQuestionContent(final long mcContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_QUESTION_CONTENT_BY_CONTENT_ID) + .setLong("mcContentId", mcContentId) + .list(); + + if(list != null && list.size() > 0){ + McQueContent mcq = (McQueContent) list.get(0); + return mcq; + } + return null; + } + + + public List getAllQuestionEntries(final long mcContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_QUESTION_CONTENT_BY_CONTENT_ID) + .setLong("mcContentId", mcContentId) + .list(); + + return list; + } + + public List refreshQuestionContent(final Long mcContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(REFRESH_QUESTION_CONTENT) + .setLong("mcContentId", mcContentId.longValue()) + .list(); + + return list; + } + + + public McQueContent getQuestionContentByQuestionText(final String question, final Long mcContentUid) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_QUESTION_CONTENT_BY_QUESTION_TEXT) + .setString("question", question) + .setLong("mcContentUid", mcContentUid.longValue()) + .list(); + + if(list != null && list.size() > 0){ + McQueContent mcq = (McQueContent) list.get(0); + return mcq; + } + return null; + } + + + public McQueContent getQuestionContentByDisplayOrder(final Long displayOrder, final Long mcContentUid) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_QUESTION_CONTENT_BY_DISPLAY_ORDER) + .setLong("displayOrder", displayOrder.longValue()) + .setLong("mcContentUid", mcContentUid.longValue()) + .list(); + + if(list != null && list.size() > 0){ + McQueContent mcq = (McQueContent) list.get(0); + return mcq; + } + return null; + } + + + public void removeQuestionContentByMcUid(final Long mcContentUid) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_QUESTION_CONTENT_BY_CONTENT_ID) + .setLong("mcContentId", mcContentUid.longValue()) + .list(); + + if(list != null && list.size() > 0){ + Iterator listIterator=list.iterator(); + while (listIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)listIterator.next(); + this.getSession().setFlushMode(FlushMode.AUTO); + templ.delete(mcQueContent); + templ.flush(); + } + } + } + + + public void resetAllQuestions(final Long mcContentUid) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_QUESTION_CONTENT_BY_CONTENT_ID) + .setLong("mcContentId", mcContentUid.longValue()) + .list(); + + if(list != null && list.size() > 0){ + Iterator listIterator=list.iterator(); + while (listIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)listIterator.next(); + mcQueContent.setDisabled(true); + this.getSession().setFlushMode(FlushMode.AUTO); + templ.update(mcQueContent); + } + } + } + + + public void cleanAllQuestions(final Long mcContentUid) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(CLEAN_QUESTION_CONTENT_BY_CONTENT_ID) + .setLong("mcContentId", mcContentUid.longValue()) + .list(); + + if(list != null && list.size() > 0){ + logger.debug("will iterate the list of McQueContent"); + Iterator listIterator=list.iterator(); + while (listIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)listIterator.next(); + this.getSession().setFlushMode(FlushMode.AUTO); + logger.debug("deleting mcQueContent: " + mcQueContent); + templ.delete(mcQueContent); + } + } + } + + + public void cleanAllQuestionsSimple(final Long mcContentUid) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(CLEAN_QUESTION_CONTENT_BY_CONTENT_ID_SIMPLE) + .setLong("mcContentId", mcContentUid.longValue()) + .list(); + + if(list != null && list.size() > 0){ + logger.debug("will iterate the list of McQueContent"); + Iterator listIterator=list.iterator(); + while (listIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)listIterator.next(); + this.getSession().setFlushMode(FlushMode.AUTO); + logger.debug("deleting mcQueContent: " + mcQueContent); + templ.delete(mcQueContent); + } + } + } + + + public List getNextAvailableDisplayOrder(final long mcContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(GET_NEXT_AVAILABLE_DISPLAY_ORDER) + .setLong("mcContentId", mcContentId) + .list(); + + return list; + } + + + public void saveMcQueContent(McQueContent mcQueContent) + { + this.getHibernateTemplate().save(mcQueContent); + } + + public void updateMcQueContent(McQueContent mcQueContent) + { + this.getHibernateTemplate().update(mcQueContent); + } + + public void saveOrUpdateMcQueContent(McQueContent mcQueContent) + { + this.getHibernateTemplate().saveOrUpdate(mcQueContent); + } + + public void removeMcQueContentByUID(Long uid) + { + McQueContent mcq = (McQueContent)getHibernateTemplate().get(McQueContent.class, uid); + this.getSession().setFlushMode(FlushMode.AUTO); + this.getHibernateTemplate().delete(mcq); + } + + + public void removeMcQueContent(McQueContent mcQueContent) + { + this.getSession().setFlushMode(FlushMode.AUTO); + this.getHibernateTemplate().delete(mcQueContent); + } + + public void flush() + { + this.getHibernateTemplate().flush(); + } + +} \ No newline at end of file Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McSessionDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McSessionDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McSessionDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,189 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.dao.hibernate; + +import java.util.List; + +import org.hibernate.FlushMode; +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.lamsfoundation.lams.tool.mc.McContent; +import org.lamsfoundation.lams.tool.mc.McQueUsr; +import org.lamsfoundation.lams.tool.mc.McSession; +import org.lamsfoundation.lams.tool.mc.dao.IMcSessionDAO; +import org.springframework.orm.hibernate3.HibernateCallback; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.orm.hibernate3.support.HibernateDaoSupport; + +/** + * @author ozgurd + *

Hibernate implementation for database access to Mc sessions for the mc tool.

+ */ + +public class McSessionDAO extends HibernateDaoSupport implements IMcSessionDAO { + + private static final String FIND_MC_SESSION_CONTENT = "from " + McSession.class.getName() + " as mcs where mc_session_id=?"; + + private static final String LOAD_MCSESSION_BY_USER = "select ms from McSession ms left join fetch " + + "ms.mcQueUsers user where user.queUsrId=:userId"; + + private static final String GET_SESSIONS_FROM_CONTENT = "select ms.mcSessionId from McSession ms where ms.mcContent=:mcContent"; + + private static final String COUNT_SESSION_COMPLETE = "from mcSession in class McSession where mcSession.sessionStatus='COMPLETE'"; + + private static final String COUNT_SESSION_INCOMPLETE = "from mcSession in class McSession where mcSession.sessionStatus='INCOMPLETE'"; + + public McSession getMcSessionByUID(Long uid) + { + return (McSession) this.getHibernateTemplate() + .get(McSession.class, uid); + } + + public McSession findMcSessionById(Long mcSessionId) + { + String query = "from McSession mcs where mcs.mcSessionId=?"; + + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(query) + .setLong(0,mcSessionId.longValue()) + .list(); + + if(list != null && list.size() > 0){ + McSession mcs = (McSession) list.get(0); + return mcs; + } + return null; + } + + public int countSessionComplete() + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(COUNT_SESSION_COMPLETE) + .list(); + + if(list != null && list.size() > 0){ + return list.size(); + } + else return 0; + } + + public int countSessionIncomplete() + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(COUNT_SESSION_INCOMPLETE) + .list(); + + if(list != null && list.size() > 0){ + return list.size(); + } + else return 0; + } + + + public void saveMcSession(McSession mcSession) + { + this.getHibernateTemplate().save(mcSession); + } + + + public void updateMcSession(McSession mcSession) + { + this.getHibernateTemplate().update(mcSession); + } + + + public void removeMcSessionByUID(Long uid) + { + McSession ms = (McSession)getHibernateTemplate().get(McSession.class, uid); + this.getHibernateTemplate().delete(ms); + } + + public void removeMcSessionById(Long mcSessionId) + { + String query = "from McSession as mcs where mcs.mcSessionId ="; + + HibernateTemplate templ = this.getHibernateTemplate(); + if ( mcSessionId != null) { + List list = getSession().createQuery(FIND_MC_SESSION_CONTENT) + .setLong(0,mcSessionId.longValue()) + .list(); + + if(list != null && list.size() > 0){ + McSession mcs = (McSession) list.get(0); + this.getSession().setFlushMode(FlushMode.AUTO); + templ.delete(mcs); + templ.flush(); + } + } + + + } + + public void removeMcSession(McSession mcSession) + { + this.getSession().setFlushMode(FlushMode.AUTO); + this.getHibernateTemplate().delete(mcSession); + } + + + + public McSession getMcSessionByUser(final Long userId) + { + return (McSession) getHibernateTemplate().execute(new HibernateCallback() + { + + public Object doInHibernate(Session session) throws HibernateException + { + return session.createQuery(LOAD_MCSESSION_BY_USER) + .setLong("userId", + userId.longValue()) + .uniqueResult(); + } + }); + } + + + public void removeMcUsers(McSession mcSession) + { + this.getHibernateTemplate().deleteAll(mcSession.getMcQueUsers()); + } + + + public void addMcUsers(Long mcSessionId, McQueUsr user) + { + McSession session = findMcSessionById(mcSessionId); + user.setMcSession(session); + session.getMcQueUsers().add(user); + this.getHibernateTemplate().saveOrUpdate(user); + this.getHibernateTemplate().saveOrUpdate(session); + + } + + + public List getSessionsFromContent(McContent mcContent) + { + return (getHibernateTemplate().findByNamedParam(GET_SESSIONS_FROM_CONTENT, + "mcContent", + mcContent)); + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McUploadedFileDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McUploadedFileDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McUploadedFileDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,248 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.dao.hibernate; + +import java.util.Iterator; +import java.util.List; + +import org.apache.log4j.Logger; +import org.hibernate.FlushMode; + +import org.lamsfoundation.lams.tool.mc.McUploadedFile; +import org.lamsfoundation.lams.tool.mc.dao.IMcUploadedFileDAO; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.orm.hibernate3.support.HibernateDaoSupport; + + +/** + * @author ozgurd + *

Hibernate implementation for database access to McUploadedFile for the mc tool.

+ */ +public class McUploadedFileDAO extends HibernateDaoSupport implements IMcUploadedFileDAO { + static Logger logger = Logger.getLogger(McUploadedFileDAO.class.getName()); + + private static final String GET_ONLINE_FILENAMES_FOR_CONTENT = "select mcUploadedFile.filename from McUploadedFile mcUploadedFile where mcUploadedFile.mcContentId = :mcContentId and mcUploadedFile.fileOnline=1"; + private static final String GET_OFFLINE_FILENAMES_FOR_CONTENT = "select mcUploadedFile.filename from McUploadedFile mcUploadedFile where mcUploadedFile.mcContentId = :mcContentId and mcUploadedFile.fileOnline=0"; + + private static final String GET_ONLINE_FILES_UUID = "select mcUploadedFile.uuid from McUploadedFile mcUploadedFile where mcUploadedFile.mcContentId = :mcContentId and mcUploadedFile.fileOnline=1"; + private static final String GET_ONLINE_FILES_NAME ="select mcUploadedFile.filename from McUploadedFile mcUploadedFile where mcUploadedFile.mcContentId = :mcContentId and mcUploadedFile.fileOnline=1 order by mcUploadedFile.uuid"; + + private static final String GET_OFFLINE_FILES_UUID = "select mcUploadedFile.uuid from McUploadedFile mcUploadedFile where mcUploadedFile.mcContentId = :mcContentId and mcUploadedFile.fileOnline=0"; + private static final String GET_OFFLINE_FILES_NAME ="select mcUploadedFile.filename from McUploadedFile mcUploadedFile where mcUploadedFile.mcContentId = :mcContentId and mcUploadedFile.fileOnline=0 order by mcUploadedFile.uuid"; + + private static final String GET_FILES_UUID ="select mcUploadedFile.uuid from McUploadedFile mcUploadedFile where mcUploadedFile.filename=:filename"; + + + private static final String GET_OFFLINE_FILES_UUIDPLUSFILENAME = "select (mcUploadedFile.uuid + '~' + mcUploadedFile.filename) from McUploadedFile mcUploadedFile where mcUploadedFile.mcContentId = :mcContentId and mcUploadedFile.fileOnline=0"; + + private static final String FIND_ALL_UPLOADED_FILE_DATA = "from mcUploadedFile in class McUploadedFile"; + + + public McUploadedFile getUploadedFileById(long submissionId) + { + return (McUploadedFile) this.getHibernateTemplate() + .load(McUploadedFile.class, new Long(submissionId)); + } + + /** + * + * return null if not found + */ + public McUploadedFile loadUploadedFileById(long uid) + { + return (McUploadedFile) this.getHibernateTemplate().get(McUploadedFile.class, new Long(uid)); + } + + + + public void updateUploadFile(McUploadedFile mcUploadedFile) + { + this.getHibernateTemplate().update(mcUploadedFile); + this.getSession().setFlushMode(FlushMode.AUTO); + } + + + public void saveUploadFile(McUploadedFile mcUploadedFile) + { + this.getHibernateTemplate().save(mcUploadedFile); + this.getSession().setFlushMode(FlushMode.AUTO); + } + + public void createUploadFile(McUploadedFile mcUploadedFile) + { + this.getHibernateTemplate().save(mcUploadedFile); + } + + public void UpdateUploadFile(McUploadedFile mcUploadedFile) + { + this.getHibernateTemplate().update(mcUploadedFile); + } + + + public void cleanUploadedFilesMetaData() + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(FIND_ALL_UPLOADED_FILE_DATA) + .list(); + + if(list != null && list.size() > 0){ + Iterator listIterator=list.iterator(); + while (listIterator.hasNext()) + { + McUploadedFile mcFile=(McUploadedFile)listIterator.next(); + this.getSession().setFlushMode(FlushMode.AUTO); + templ.delete(mcFile); + templ.flush(); + } + } + } + + + public String getFileUuid(String filename) + { + + logger.debug("starting getFileUuid :" + filename); + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(GET_FILES_UUID) + .setString("filename", filename) + .list(); + + logger.debug("list getFileUuid :" + list); + + if (list != null && list.size() > 0){ + Iterator listIterator=list.iterator(); + while (listIterator.hasNext()) + { + String uuid=(String)listIterator.next(); + logger.debug("uuid :" + uuid); + return uuid; + } + } + else + { + return null; + } + return null; + } + + + public void removeUploadFile(Long uid) + { + if (uid != null ) { + + String query = "from uploadedFile in class org.lamsfoundation.lams.tool.mc.McUploadedFile" + + " where uploadedFile.uid = ?"; + Object obj = this.getSession().createQuery(query) + .setLong(0,uid.longValue()) + .uniqueResult(); + if ( obj != null ) { + this.getHibernateTemplate().delete(obj); + } + } + } + + public List retrieveMcUploadedFiles(Long mcContentId, boolean fileOnline) + { + List listFilenames=null; + + if (fileOnline) + { + listFilenames=(getHibernateTemplate().findByNamedParam(GET_ONLINE_FILENAMES_FOR_CONTENT, + "mcContentId", + mcContentId)); + } + else + { + listFilenames=(getHibernateTemplate().findByNamedParam(GET_OFFLINE_FILENAMES_FOR_CONTENT, + "mcContentId", + mcContentId)); + } + return listFilenames; + } + + + public List retrieveMcUploadedOfflineFilesUuid(Long mcContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(GET_OFFLINE_FILES_UUID) + .setLong("mcContentId", mcContentId.longValue()) + .list(); + + + return list; + } + + public List retrieveMcUploadedOnlineFilesUuid(Long mcContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(GET_ONLINE_FILES_UUID) + .setLong("mcContentId", mcContentId.longValue()) + .list(); + + return list; + } + + public List retrieveMcUploadedOfflineFilesUuidPlusFilename(Long mcContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(GET_OFFLINE_FILES_UUIDPLUSFILENAME) + .setLong("mcContentId", mcContentId.longValue()) + .list(); + + return list; + } + + + public List retrieveMcUploadedOfflineFilesName(Long mcContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(GET_OFFLINE_FILES_NAME) + .setLong("mcContentId", mcContentId.longValue()) + .list(); + + return list; + } + + + public List retrieveMcUploadedOnlineFilesName(Long mcContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(GET_ONLINE_FILES_NAME) + .setLong("mcContentId", mcContentId.longValue()) + .list(); + + return list; + } + + + public void deleteUploadFile(McUploadedFile mcUploadedFile) + { + this.getHibernateTemplate().delete(mcUploadedFile); + } + + public void flush() + { + this.getHibernateTemplate().flush(); + } + +} \ No newline at end of file Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McUserDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McUserDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McUserDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,138 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ +/* + * @author ozgurd + */ +package org.lamsfoundation.lams.tool.mc.dao.hibernate; + +import java.util.List; + +import org.hibernate.FlushMode; +import org.lamsfoundation.lams.tool.mc.McQueUsr; +import org.lamsfoundation.lams.tool.mc.McSession; +import org.lamsfoundation.lams.tool.mc.dao.IMcUserDAO; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.orm.hibernate3.support.HibernateDaoSupport; + +/** + * @author ozgurd + *

Hibernate implementation for database access to Mc users (learners) for the mc tool.

+ */ +public class McUserDAO extends HibernateDaoSupport implements IMcUserDAO { + + private static final String FIND_MC_USR_CONTENT = "from " + McQueUsr.class.getName() + " as mcu where que_usr_id=?"; + + private static final String COUNT_USERS_IN_SESSION = "select mu.queUsrId from McQueUsr mu where mu.mcSession= :mcSession"; + + + public McQueUsr getMcUserByUID(Long uid) + { + return (McQueUsr) this.getHibernateTemplate() + .get(McQueUsr.class, uid); + } + + + public McQueUsr findMcUserById(Long userId) + { + String query = "from McQueUsr user where user.queUsrId=?"; + + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(query) + .setLong(0,userId.longValue()) + .list(); + + if(list != null && list.size() > 0){ + McQueUsr mcu = (McQueUsr) list.get(0); + return mcu; + } + return null; + } + + + public McQueUsr getMcUserBySession(Long userId, Long sessionId) + { + /* + String query = "select mu from McQueUsr mu where mu.queUsrId=? and mu.mcSession.mcSessionId=?"; + Long[] bindingValues = new Long[2]; + bindingValues[0] = userId; + bindingValues[1] = sessionId; + List usersReturned = getHibernateTemplate().find(query, bindingValues); + + if (usersReturned!= null && usersReturned.size() == 0) + { + return null; + } + else + { + return (McQueUsr)usersReturned.get(0); + } + */ + return null; + } + + + public void saveMcUser(McQueUsr mcUser) + { + this.getHibernateTemplate().save(mcUser); + } + + + public void updateMcUser(McQueUsr mcUser) + { + this.getHibernateTemplate().update(mcUser); + } + + + public void removeMcUserById(Long userId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + if ( userId != null) { + List list = getSession().createQuery(FIND_MC_USR_CONTENT) + .setLong(0,userId.longValue()) + .list(); + + if(list != null && list.size() > 0){ + McQueUsr mcu = (McQueUsr) list.get(0); + this.getSession().setFlushMode(FlushMode.AUTO); + templ.delete(mcu); + templ.flush(); + } + } + + } + + + public void removeMcUser(McQueUsr mcUser) + { + this.getSession().setFlushMode(FlushMode.AUTO); + this.getHibernateTemplate().delete(mcUser); + } + + + public int getNumberOfUsers(McSession mcSession) + { + return (getHibernateTemplate().findByNamedParam(COUNT_USERS_IN_SESSION, + "mcSession", + mcSession)).size(); + } + +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McUsrAttemptDAO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McUsrAttemptDAO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/dao/hibernate/McUsrAttemptDAO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,133 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.dao.hibernate; + +import java.util.List; + +import org.apache.log4j.Logger; +import org.hibernate.FlushMode; +import org.lamsfoundation.lams.tool.mc.McUsrAttempt; +import org.lamsfoundation.lams.tool.mc.dao.IMcUsrAttemptDAO; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.orm.hibernate3.support.HibernateDaoSupport; + +/** + * @author ozgurd + *

Hibernate implementation for database access to McUsrAttempt for the mc tool.

+ */ +public class McUsrAttemptDAO extends HibernateDaoSupport implements IMcUsrAttemptDAO { + static Logger logger = Logger.getLogger(McUsrAttemptDAO.class.getName()); + + private static final String LOAD_HIGHEST_MARK_BY_USER_ID = "from mcUsrAttempt in class McUsrAttempt where mcUsrAttempt.queUsrId=:queUsrId"; + + private static final String LOAD_HIGHEST_ATTEMPT_ORDER_BY_USER_ID = "from mcUsrAttempt in class McUsrAttempt where mcUsrAttempt.queUsrId=:queUsrId"; + + private static final String LOAD_ATTEMPT_FOR_QUE_CONTENT = "from mcUsrAttempt in class McUsrAttempt where mcUsrAttempt.queUsrId=:queUsrId and mcUsrAttempt.mcQueContentId=:mcQueContentId"; + + private static final String LOAD_ATTEMPT_BY_ATTEMPT_ORDER = "from mcUsrAttempt in class McUsrAttempt where mcUsrAttempt.queUsrId=:queUsrId and mcUsrAttempt.mcQueContentId=:mcQueContentId and attemptOrder=:attemptOrder"; + + private static final String LOAD_MARK = "from mcUsrAttempt in class McUsrAttempt"; + + public McUsrAttempt getMcUserAttemptByUID(Long uid) + { + return (McUsrAttempt) this.getHibernateTemplate() + .get(McUsrAttempt.class, uid); + } + + public void saveMcUsrAttempt(McUsrAttempt mcUsrAttempt) + { + this.getHibernateTemplate().save(mcUsrAttempt); + } + + public List getHighestMark(Long queUsrId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_HIGHEST_MARK_BY_USER_ID) + .setLong("queUsrId", queUsrId.longValue()) + .list(); + + return list; + } + + + public List getMarks() + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_MARK) + .list(); + + return list; + } + + + public List getHighestAttemptOrder(Long queUsrId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_HIGHEST_ATTEMPT_ORDER_BY_USER_ID) + .setLong("queUsrId", queUsrId.longValue()) + .list(); + return list; + } + + public List getAttemptForQueContent(final Long queUsrId, final Long mcQueContentId) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_ATTEMPT_FOR_QUE_CONTENT) + .setLong("queUsrId", queUsrId.longValue()) + .setLong("mcQueContentId", mcQueContentId.longValue()) + .list(); + return list; + } + + + public List getAttemptByAttemptOrder(final Long queUsrId, final Long mcQueContentId, final Integer attemptOrder) + { + HibernateTemplate templ = this.getHibernateTemplate(); + List list = getSession().createQuery(LOAD_ATTEMPT_BY_ATTEMPT_ORDER) + .setLong("queUsrId", queUsrId.longValue()) + .setLong("mcQueContentId", mcQueContentId.longValue()) + .setInteger("attemptOrder", attemptOrder.intValue()) + .list(); + return list; + } + + public void updateMcUsrAttempt(McUsrAttempt mcUsrAttempt) + { + this.getHibernateTemplate().update(mcUsrAttempt); + } + + public void removeMcUsrAttemptByUID(Long uid) + { + McUsrAttempt mca = (McUsrAttempt)getHibernateTemplate().get(McUsrAttempt.class, uid); + this.getSession().setFlushMode(FlushMode.AUTO); + this.getHibernateTemplate().delete(mca); + } + + + public void removeMcUsrAttempt(McUsrAttempt mcUsrAttempt) + { + this.getSession().setFlushMode(FlushMode.AUTO); + this.getHibernateTemplate().delete(mcUsrAttempt); + } + +} \ No newline at end of file Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/mcApplicationContext.xml =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/mcApplicationContext.xml (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/mcApplicationContext.xml (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + /org/lamsfoundation/lams/tool/mc/McContent.hbm.xml + /org/lamsfoundation/lams/tool/mc/McQueContent.hbm.xml + /org/lamsfoundation/lams/tool/mc/McOptsContent.hbm.xml + /org/lamsfoundation/lams/tool/mc/McSession.hbm.xml + /org/lamsfoundation/lams/tool/mc/McQueUsr.hbm.xml + /org/lamsfoundation/lams/tool/mc/McUsrAttempt.hbm.xml + /org/lamsfoundation/lams/tool/mc/McUploadedFile.hbm.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + PROPAGATION_REQUIRED,-McApplicationException + PROPAGATION_REQUIRED,-McApplicationException + PROPAGATION_REQUIRED, -McApplicationException + PROPAGATION_REQUIRED,-McApplicationException + PROPAGATION_REQUIRED,readOnly,-McApplicationException + PROPAGATION_REQUIRED,-McApplicationException + + + + + Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/service/IMcService.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/service/IMcService.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/service/IMcService.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,227 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.service; + +import java.io.InputStream; +import java.util.List; + +import org.lamsfoundation.lams.contentrepository.ITicket; +import org.lamsfoundation.lams.contentrepository.NodeKey; +import org.lamsfoundation.lams.lesson.Lesson; +import org.lamsfoundation.lams.tool.BasicToolVO; +import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; +import org.lamsfoundation.lams.tool.exception.DataMissingException; +import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; +import org.lamsfoundation.lams.tool.exception.ToolException; +import org.lamsfoundation.lams.tool.mc.McApplicationException; +import org.lamsfoundation.lams.tool.mc.McContent; +import org.lamsfoundation.lams.tool.mc.McOptsContent; +import org.lamsfoundation.lams.tool.mc.McQueContent; +import org.lamsfoundation.lams.tool.mc.McQueUsr; +import org.lamsfoundation.lams.tool.mc.McSession; +import org.lamsfoundation.lams.tool.mc.McUsrAttempt; +import org.lamsfoundation.lams.usermanagement.User; + + +/** + * @author Ozgur Demirtas + * + * Interface that defines the contract that all MCQ service provider must follow. + */ +public interface IMcService +{ + public void configureContentRepository() throws McApplicationException; + + public void createMc(McContent mcContent) throws McApplicationException; + + public McContent retrieveMc(Long toolContentId) throws McApplicationException; + + public void createMcQue(McQueContent mcQueContent) throws McApplicationException; + + public McQueContent getQuestionContentByDisplayOrder(final Long displayOrder, final Long mcContentUid) throws McApplicationException; + + public void createMcSession(McSession mcSession) throws McApplicationException; + + public void createMcQueUsr(McQueUsr mcQueUsr) throws McApplicationException; + + public McQueUsr retrieveMcQueUsr(Long userId) throws McApplicationException; + + public void createMcUsrAttempt(McUsrAttempt mcUsrAttempt) throws McApplicationException; + + public void updateMcUsrAttempt(McUsrAttempt mcUsrAttempt) throws McApplicationException; + + public McQueContent retrieveMcQueContentByUID(Long uid) throws McApplicationException; + + public void removeMcQueContent(McQueContent mcQueContent) throws McApplicationException; + + public McQueContent getMcQueContentByUID(Long uid) throws McApplicationException; + + public void saveOrUpdateMcQueContent(McQueContent mcQueContent) throws McApplicationException; + + public void removeQuestionContentByMcUid(final Long mcContentUid) throws McApplicationException; + + public McOptsContent getMcOptionsContentByUID(Long uid) throws McApplicationException; + + public void cleanAllQuestionsSimple(final Long mcContentUid) throws McApplicationException; + + public void resetAllQuestions(final Long mcContentUid) throws McApplicationException; + + public void cleanAllQuestions(final Long mcContentUid) throws McApplicationException; + + public List refreshQuestionContent(final Long mcContentId) throws McApplicationException; + + public void removeMcOptionsContentByQueId(Long mcQueContentId) throws McApplicationException; + + public void removeMcOptionsContent(McOptsContent mcOptsContent); + + public McQueContent getQuestionContentByQuestionText(final String question, final Long mcContentUid); + + public List getPersistedSelectedOptions(Long mcQueContentId); + + public void removeMcQueContentByUID(Long uid) throws McApplicationException; + + public List getCorrectOption(Long mcQueContentId); + + public List getAllQuestionEntries(final Long mcContentId) throws McApplicationException; + + public McSession retrieveMcSession(Long mcSessionId) throws McApplicationException; + + public McContent retrieveMcBySessionId(Long mcSessionId) throws McApplicationException; + + public void updateMc(McContent mc) throws McApplicationException; + + public void updateMcSession(McSession mcSession) throws McApplicationException; + + public void deleteMc(McContent mc) throws McApplicationException; + + public void deleteMcById(Long mcId) throws McApplicationException; + + public void deleteMcSession(McSession mcSession) throws McApplicationException; + + public void removeAttempt (McUsrAttempt attempt) throws McApplicationException; + + public void deleteMcQueUsr(McQueUsr mcQueUsr) throws McApplicationException; + + public List findMcOptionsContentByQueId(Long mcQueContentId) throws McApplicationException; + + public void saveMcOptionsContent(McOptsContent mcOptsContent) throws McApplicationException; + + public McOptsContent getOptionContentByOptionText(final String option, final Long mcQueContentUid); + + public void updateMcOptionsContent(McOptsContent mcOptsContent) throws McApplicationException; + + public void deleteMcOptionsContent(McOptsContent mcOptsContent) throws McApplicationException; + + public void deleteMcOptionsContentByUID(Long uid) throws McApplicationException; + + public User getCurrentUserData(String username) throws McApplicationException; + + public Lesson getCurrentLesson(long lessonId) throws McApplicationException; + + public void saveMcContent(McContent mc) throws McApplicationException; + + public boolean studentActivityOccurredGlobal(McContent mcContent) throws McApplicationException; + + public int countIncompleteSession(McContent mc) throws McApplicationException; + + public boolean studentActivityOccurred(McContent mc) throws McApplicationException; + + public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException; + + public void setAsForceCompleteSession(Long toolSessionId) throws McApplicationException; + + public void setAsForceComplete(Long userId) throws McApplicationException; + + public void unsetAsDefineLater(Long toolContentId) throws McApplicationException; + + public void setAsDefineLater(Long toolContentId) throws DataMissingException, ToolException; + + public void setAsRunOffline(Long toolContentId) throws DataMissingException, ToolException; + + public void removeToolContent(Long toolContentId); + + public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, ToolException; + + public boolean existsSession(Long toolSessionId); + + public void createToolSession(Long toolSessionId, Long toolContentId) throws ToolException; + + public void removeToolSession(Long toolSessionId) throws DataMissingException, ToolException; + + public String leaveToolSession(Long toolSessionId,Long learnerId) throws DataMissingException, ToolException; + + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException; + + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, ToolException; + + public BasicToolVO getToolBySignature(String toolSignature) throws McApplicationException; + + public long getToolDefaultContentIdBySignature(String toolSignature) throws McApplicationException; + + public McQueContent getToolDefaultQuestionContent(long contentId) throws McApplicationException; + + public List getToolSessionsForContent(McContent mc); + + public ITicket getRepositoryLoginTicket() throws McApplicationException; + + public void deleteFromRepository(Long uuid, Long versionID); + + public NodeKey uploadFileToRepository(InputStream stream, String fileName) throws McApplicationException; + + public InputStream downloadFile(Long uuid, Long versionID) throws McApplicationException; + + public String getFileUuid(String filename) throws McApplicationException; + + public List retrieveMcUploadedOfflineFilesUuid(Long mcContentId) throws McApplicationException; + + public List retrieveMcUploadedOnlineFilesUuid(Long mcContentId) throws McApplicationException; + + public List retrieveMcUploadedOfflineFilesName(Long mcContentId) throws McApplicationException; + + public List retrieveMcUploadedOnlineFilesName(Long mcContentId) throws McApplicationException; + + public List retrieveMcUploadedFiles(Long mcContentId, boolean fileOnline) throws McApplicationException; + + public List retrieveMcUploadedOfflineFilesUuidPlusFilename(Long mcContentId) throws McApplicationException; + + public void cleanUploadedFilesMetaData() throws McApplicationException; + + public void persistFile(String uuid, boolean isOnlineFile, String fileName, McContent mcContent) throws McApplicationException; + + public List getHighestMark(Long queUsrId) throws McApplicationException; + + public List getHighestAttemptOrder(Long queUsrId) throws McApplicationException; + + public List getAttemptForQueContent(final Long queUsrId, final Long mcQueContentId) throws McApplicationException; + + public List getAttemptByAttemptOrder(final Long queUsrId, final Long mcQueContentId, final Integer attemptOrder) throws McApplicationException; + + public List getMarks() throws McApplicationException; + + public int countSessionComplete() throws McApplicationException; + + public int countSessionIncomplete() throws McApplicationException; + + public List getNextAvailableDisplayOrder(final long mcContentId) throws McApplicationException; +} + Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/service/McServicePOJO.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/service/McServicePOJO.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/service/McServicePOJO.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,2037 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.service; +import java.io.InputStream; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.TreeSet; + +import org.apache.log4j.Logger; +import org.lamsfoundation.lams.contentrepository.AccessDeniedException; +import org.lamsfoundation.lams.contentrepository.FileException; +import org.lamsfoundation.lams.contentrepository.ICredentials; +import org.lamsfoundation.lams.contentrepository.ITicket; +import org.lamsfoundation.lams.contentrepository.IVersionedNode; +import org.lamsfoundation.lams.contentrepository.ItemExistsException; +import org.lamsfoundation.lams.contentrepository.ItemNotFoundException; +import org.lamsfoundation.lams.contentrepository.LoginException; +import org.lamsfoundation.lams.contentrepository.NodeKey; +import org.lamsfoundation.lams.contentrepository.RepositoryCheckedException; +import org.lamsfoundation.lams.contentrepository.WorkspaceNotFoundException; +import org.lamsfoundation.lams.contentrepository.service.IRepositoryService; +import org.lamsfoundation.lams.contentrepository.service.RepositoryProxy; +import org.lamsfoundation.lams.contentrepository.service.SimpleCredentials; +import org.lamsfoundation.lams.lesson.Lesson; +import org.lamsfoundation.lams.tool.BasicToolVO; +import org.lamsfoundation.lams.tool.ToolContentManager; +import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; +import org.lamsfoundation.lams.tool.ToolSessionManager; +import org.lamsfoundation.lams.tool.exception.DataMissingException; +import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; +import org.lamsfoundation.lams.tool.exception.ToolException; +import org.lamsfoundation.lams.tool.mc.McAppConstants; +import org.lamsfoundation.lams.tool.mc.McApplicationException; +import org.lamsfoundation.lams.tool.mc.McContent; +import org.lamsfoundation.lams.tool.mc.McOptsContent; +import org.lamsfoundation.lams.tool.mc.McQueContent; +import org.lamsfoundation.lams.tool.mc.McQueUsr; +import org.lamsfoundation.lams.tool.mc.McSession; +import org.lamsfoundation.lams.tool.mc.McUploadedFile; +import org.lamsfoundation.lams.tool.mc.McUsrAttempt; +import org.lamsfoundation.lams.tool.mc.dao.IMcContentDAO; +import org.lamsfoundation.lams.tool.mc.dao.IMcOptionsContentDAO; +import org.lamsfoundation.lams.tool.mc.dao.IMcQueContentDAO; +import org.lamsfoundation.lams.tool.mc.dao.IMcSessionDAO; +import org.lamsfoundation.lams.tool.mc.dao.IMcUploadedFileDAO; +import org.lamsfoundation.lams.tool.mc.dao.IMcUserDAO; +import org.lamsfoundation.lams.tool.mc.dao.IMcUsrAttemptDAO; +import org.lamsfoundation.lams.tool.service.ILamsToolService; +import org.lamsfoundation.lams.usermanagement.User; +import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; +import org.springframework.dao.DataAccessException; + +/** + * + * @author Ozgur Demirtas + * + * The POJO implementation of Mc service. All business logics of MCQ tool + * are implemented in this class. It translate the request from presentation + * layer and perform appropriate database operation. + * + */ +public class McServicePOJO implements + IMcService, ToolContentManager, ToolSessionManager, McAppConstants + +{ + static Logger logger = Logger.getLogger(McServicePOJO.class.getName()); + + /*repository access related constants */ + private final String repositoryUser = "lamc11"; + private final char[] repositoryId = {'l','a','m','c','_','1', '1'}; + private final String repositoryWorkspace = "lamc11"; + private IRepositoryService repositoryService; + private ICredentials cred; + + private IMcContentDAO mcContentDAO; + private IMcQueContentDAO mcQueContentDAO; + private IMcOptionsContentDAO mcOptionsContentDAO; + private IMcSessionDAO mcSessionDAO; + private IMcUserDAO mcUserDAO; + private IMcUsrAttemptDAO mcUsrAttemptDAO; + private IMcUploadedFileDAO mcUploadedFileDAO; + + private IUserManagementService userManagementService; + private ILamsToolService toolService; + + public McServicePOJO(){} + + public void configureContentRepository() throws McApplicationException { + logger.debug("retrieved repService: " + repositoryService); + cred = new SimpleCredentials(repositoryUser, repositoryId); + logger.debug("retrieved cred: "+ cred); + try + { + repositoryService.createCredentials(cred); + logger.debug("created credentails."); + repositoryService.addWorkspace(cred,repositoryWorkspace); + logger.debug("created workspace."); + } catch (ItemExistsException ie) { + logger.warn("Tried to configure repository but it " + +" appears to be already configured. Exception thrown by repository being ignored. ", ie); + } catch (RepositoryCheckedException e) { + String error = "Error occured while trying to configure repository." + +" Unable to recover from error: "+e.getMessage(); + logger.error(error, e); + throw new McApplicationException(error,e); + } + } + + + public void createMc(McContent mcContent) throws McApplicationException + { + try + { + mcContentDAO.saveMcContent(mcContent); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is loading mc content: " + + e.getMessage(), + e); + } + } + + + public McContent retrieveMc(Long toolContentId) throws McApplicationException + { + try + { + return mcContentDAO.findMcContentById(toolContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is loading mc content: " + + e.getMessage(), + e); + } + } + + + public void createMcQue(McQueContent mcQueContent) throws McApplicationException + { + try + { + mcQueContentDAO.saveMcQueContent(mcQueContent); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is creating mc que content: " + + e.getMessage(), + e); + } + } + + public McQueContent getQuestionContentByDisplayOrder(final Long displayOrder, final Long mcContentUid) throws McApplicationException + { + try + { + return mcQueContentDAO.getQuestionContentByDisplayOrder(displayOrder, mcContentUid); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is getting mc que content by display order: " + + e.getMessage(), + e); + } + } + + + public McQueContent getMcQueContentByUID(Long uid) throws McApplicationException + { + try + { + return mcQueContentDAO.getMcQueContentByUID(uid); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is getting mc que content by uid: " + + e.getMessage(), + e); + } + } + + + public void saveOrUpdateMcQueContent(McQueContent mcQueContent) throws McApplicationException + { + try + { + mcQueContentDAO.saveOrUpdateMcQueContent(mcQueContent); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is updating mc que content: " + + e.getMessage(), + e); + } + } + + + public void removeQuestionContentByMcUid(final Long mcContentUid) throws McApplicationException + { + try + { + mcQueContentDAO.removeQuestionContentByMcUid(mcContentUid); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is removing mc que content by mc content id: " + + e.getMessage(), + e); + } + } + + public void resetAllQuestions(final Long mcContentUid) throws McApplicationException + { + try + { + mcQueContentDAO.resetAllQuestions(mcContentUid); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is resetting all questions: " + + e.getMessage(), + e); + } + } + + + + public void cleanAllQuestions(final Long mcContentUid) throws McApplicationException + { + try + { + mcQueContentDAO.cleanAllQuestions(mcContentUid); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is cleaning all questions: " + + e.getMessage(), + e); + } + } + + + public List getNextAvailableDisplayOrder(final long mcContentId) throws McApplicationException + { + try + { + return mcQueContentDAO.getNextAvailableDisplayOrder(mcContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is getting the next available display order: " + + e.getMessage(), + e); + } + } + + + public void createMcSession(McSession mcSession) throws McApplicationException + { + try + { + mcSessionDAO.saveMcSession(mcSession); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is creating mc session: " + + e.getMessage(), + e); + } + } + + public void createMcQueUsr(McQueUsr mcQueUsr) throws McApplicationException + { + try + { + mcUserDAO.saveMcUser(mcQueUsr); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is creating mc QueUsr: " + + e.getMessage(), + e); + } + } + + + + public McQueUsr retrieveMcQueUsr(Long userId) throws McApplicationException + { + try + { + McQueUsr mcQueUsr=mcUserDAO.findMcUserById(userId); + return mcQueUsr; + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is retrieving McQueUsr: " + + e.getMessage(), + e); + } + } + + + public void createMcUsrAttempt(McUsrAttempt mcUsrAttempt) throws McApplicationException + { + try + { + mcUsrAttemptDAO.saveMcUsrAttempt(mcUsrAttempt); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is creating mc UsrAttempt: " + + e.getMessage(), + e); + } + } + + + public void updateMcUsrAttempt(McUsrAttempt mcUsrAttempt) throws McApplicationException + { + try + { + mcUsrAttemptDAO.updateMcUsrAttempt(mcUsrAttempt); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is updating mc UsrAttempt: " + + e.getMessage(), + e); + } + } + + + public List getHighestMark(Long queUsrId) throws McApplicationException + { + try + { + return mcUsrAttemptDAO.getHighestMark(queUsrId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is getting the learner's highest mark: " + + e.getMessage(), + e); + } + } + + + public List getHighestAttemptOrder(Long queUsrId) throws McApplicationException + { + try + { + return mcUsrAttemptDAO.getHighestAttemptOrder(queUsrId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is getting the learner's highest attempt order: " + + e.getMessage(), + e); + } + } + + + public List getAttemptForQueContent(final Long queUsrId, final Long mcQueContentId) throws McApplicationException + { + try + { + return mcUsrAttemptDAO.getAttemptForQueContent(queUsrId, mcQueContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is getting the learner's attempts by user id and que content id: " + + e.getMessage(), + e); + } + } + + + public List getAttemptByAttemptOrder(final Long queUsrId, final Long mcQueContentId, final Integer attemptOrder) throws McApplicationException + { + try + { + return mcUsrAttemptDAO.getAttemptByAttemptOrder(queUsrId, mcQueContentId, attemptOrder); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is getting the learner's attempts by user id and que content id and attempt order: " + + e.getMessage(), + e); + } + } + + + public McQueContent retrieveMcQueContentByUID(Long uid) throws McApplicationException + { + try + { + return mcQueContentDAO.getMcQueContentByUID(uid); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is retrieving by uid mc question content: " + + e.getMessage(), + e); + } + } + + + public void cleanAllQuestionsSimple(final Long mcContentId) throws McApplicationException + { + try + { + mcQueContentDAO.cleanAllQuestionsSimple(mcContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is cleaning mc question content by mcContentId : " + + e.getMessage(), + e); + } + } + + public List getAllQuestionEntries(final Long uid) throws McApplicationException + { + try + { + return mcQueContentDAO.getAllQuestionEntries(uid.longValue()); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is getting by uid mc question content: " + + e.getMessage(), + e); + } + } + + + public void removeMcQueContentByUID(Long uid) throws McApplicationException + { + try + { + mcQueContentDAO.removeMcQueContentByUID(uid); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is removing by uid mc question content: " + + e.getMessage(), + e); + } + } + + + public List refreshQuestionContent(final Long mcContentId) throws McApplicationException + { + try + { + return mcQueContentDAO.refreshQuestionContent(mcContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is refreshing mc question content: " + + e.getMessage(), + e); + } + + } + + public void removeMcQueContent(McQueContent mcQueContent) throws McApplicationException + { + try + { + mcQueContentDAO.removeMcQueContent(mcQueContent); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is removing mc question content: " + + e.getMessage(), + e); + } + } + + public void removeMcOptionsContent(McOptsContent mcOptsContent) throws McApplicationException + { + try + { + mcOptionsContentDAO.removeMcOptionsContent(mcOptsContent); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is removing" + + " the mc options content: " + + e.getMessage(),e); + } + } + + public List getPersistedSelectedOptions(Long mcQueContentId) throws McApplicationException + { + try + { + return mcOptionsContentDAO.getPersistedSelectedOptions(mcQueContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is gettong persisted selected" + + " the mc options content: " + + e.getMessage(),e); + } + + } + + + + public McQueContent getQuestionContentByQuestionText(final String question, final Long mcContentId) + { + try + { + return mcQueContentDAO.getQuestionContentByQuestionText(question, mcContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is retrieving question content by question text: " + + e.getMessage(), + e); + } + } + + + public McSession retrieveMcSession(Long mcSessionId) throws McApplicationException + { + try + { + return mcSessionDAO.findMcSessionById(mcSessionId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is retrieving by id mc session : " + + e.getMessage(), + e); + } + } + + + + public McContent retrieveMcBySessionId(Long mcSessionId) throws McApplicationException + { + try + { + return mcContentDAO.getMcContentBySession(mcSessionId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is retrieving mc by session id: " + + e.getMessage(), + e); + } + } + + + public void updateMc(McContent mc) throws McApplicationException + { + try + { + mcContentDAO.updateMcContent(mc); + } + catch(DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is updating" + + " the mc content: " + + e.getMessage(),e); + } + } + + + public void updateMcSession(McSession mcSession) throws McApplicationException + { + try + { + mcSessionDAO.updateMcSession(mcSession); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is updating mc session : " + + e.getMessage(), + e); + } + } + + public void deleteMc(McContent mc) throws McApplicationException + { + try + { + mcContentDAO.removeMc(mc); + } + catch(DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is removing" + + " the mc content: " + + e.getMessage(),e); + } + } + + public void deleteMcById(Long mcId) throws McApplicationException + { + try + { + mcContentDAO.removeMcById(mcId); + } + catch(DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is removing by id" + + " the mc content: " + + e.getMessage(),e); + } + } + + public int countSessionComplete() throws McApplicationException + { + try + { + return mcSessionDAO.countSessionComplete(); + } + catch(DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is counting incomplete sessions" + + e.getMessage(),e); + } + } + + public int countSessionIncomplete() throws McApplicationException + { + try + { + return mcSessionDAO.countSessionIncomplete(); + } + catch(DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is counting incomplete sessions" + + e.getMessage(),e); + } + } + + public void deleteMcSession(McSession mcSession) throws McApplicationException + { + try + { + mcSessionDAO.removeMcSession(mcSession); + } + catch(DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is deleting" + + " the mc session: " + + e.getMessage(),e); + } + } + + + public void removeAttempt (McUsrAttempt attempt) throws McApplicationException + { + try + { + mcUsrAttemptDAO.removeMcUsrAttempt(attempt); + } + catch(DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is removing" + + " the attempt: " + + e.getMessage(),e); + } + } + + + public List getMarks() throws McApplicationException + { + try + { + return mcUsrAttemptDAO.getMarks(); + } + catch(DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is getting marks " + + e.getMessage(),e); + } + } + + public void deleteMcQueUsr(McQueUsr mcQueUsr) throws McApplicationException + { + try + { + mcUserDAO.removeMcUser(mcQueUsr); + } + catch(DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is removing" + + " the user: " + + e.getMessage(),e); + } + } + + + public void saveMcContent(McContent mc) throws McApplicationException + { + try + { + mcContentDAO.saveMcContent(mc); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is saving" + + " the mc content: " + + e.getMessage(),e); + } + } + + + public List findMcOptionsContentByQueId(Long mcQueContentId) throws McApplicationException + { + try + { + List list=mcOptionsContentDAO.findMcOptionsContentByQueId(mcQueContentId); + return list; + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is finding by que id" + + " the mc options: " + + e.getMessage(),e); + } + } + + + public McOptsContent getMcOptionsContentByUID(Long uid) throws McApplicationException + { + try + { + return getMcOptionsContentByUID(uid); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is getting opt content by uid" + + e.getMessage(),e); + } + } + + + public void saveMcOptionsContent(McOptsContent mcOptsContent) throws McApplicationException + { + try + { + mcOptionsContentDAO.saveMcOptionsContent(mcOptsContent); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is saving" + + " the mc options content: " + + e.getMessage(),e); + } + } + + public McOptsContent getOptionContentByOptionText(final String option, final Long mcQueContentUid) + { + try + { + return mcOptionsContentDAO.getOptionContentByOptionText(option, mcQueContentUid); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is returning the" + + " option by option text: " + + e.getMessage(),e); + } + } + + + public List getCorrectOption(Long mcQueContentId) + { + try + { + return mcOptionsContentDAO.getCorrectOption(mcQueContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is returning the " + + " correct option: " + + e.getMessage(),e); + } + } + + public void updateMcOptionsContent(McOptsContent mcOptsContent) throws McApplicationException + { + try + { + mcOptionsContentDAO.updateMcOptionsContent(mcOptsContent); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is updating" + + " the mc options content: " + + e.getMessage(),e); + } + } + + + public void deleteMcOptionsContent(McOptsContent mcOptsContent) throws McApplicationException + { + try + { + mcOptionsContentDAO.removeMcOptionsContent(mcOptsContent); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is removing" + + " the mc options content: " + + e.getMessage(),e); + } + } + + + public void removeMcOptionsContentByQueId(Long mcQueContentId) throws McApplicationException + { + try + { + mcOptionsContentDAO.removeMcOptionsContentByQueId(mcQueContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is removing by que id" + + " the mc options content: " + + e.getMessage(),e); + } + } + + + public void deleteMcOptionsContentByUID(Long uid) throws McApplicationException + { + try + { + mcOptionsContentDAO.removeMcOptionsContentByUID(uid); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is removing by uid" + + " the mc options content: " + + e.getMessage(),e); + } + } + + + public User getCurrentUserData(String username) throws McApplicationException + { + try + { + logger.debug("getCurrentUserData: " + username); + /** + * this will return null if the username not found + */ + User user=userManagementService.getUserByLogin(username); + if (user == null) + { + logger.debug("No user with the username: "+ username + " exists."); + throw new McApplicationException("No user with that username exists."); + } + return user; + } + catch (DataAccessException e) + { + throw new McApplicationException("Unable to find current user information" + + " Root Cause: [" + + e.getMessage() + "]", + e); + } + } + + /** + * + * Unused method + * @param lessonId + * @return + * @throws McApplicationException + */ + public Lesson getCurrentLesson(long lessonId) throws McApplicationException + { + try + { + /**this is a mock implementation to make the project compile and + work. When the Lesson service is ready, we need to switch to + real service implementation. + */ + return new Lesson(); + /**return lsDAO.find(lsessionId); */ + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is loading" + + " learning session:" + + e.getMessage(), + e); + } + } + + + /** + * checks the paramter content in the user responses table + * @param qa + * @return + * @throws McApplicationException + */ + public boolean studentActivityOccurredGlobal(McContent mcContent) throws McApplicationException + { + Iterator questionIterator=mcContent.getMcQueContents().iterator(); + while (questionIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)questionIterator.next(); + Iterator attemptsIterator=mcQueContent.getMcUsrAttempts().iterator(); + while (attemptsIterator.hasNext()) + { + logger.debug("there is at least one attempt"); + /** + * proved the fact that there is at least one attempt for this content. + */ + return true; + } + } + logger.debug("there is no response for this content"); + return false; + } + + + public int countIncompleteSession(McContent mc) throws McApplicationException + { + //int countIncompleteSession=mcSessionDAO.countIncompleteSession(mc); + int countIncompleteSession=2; + return countIncompleteSession; + } + + /** + * checks the parameter content in the tool sessions table + * + * find out if any student has ever used (logged in through the url and replied) to this content + * return true even if you have only one content passed as parameter referenced in the tool sessions table + * @param qa + * @return boolean + * @throws McApplicationException + */ + public boolean studentActivityOccurred(McContent mc) throws McApplicationException + { + //int countStudentActivity=mcSessionDAO.studentActivityOccurred(mc); + int countStudentActivity=2; + + if (countStudentActivity > 0) + return true; + return false; + } + + + /** + * + * gets called ONLY when a lesson is being created in monitoring mode. + * Should create the new content(toContent) based on what the author has created her content with. In q/a tool's case + * that is content + question's content but not user responses. The deep copy should go only as far as + * default content (or author created content) already goes. + * ToolContentManager CONTRACT + * + * + * similar to public void removeToolContent(Long toolContentId) + * gets called by Container+Flash + * + */ + + public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException + { + logger.debug("start of copyToolContent with ids: " + fromContentId + " and " + toContentId); + + if (fromContentId == null) + { + logger.debug("fromContentId is null."); + logger.debug("attempt retrieving tool's default content id with signatute : " + MY_SIGNATURE); + long defaultContentId=0; + try + { + defaultContentId=getToolDefaultContentIdBySignature(MY_SIGNATURE); + fromContentId= new Long(defaultContentId); + } + catch(Exception e) + { + logger.debug("default content id has not been setup for signature: " + MY_SIGNATURE); + throw new ToolException("WARNING! default content has not been setup for signature" + MY_SIGNATURE + " Can't continue!"); + } + } + + if (toContentId == null) + { + logger.debug("throwing ToolException: toContentId is null"); + throw new ToolException("toContentId is missing"); + } + logger.debug("final - copyToolContent using ids: " + fromContentId + " and " + toContentId); + + try + { + McContent fromContent = mcContentDAO.findMcContentById(fromContentId); + + if (fromContent == null) + { + logger.debug("fromContent is null."); + logger.debug("attempt retrieving tool's default content id with signatute : " + MY_SIGNATURE); + long defaultContentId=0; + try + { + defaultContentId=getToolDefaultContentIdBySignature(MY_SIGNATURE); + fromContentId= new Long(defaultContentId); + } + catch(Exception e) + { + logger.debug("default content id has not been setup for signature: " + MY_SIGNATURE); + throw new ToolException("WARNING! default content has not been setup for signature" + MY_SIGNATURE + " Can't continue!"); + } + + fromContent = mcContentDAO.findMcContentById(fromContentId); + logger.debug("using fromContent: " + fromContent); + } + + logger.debug("final - retrieved fromContent: " + fromContent); + logger.debug("final - before new instance using " + fromContent + " and " + toContentId); + McContent toContent = McContent.newInstance(fromContent,toContentId); + if (toContent == null) + { + logger.debug("throwing ToolException: WARNING!, retrieved toContent is null."); + throw new ToolException("WARNING! Fail to create toContent. Can't continue!"); + } + else + { + logger.debug("retrieved toContent: " + toContent); + mcContentDAO.saveMcContent(toContent); + logger.debug("toContent has been saved successfully: " + toContent); + } + logger.debug("end of copyToolContent with ids: " + fromContentId + " and " + toContentId); + } + catch (DataAccessException e) + { + logger.debug("throwing ToolException: Exception occured when lams is copying content between content ids."); + throw new ToolException("Exception occured when lams is copying content between content ids."); + } + } + + + + /** + * TO BE DEFINED-FUTURE API + * gets called from monitoring module + * + * update the tool session status to COMPLETE for this tool session + * + * @param Long toolSessionId + */ + public void setAsForceCompleteSession(Long toolSessionId) throws McApplicationException + { + McSession mcSession=retrieveMcSession(toolSessionId); + mcSession.setSessionStatus(McSession.COMPLETED); + updateMcSession(mcSession); + } + + + /** + * TO BE DEFINED + * + * update the tool session status to COMPLETE for this user + * IMPLEMENT THIS!!!! Is this from ToolContentManager??? + * + + * @param userId + */ + public void setAsForceComplete(Long userId) throws McApplicationException + { + McQueUsr mcQueUsr=retrieveMcQueUsr(userId); + + if (mcQueUsr != null) + { + logger.debug("retrieved mcQueUsr : " + mcQueUsr); + logger.debug("retrieved mcQueUsr has the tool session : " + mcQueUsr.getMcSession()); + McSession mcSession=mcQueUsr.getMcSession(); + if (mcSession != null) + { + Long usersToolSessionId=mcSession.getMcSessionId(); + logger.debug("retrieved tool session has tool session id : " + usersToolSessionId); + + mcSession=retrieveMcSession(usersToolSessionId); + logger.debug("retrieved mcSession is : " + mcSession); + mcSession.setSessionStatus(McSession.COMPLETED); + logger.debug("updated mcSession to COMPLETED : "); + updateMcSession(mcSession); + logger.debug("updated mcSession to COMPLETED in the db : "); + + McContent mcContent=mcSession.getMcContent(); + logger.debug("mcSession uses qaContent : " + mcContent); + logger.debug("mcSession uses qaContentId : " + mcContent.getMcContentId()); + + /** + * if all the sessions of this content is COMPLETED, unlock the content + * + */ + int countIncompleteSession=countIncompleteSession(mcContent); + logger.debug("mcSession countIncompleteSession : " + countIncompleteSession); + + if (countIncompleteSession == 0) + { + mcContent.setContentInUse(false); + updateMc(mcContent); + logger.debug("qaContent has been updated for contentInUse" + mcContent); + } + } + else + { + logger.debug("WARNING!: retrieved mcSession is null."); + throw new McApplicationException("Fail to setAsForceComplete" + + " based on null mcSession."); + } + } + else + { + logger.debug("WARNING!: retrieved qaQueUsr is null."); + throw new McApplicationException("Fail to setAsForceComplete" + + " based on null qaQueUsr."); + } + } + + public void unsetAsDefineLater(Long toolContentId) throws McApplicationException + { + logger.debug("request for unsetAsDefineLater with toolContentId: " + toolContentId); + if (toolContentId == null) + { + logger.debug("WARNING!: retrieved toolContentId is null."); + throw new McApplicationException("Fail to setAsDefineLater" + + " based on null toolContentId."); + } + McContent mcContent = mcContentDAO.findMcContentById(toolContentId); + if (mcContent == null) + { + logger.debug("WARNING!!!: retrieved mcContent is null."); + throw new McApplicationException("Fail to unsetAsDefineLater" + + " based on null mcContent."); + } + mcContent.setDefineLater(false); + updateMc(mcContent); + logger.debug("qaContent has been updated for unsetAsDefineLater: " + mcContent); + } + + /** + * + * set the defineLater to true on this content + * + * @param toolContentId + * return void + */ + public void setAsDefineLater(Long toolContentId) throws DataMissingException, ToolException + { + logger.debug("request for setAsDefineLater with toolContentId: " + toolContentId); + if (toolContentId == null) + { + logger.debug("throwing DataMissingException: WARNING!: retrieved toolContentId is null."); + throw new DataMissingException("toolContentId is missing"); + } + + McContent mcContent = mcContentDAO.findMcContentById(toolContentId); + if (mcContent == null) + { + logger.debug("throwing DataMissingException: WARNING!: retrieved mcContent is null."); + throw new DataMissingException("mcContent is missing"); + } + mcContent.setDefineLater(true); + updateMc(mcContent); + logger.debug("mcContent has been updated for defineLater: " + mcContent); + } + + /** + * + * set the runOffline to true on this content + * + * @param toolContentId + * return void + */ + public void setAsRunOffline(Long toolContentId) throws DataMissingException, ToolException + { + logger.debug("request for setAsRunOffline with toolContentId:" + toolContentId); + if (toolContentId == null) + { + logger.debug("throwing DataMissingException: WARNING!: retrieved toolContentId is null."); + throw new DataMissingException("toolContentId is missing"); + } + McContent mcContent = mcContentDAO.findMcContentById(toolContentId); + if (mcContent == null) + { + logger.debug("throwing DataMissingException: WARNING!: retrieved mcContent is null."); + throw new DataMissingException("mcContent is missing"); + } + mcContent.setRunOffline(true); + updateMc(mcContent); + logger.debug("qaContent has been updated for runOffline: " + mcContent); + } + + + + /** + * !!! UNUSED !!! + * + * gets automatically called only in monitoring mode when the author chooses to delete a lesson. + * + * The idea is to remove content + its relevant sessions + in q/a tools's case the question's content from the db. + * ToolContentManager CONTRACT + * this gets called automatically by Flash when a deletion is detected in the tool interface. + */ + public void removeToolContent(Long toolContentId) + { + logger.debug("start of removeToolContent with toolContentId: " + toolContentId); + + McContent mcContent = mcContentDAO.findMcContentById(toolContentId); + logger.debug("retrieving mcContent: " + mcContent); + + if (mcContent != null) + { + Iterator sessionIterator=mcContent.getMcSessions().iterator(); + while (sessionIterator.hasNext()) + { + McSession mcSession=(McSession)sessionIterator.next(); + logger.debug("iterated mcSession : " + mcSession); + + Iterator sessionUsersIterator=mcSession.getMcQueUsers().iterator(); + while (sessionUsersIterator.hasNext()) + { + McQueUsr mcQueUsr=(McQueUsr) sessionUsersIterator.next(); + logger.debug("iterated mcQueUsr : " + mcQueUsr); + + Iterator sessionUsersAttemptsIterator=mcQueUsr.getMcUsrAttempts().iterator(); + while (sessionUsersAttemptsIterator.hasNext()) + { + McUsrAttempt mcUsrAttempt=(McUsrAttempt)sessionUsersAttemptsIterator.next(); + logger.debug("iterated mcUsrAttempt : " + mcUsrAttempt); + removeAttempt(mcUsrAttempt); + logger.debug("removed qaUsrAttempt : " + mcUsrAttempt); + } + } + } + + logger.debug("removed all existing responses of toolContent with toolContentId:" + + toolContentId); + mcContentDAO.removeMcById(toolContentId); + logger.debug("removed qaContent:" + mcContent); + } + } + + + /* + * + * Will need an update on the core tool signature: reason : when mcContent is null throw an exception + * (non-Javadoc) + * @see org.lamsfoundation.lams.tool.ToolContentManager#removeToolContent(java.lang.Long, boolean) + */ + public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, ToolException + { + logger.debug("start of: removeToolContent(Long toolContentId, boolean removeSessionData"); + logger.debug("start of removeToolContent with toolContentId: " + toolContentId + "removeSessionData: " + removeSessionData); + + if (toolContentId == null) + { + logger.debug("toolContentId is null"); + throw new ToolException("toolContentId is missing"); + } + + McContent mcContent = mcContentDAO.findMcContentById(toolContentId); + logger.debug("retrieving mcContent: " + mcContent); + + if (mcContent != null) + { + Iterator sessionIterator=mcContent.getMcSessions().iterator(); + while (sessionIterator.hasNext()) + { + if (removeSessionData == false) + { + logger.debug("removeSessionData is false, throwing SessionDataExistsException."); + throw new SessionDataExistsException(); + } + + McSession mcSession=(McSession)sessionIterator.next(); + logger.debug("iterated mcSession : " + mcSession); + + Iterator sessionUsersIterator=mcSession.getMcQueUsers().iterator(); + while (sessionUsersIterator.hasNext()) + { + McQueUsr mcQueUsr=(McQueUsr) sessionUsersIterator.next(); + logger.debug("iterated mcQueUsr : " + mcQueUsr); + + Iterator sessionUsersAttemptsIterator=mcQueUsr.getMcUsrAttempts().iterator(); + while (sessionUsersAttemptsIterator.hasNext()) + { + McUsrAttempt mcUsrAttempt=(McUsrAttempt)sessionUsersAttemptsIterator.next(); + logger.debug("iterated mcUsrAttempt : " + mcUsrAttempt); + removeAttempt(mcUsrAttempt); + logger.debug("removed mcUsrAttempt : " + mcUsrAttempt); + } + } + } + + logger.debug("removed all existing responses of toolContent with toolContentId:" + + toolContentId); + mcContentDAO.removeMcById(toolContentId); + logger.debug("removed qaContent:" + mcContent); + } + else + { + logger.debug("Warning!!!, We should have not come here. mcContent is null."); + throw new ToolException("toolContentId is missing"); + } + } + + + /** + * it is possible that the tool session id already exists in the tool sessions table + * as the users from the same session are involved. + * existsSession(long toolSessionId) + * @param toolSessionId + * @return boolean + */ + public boolean existsSession(Long toolSessionId) + { + McSession mcSession= retrieveMcSession(toolSessionId); + + if (mcSession == null) + { + logger.debug("mcSession does not exist yet: " + toolSessionId); + return false; + } + else + { + logger.debug("retrieving an existing mcSession: " + mcSession + " " + toolSessionId); + } + return true; + } + + /** + * + * ToolSessionManager CONTRACT : creates a tool session with the incoming toolSessionId in the tool session table + * + * gets called only in the Learner mode. + * All the learners in the same group have the same toolSessionId. + * + */ + public void createToolSession(Long toolSessionId, Long toolContentId) throws ToolException + { + logger.debug("start of createToolSession with ids: " + toolSessionId + " and " + toolContentId); + if (toolSessionId == null) + { + logger.debug("toolSessionId is null"); + throw new ToolException("toolSessionId is missing"); + } + + long defaultContentId=0; + if (toolContentId == null) + { + logger.debug("toolContentId is null."); + logger.debug("attempt retrieving tool's default content id with signatute : " + MY_SIGNATURE); + + try + { + defaultContentId=getToolDefaultContentIdBySignature(MY_SIGNATURE); + toolContentId=new Long(defaultContentId); + logger.debug("updated toolContentId to: " + toolContentId); + } + catch(Exception e) + { + logger.debug("default content id has not been setup for signature: " + MY_SIGNATURE); + throw new ToolException("WARNING! default content has not been setup for signature" + MY_SIGNATURE + " Can't continue!"); + } + } + logger.debug("final toolSessionId and toolContentId: " + toolSessionId + " " + toolContentId); + + McContent mcContent = mcContentDAO.findMcContentById(toolContentId); + logger.debug("retrieved mcContent: " + mcContent); + + if (mcContent == null) + { + logger.debug("mcContent is null."); + logger.debug("attempt retrieving tool's default content id with signatute : " + MY_SIGNATURE); + + try + { + defaultContentId=getToolDefaultContentIdBySignature(MY_SIGNATURE); + toolContentId=new Long(defaultContentId); + logger.debug("updated toolContentId to: " + toolContentId); + } + catch(Exception e) + { + logger.debug("default content id has not been setup for signature: " + MY_SIGNATURE); + throw new ToolException("WARNING! default content has not been setup for signature" + MY_SIGNATURE + " Can't continue!"); + } + + mcContent = mcContentDAO.findMcContentById(toolContentId); + } + logger.debug("final - retrieved mcContent: " + mcContent); + + + /** + * create a new a new tool session if it does not already exist in the tool session table + */ + if (!existsSession(toolSessionId)) + { + + try + { + McSession mcSession = new McSession(toolSessionId, + new Date(System.currentTimeMillis()), + McSession.INCOMPLETE, + mcContent, + new TreeSet()); + + logger.debug("created mcSession: " + mcSession); + mcSessionDAO.saveMcSession(mcSession); + logger.debug("created mcSession in the db: " + mcSession); + + } + catch(Exception e) + { + logger.debug("Error creating new toolsession in the db"); + throw new ToolException("Error creating new toolsession in the db: " + e); + } + } + } + + + public void removeToolSession(Long toolSessionId) throws DataMissingException, ToolException + { + logger.debug("start of removeToolSession with id: " + toolSessionId); + if (toolSessionId == null) + { + logger.debug("toolSessionId is null"); + throw new DataMissingException("toolSessionId is missing"); + } + + + McSession mcSession=null; + try + { + mcSession=retrieveMcSession(toolSessionId); + logger.debug("retrieved qaSession: " + mcSession); + } + catch(McApplicationException e) + { + throw new DataMissingException("error retrieving mcSession: " + e); + } + catch(Exception e) + { + throw new ToolException("error retrieving qaSession: " + e); + } + + if (mcSession == null) + { + logger.debug("mcSession is null"); + throw new DataMissingException("mcSession is missing"); + } + + try + { + mcSessionDAO.removeMcSession(mcSession); + logger.debug("mcSession " + mcSession + " has been deleted successfully."); + } + catch(McApplicationException e) + { + throw new ToolException("error deleting qaSession:" + e); + } + } + + + /**FIX THIS ONE!!!! + * TO BE TESTED + * ToolSessionManager CONTRACT + * gets called only in the Learner mode. + * + * Call controller service to complete the qa session + * @see org.lamsfoundation.lams.tool.ToolSessionManager#leaveToolSession(java.lang.Long) + */ + public String leaveToolSession(Long toolSessionId,User user) throws DataMissingException, ToolException + { + logger.debug("start of leaveToolSession with toolSessionId:" + toolSessionId); + //logger.debug("start of leaveToolSession with learner:" + learnerId); + + if (toolSessionId == null) + { + logger.debug("toolSessionId is null"); + throw new DataMissingException("toolSessionId is missing"); + } + + /* + if (learnerId == null) + { + logger.debug("learnerId is null"); + throw new DataMissingException("learnerId is missing"); + } + */ + + try + { + /* + String nextUrl=learnerService.completeToolSession(toolSessionId,learner); + logger.debug(logger + " " + this.getClass().getName() + " " + "nextUrl: " + nextUrl); + return nextUrl; + */ + return "nextUrl"; + } + catch(DataAccessException e) + { + throw new ToolException("Exception occured when user is leaving tool session: " + e); + } + + } + + + public String leaveToolSession(Long toolSessionId,Long learnerId) throws DataMissingException, ToolException + { + logger.debug("start of leaveToolSession with toolSessionId:" + toolSessionId); + logger.debug("start of leaveToolSession with learner:" + learnerId); + + if (toolSessionId == null) + { + logger.debug("toolSessionId is null"); + throw new DataMissingException("toolSessionId is missing"); + } + + + if (learnerId == null) + { + logger.debug("learnerId is null"); + throw new DataMissingException("learnerId is missing"); + } + + + try + { + /* + String nextUrl=learnerService.completeToolSession(toolSessionId,learner); + logger.debug(logger + " " + this.getClass().getName() + " " + "nextUrl: " + nextUrl); + return nextUrl; + */ + return "nextUrl"; + } + catch(DataAccessException e) + { + throw new ToolException("Exception occured when user is leaving tool session: " + e); + } + + } + + /** + * ToolSessionManager CONTRACT + * + */ + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException + { + throw new ToolException("not yet implemented"); + } + + /** + * ToolSessionManager CONTRACT + * + */ + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, ToolException + { + + throw new ToolException("not yet implemented"); + } + + public BasicToolVO getToolBySignature(String toolSignature) throws McApplicationException + { + logger.debug("attempt retrieving tool with signature : " + toolSignature); + BasicToolVO tool=toolService.getToolBySignature(toolSignature); + logger.debug("retrieved tool: " + tool); + return tool; + } + + public long getToolDefaultContentIdBySignature(String toolSignature) throws McApplicationException + { + long contentId=0; + contentId=toolService.getToolDefaultContentIdBySignature(toolSignature); + logger.debug("tool default contentId : " + contentId); + return contentId; + } + + public McQueContent getToolDefaultQuestionContent(long contentId) throws McApplicationException + { + McQueContent mcQueContent=mcQueContentDAO.getToolDefaultQuestionContent(contentId); + logger.debug("retrieved mcQueContent : " + mcQueContent); + return mcQueContent; + } + + + public List getToolSessionsForContent(McContent mc) + { + logger.debug("attempt retrieving listToolSessionIds for : " + mc); + List listToolSessionIds=mcSessionDAO.getSessionsFromContent(mc); + return listToolSessionIds; + } + + + + /** + * This method verifies the credentials of the SubmitFiles Tool and gives it + * the Ticket to login and access the Content Repository. + * + * A valid ticket is needed in order to access the content from the + * repository. This method would be called evertime the tool needs to + * upload/download files from the content repository. + * + * @return ITicket The ticket for repostory access + * @throws SubmitFilesException + */ + public ITicket getRepositoryLoginTicket() throws McApplicationException { + repositoryService = RepositoryProxy.getRepositoryService(); + logger.debug("retrieved repositoryService : " + repositoryService); + + ICredentials credentials = new SimpleCredentials( + repositoryUser, + repositoryId); + try { + ITicket ticket = repositoryService.login(credentials, + repositoryWorkspace); + logger.debug("retrieved ticket: " + ticket); + return ticket; + } catch (AccessDeniedException e) { + throw new McApplicationException("Access Denied to repository." + + e.getMessage()); + } catch (WorkspaceNotFoundException e) { + throw new McApplicationException("Workspace not found." + + e.getMessage()); + } catch (LoginException e) { + throw new McApplicationException("Login failed." + e.getMessage()); + } + } + + + /** + * This method deletes the content with the given uuid and + * versionID from the content repository + * + * @param uuid + * The uuid of the node to be deleted + * @param versionID + * The version_id of the node to be deleted. + * @throws SubmitFilesException + */ + public void deleteFromRepository(Long uuid, Long versionID) + throws McApplicationException { + ITicket ticket = getRepositoryLoginTicket(); + logger.debug("retrieved ticket: " + ticket); + try { + String files[] = repositoryService.deleteVersion(ticket, uuid,versionID); + logger.debug("retrieved files: " + files); + } catch (Exception e) { + throw new McApplicationException( + "Exception occured while deleting files from" + + " the repository " + e.getMessage()); + } + } + + + /** + * This method is called everytime a new content has to be added to the + * repository. In order to do so first of all a valid ticket is obtained + * from the Repository hence authenticating the tool(SubmitFiles) and then + * the corresponding file is added to the repository. + * + * @param stream + * The InputStream representing the data to be + * added + * @param fileName + * The name of the file being added + * @param mimeType + * The MIME type of the file (eg. TXT, DOC, GIF etc) + * @return NodeKey Represents the two part key - UUID and Version. + * @throws SubmitFilesException + */ + public NodeKey uploadFileToRepository(InputStream stream, String fileName) throws McApplicationException { + logger.debug("attempt getting the ticket"); + ITicket ticket = getRepositoryLoginTicket(); + logger.debug("retrieved ticket: " + ticket); + + try { + NodeKey nodeKey = repositoryService.addFileItem(ticket, stream, + fileName, null, null); + logger.debug("retrieved nodeKey from repository service: " + nodeKey); + return nodeKey; + } catch (Exception e) { + throw new McApplicationException("Exception occured while trying to" + + " upload file into the repository" + e.getMessage()); + } + } + + public InputStream downloadFile(Long uuid, Long versionID)throws McApplicationException{ + ITicket ticket = getRepositoryLoginTicket(); + try{ + IVersionedNode node = repositoryService.getFileItem(ticket,uuid,null); + logger.debug("retrieved node: " + node); + return node.getFile(); + }catch(AccessDeniedException e){ + throw new McApplicationException("AccessDeniedException occured while trying to download file " + e.getMessage()); + }catch(FileException e){ + throw new McApplicationException("FileException occured while trying to download file " + e.getMessage()); + }catch(ItemNotFoundException e){ + throw new McApplicationException("ItemNotFoundException occured while trying to download file " + e.getMessage()); + } + } + + + + + public String getFileUuid(String filename) throws McApplicationException + { + try + { + return mcUploadedFileDAO.getFileUuid(filename); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is loading uuid by filename: " + + e.getMessage(), + e); + } + } + + /** + * !! COMPLETE THIS !! + * + * adds a new entry to the uploaded files table + */ + public void persistFile(String uuid, boolean isOnlineFile, String fileName, McContent mcContent) throws McApplicationException { + + logger.debug("attempt persisting file to the db: " + uuid + " " + isOnlineFile + " " + fileName + " " + mcContent); + McUploadedFile mcUploadedFile= new McUploadedFile(uuid, isOnlineFile, fileName, mcContent); + logger.debug("created mcUploadedFile: " + mcUploadedFile); + mcUploadedFileDAO.saveUploadFile(mcUploadedFile); + logger.debug("persisted mcUploadedFile: " + mcUploadedFile); + } + + /** + * + * !! COMPLETE THIS !! + * + * removes all the entries in the uploaded files table + */ + public void cleanUploadedFilesMetaData() throws McApplicationException { + logger.debug("attempt cleaning up uploaded file meta data table from the db"); + mcUploadedFileDAO.cleanUploadedFilesMetaData(); + logger.debug("files meta data has been cleaned up"); + } + + + public List retrieveMcUploadedFiles(Long mcContentId, boolean fileOnline) throws McApplicationException { + try + { + return mcUploadedFileDAO.retrieveMcUploadedFiles(mcContentId, fileOnline); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is loading mc uploaded files: " + + e.getMessage(), + e); + } + } + + public List retrieveMcUploadedOfflineFilesUuid(Long mcContentId) throws McApplicationException { + try + { + return mcUploadedFileDAO.retrieveMcUploadedOfflineFilesUuid(mcContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is loading mc uploaded files: offline + uuids " + + e.getMessage(), + e); + } + } + + + public List retrieveMcUploadedOnlineFilesUuid(Long mcContentId) throws McApplicationException { + try + { + return mcUploadedFileDAO.retrieveMcUploadedOnlineFilesUuid(mcContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is loading mc uploaded files: online + uuids " + + e.getMessage(), + e); + } + } + + + public List retrieveMcUploadedOfflineFilesName(Long mcContentId) throws McApplicationException { + try + { + return mcUploadedFileDAO.retrieveMcUploadedOfflineFilesName(mcContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is loading mc uploaded files: offline + fileNames " + + e.getMessage(), + e); + } + } + + + public List retrieveMcUploadedOnlineFilesName(Long mcContentId) throws McApplicationException { + try + { + return mcUploadedFileDAO.retrieveMcUploadedOnlineFilesName(mcContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is loading mc uploaded files: online + fileNames " + + e.getMessage(), + e); + } + } + + + public List retrieveMcUploadedOfflineFilesUuidPlusFilename(Long mcContentId) throws McApplicationException { + try + { + return mcUploadedFileDAO.retrieveMcUploadedOfflineFilesUuidPlusFilename(mcContentId); + } + catch (DataAccessException e) + { + throw new McApplicationException("Exception occured when lams is loading mc uploaded offline file uuid plus filename: " + + e.getMessage(), + e); + } + + + } + + + /** + * @return Returns the logger. + */ + public static Logger getLogger() { + return logger; + } + /** + * @param logger The logger to set. + */ + public static void setLogger(Logger logger) { + McServicePOJO.logger = logger; + } + /** + * @return Returns the cred. + */ + public ICredentials getCred() { + return cred; + } + /** + * @param cred The cred to set. + */ + public void setCred(ICredentials cred) { + this.cred = cred; + } + + /* + !!! COMPLETE THIS !!! + public IQaUploadedFileDAO getQaUploadedFileDAO() { + return qaUploadedFileDAO; + } + + public void setQaUploadedFileDAO(IQaUploadedFileDAO qaUploadedFileDAO) { + this.qaUploadedFileDAO = qaUploadedFileDAO; + } + + */ + + + /** + * @return Returns the repositoryId. + */ + public char[] getRepositoryId() { + return repositoryId; + } + /** + * @return Returns the repositoryUser. + */ + public String getRepositoryUser() { + return repositoryUser; + } + /** + * @return Returns the repositoryWorkspace. + */ + public String getRepositoryWorkspace() { + return repositoryWorkspace; + } + + /** + * @return Returns the toolService. + */ + public ILamsToolService getToolService() { + return toolService; + } + /** + * @return Returns the userManagementService. + */ + public IUserManagementService getUserManagementService() { + return userManagementService; + } + /** + * @return Returns the mcContentDAO. + */ + public IMcContentDAO getMcContentDAO() { + return mcContentDAO; + } + /** + * @param mcContentDAO The mcContentDAO to set. + */ + public void setMcContentDAO(IMcContentDAO mcContentDAO) { + this.mcContentDAO = mcContentDAO; + } + /** + * @return Returns the mcOptionsContentDAO. + */ + public IMcOptionsContentDAO getMcOptionsContentDAO() { + return mcOptionsContentDAO; + } + /** + * @param mcOptionsContentDAO The mcOptionsContentDAO to set. + */ + public void setMcOptionsContentDAO(IMcOptionsContentDAO mcOptionsContentDAO) { + this.mcOptionsContentDAO = mcOptionsContentDAO; + } + /** + * @return Returns the mcQueContentDAO. + */ + public IMcQueContentDAO getMcQueContentDAO() { + return mcQueContentDAO; + } + /** + * @param mcQueContentDAO The mcQueContentDAO to set. + */ + public void setMcQueContentDAO(IMcQueContentDAO mcQueContentDAO) { + this.mcQueContentDAO = mcQueContentDAO; + } + /** + * @return Returns the mcSessionDAO. + */ + public IMcSessionDAO getMcSessionDAO() { + return mcSessionDAO; + } + /** + * @param mcSessionDAO The mcSessionDAO to set. + */ + public void setMcSessionDAO(IMcSessionDAO mcSessionDAO) { + this.mcSessionDAO = mcSessionDAO; + } + /** + * @return Returns the mcUserDAO. + */ + public IMcUserDAO getMcUserDAO() { + return mcUserDAO; + } + /** + * @param mcUserDAO The mcUserDAO to set. + */ + public void setMcUserDAO(IMcUserDAO mcUserDAO) { + this.mcUserDAO = mcUserDAO; + } + /** + * @return Returns the mcUsrAttemptDAO. + */ + public IMcUsrAttemptDAO getMcUsrAttemptDAO() { + return mcUsrAttemptDAO; + } + /** + * @param mcUsrAttemptDAO The mcUsrAttemptDAO to set. + */ + public void setMcUsrAttemptDAO(IMcUsrAttemptDAO mcUsrAttemptDAO) { + this.mcUsrAttemptDAO = mcUsrAttemptDAO; + } + + /** + * @return Returns the repositoryService. + */ + public IRepositoryService getRepositoryService() { + return repositoryService; + } + /** + * @param repositoryService The repositoryService to set. + */ + public void setRepositoryService(IRepositoryService repositoryService) { + this.repositoryService = repositoryService; + } + + public void setUserManagementService(IUserManagementService userManagementService) + { + this.userManagementService = userManagementService; + } + + public void setToolService(ILamsToolService toolService) + { + this.toolService = toolService; + } + + /** + * @return Returns the mcUploadedFileDAO. + */ + public IMcUploadedFileDAO getMcUploadedFileDAO() { + return mcUploadedFileDAO; + } + /** + * @param mcUploadedFileDAO The mcUploadedFileDAO to set. + */ + public void setMcUploadedFileDAO(IMcUploadedFileDAO mcUploadedFileDAO) { + this.mcUploadedFileDAO = mcUploadedFileDAO; + } + +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/service/McServiceProxy.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/service/McServiceProxy.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/service/McServiceProxy.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,73 @@ +/*************************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * + * 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; either version 2 of the License, or + * (at your option) any later version. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * ***********************************************************************/ + +package org.lamsfoundation.lams.tool.mc.service; + +import javax.servlet.ServletContext; + +import org.lamsfoundation.lams.tool.ToolContentManager; +import org.lamsfoundation.lams.tool.ToolSessionManager; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.WebApplicationContextUtils; + + + + +/** + * @author Ozgur Demirtas + * + *

This class act as the proxy between web layer and service layer. It is + * designed to decouple the presentation logic and business logic completely. + * In this way, the presentation tier will no longer be aware of the changes in + * service layer. Therefore we can feel free to switch the business logic + * implementation.

+ */ +public class McServiceProxy +{ + /** + * Return the mc domain service object. It will delegate to the Spring + * helper method to retrieve the proper bean from Spring bean factory. + * @param servletContext the servletContext for current application + * @return mcq service object. + */ + public static final IMcService getMcService(ServletContext servletContext) + { + return (IMcService)getMcDomainService(servletContext); + } + + public static final ToolSessionManager getMcSessionManager(ServletContext servletContext) + { + return (ToolSessionManager)getMcDomainService(servletContext); + } + + public static final ToolContentManager getMcContentManager(ServletContext servletContext) + { + return (ToolContentManager)getMcDomainService(servletContext); + } + + private static Object getMcDomainService(ServletContext servletContext) + { + WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); + return wac.getBean("mcService"); + } + +} \ No newline at end of file Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/AuthoringUtil.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/AuthoringUtil.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/AuthoringUtil.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,1632 @@ +/* + * Created on 16/05/2005 + */ +package org.lamsfoundation.lams.tool.mc.web; + +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +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.tool.exception.ToolException; +import org.lamsfoundation.lams.tool.mc.McAppConstants; +import org.lamsfoundation.lams.tool.mc.McComparator; +import org.lamsfoundation.lams.tool.mc.McContent; +import org.lamsfoundation.lams.tool.mc.McOptsContent; +import org.lamsfoundation.lams.tool.mc.McQueContent; +import org.lamsfoundation.lams.tool.mc.McUtils; +import org.lamsfoundation.lams.tool.mc.service.IMcService; +import org.lamsfoundation.lams.usermanagement.dto.UserDTO; +import org.lamsfoundation.lams.web.session.SessionManager; +import org.lamsfoundation.lams.web.util.AttributeNames; + +/** + * + * Keeps all operations needed for Authoring mode. + * @author Ozgur Demirtas + * + */ +public class AuthoringUtil implements McAppConstants { + static Logger logger = Logger.getLogger(AuthoringUtil.class.getName()); + + + /** + * populates request parameters + * populateParameters(HttpServletRequest request, McAuthoringForm mcAuthoringForm) + * + * @param request + * @param mcAuthoringForm + */ + protected static void populateParameters(HttpServletRequest request, McAuthoringForm mcAuthoringForm) + { + String selectedQuestion=request.getParameter(SELECTED_QUESTION); + logger.debug("read parameter selectedQuestion: " + selectedQuestion); + + if ((selectedQuestion != null) && (selectedQuestion.length() > 0)) + { + request.getSession().setAttribute(SELECTED_QUESTION,selectedQuestion); + logger.debug("updated SELECTED_QUESTION"); + } + + + mcAuthoringForm.setRemoveQuestion(null); + mcAuthoringForm.setEditOptions(null); + mcAuthoringForm.setMoveUp(null); + mcAuthoringForm.setMoveDown(null); + mcAuthoringForm.setRemoveOption(null); + mcAuthoringForm.setViewFileItem(null); + + String editOptions=request.getParameter("editOptions"); + logger.debug("parameter editOptions" + editOptions); + if ((editOptions != null) && editOptions.equals("1")) + { + logger.debug("parameter editOptions is selected " + editOptions); + mcAuthoringForm.setEditOptions("1"); + } + + String removeQuestion=request.getParameter("removeQuestion"); + logger.debug("parameter removeQuestion" + removeQuestion); + if ((removeQuestion != null) && removeQuestion.equals("1")) + { + logger.debug("parameter removeQuestion is selected " + removeQuestion); + mcAuthoringForm.setRemoveQuestion("1"); + } + + String moveDown=request.getParameter("moveDown"); + logger.debug("parameter moveDown" + moveDown); + if ((moveDown != null) && moveDown.equals("1")) + { + logger.debug("parameter moveDown is selected " + moveDown); + mcAuthoringForm.setMoveDown("1"); + } + + String moveUp=request.getParameter("moveUp"); + logger.debug("parameter moveUp" + moveUp); + if ((moveUp != null) && moveUp.equals("1")) + { + logger.debug("parameter moveUp is selected " + moveUp); + mcAuthoringForm.setMoveUp("1"); + } + + String removeOption=request.getParameter("removeOption"); + logger.debug("parameter removeOption" + removeOption); + if ((removeOption != null) && removeOption.equals("1")) + { + logger.debug("parameter removeOption is selected " + removeOption); + mcAuthoringForm.setRemoveOption("1"); + } + + String viewFileItem=request.getParameter("viewFileItem"); + logger.debug("parameter viewFileItem" + viewFileItem); + if ((viewFileItem != null) && viewFileItem.equals("1")) + { + logger.debug("parameter viewFileItem is selected " + viewFileItem); + mcAuthoringForm.setViewFileItem("1"); + } + } + + + public static Map repopulateCurrentCheckBoxStatesMap(HttpServletRequest request) + { + Map mapTempContent= new TreeMap(new McComparator()); + + long mapCounter=0; + for (long i=1; i <= MAX_OPTION_COUNT ; i++) + { + String candidateEntry =request.getParameter("checkBoxSelected" + i); + String optionText =request.getParameter("optionContent" + i); + + if ( + (candidateEntry != null) && + (candidateEntry.length() > 0) + ) + { + if (candidateEntry.equals("Correct")) + { + mapCounter++; + mapTempContent.put(new Long(mapCounter).toString(), optionText); + } + } + } + logger.debug("return repopulated currentCheckBoxStatesMap: " + mapTempContent); + return mapTempContent; + } + + + public static boolean verifyDuplicatesOptionsMap(Map mapOptionsContent) + { + Map originalMapOptionsContent=mapOptionsContent; + Map backupMapOptionsContent=mapOptionsContent; + + int optionCount=0; + for (long i=1; i <= MAX_OPTION_COUNT ; i++) + { + String currentOption=(String)originalMapOptionsContent.get(new Long(i).toString()); + logger.debug("verified currentOption " + currentOption); + + optionCount=0; + for (long j=1; j <= MAX_OPTION_COUNT ; j++) + { + String backedOption=(String)backupMapOptionsContent.get(new Long(j).toString()); + + if ((currentOption != null) && (backedOption !=null)) + { + if (currentOption.equals(backedOption)) + { + optionCount++; + logger.debug("optionCount for " + currentOption + " is: " + optionCount); + } + + if (optionCount > 1) + return false; + } + } + } + return true; + } + + + public static boolean validateQuestionsNotEmpty(Map mapQuestionsContent) + { + Iterator itMap = mapQuestionsContent.entrySet().iterator(); + while (itMap.hasNext()) { + Map.Entry pairs = (Map.Entry)itMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + + if ((pairs.getValue() != null) && (pairs.getValue().toString().length() == 0)) + return false; + + } + return true; + } + + + public static Map repopulateCurrentWeightsMap(HttpServletRequest request, String parameterType) + { + Map mapTempQuestionsContent= new TreeMap(new McComparator()); + logger.debug("parameterType: " + parameterType); + + long mapCounter=0; + for (long i=1; i <= MAX_QUESTION_COUNT ; i++) + { + String candidateEntry =request.getParameter(parameterType + i); + String questionText =request.getParameter("questionContent" + i); + if ((questionText != null) && (questionText.length() > 0)) + { + logger.debug("questionText: " + questionText); + if (candidateEntry != null) + { + mapCounter++; + mapTempQuestionsContent.put(new Long(mapCounter).toString(), candidateEntry); + } + } + } + logger.debug("return repopulated Map: " + mapTempQuestionsContent); + return mapTempQuestionsContent; + } + + + /** + * shrinks the size of the Map to only used entries + * + * @param mapQuestionContent + * @param request + * @return + */ + public static Map repopulateMap(HttpServletRequest request, String parameterType) + { + Map mapTempQuestionsContent= new TreeMap(new McComparator()); + logger.debug("parameterType: " + parameterType); + + long mapCounter=0; + for (long i=1; i <= MAX_QUESTION_COUNT ; i++) + { + String candidateEntry =request.getParameter(parameterType + i); + if ( + (candidateEntry != null) && + (candidateEntry.length() > 0) + ) + { + mapCounter++; + mapTempQuestionsContent.put(new Long(mapCounter).toString(), candidateEntry); + } + } + logger.debug("return repopulated Map: " + mapTempQuestionsContent); + return mapTempQuestionsContent; + } + + + public static Map shiftMap(Map mapQuestionsContent, String questionIndex , String movableQuestionEntry, String direction) + { + logger.debug("movableQuestionEntry: " + movableQuestionEntry); + /* map to be returned */ + Map mapTempQuestionsContent= new TreeMap(new McComparator()); + + Iterator itMap = mapQuestionsContent.entrySet().iterator(); + String shiftableEntry=null; + + int shiftableIndex=0; + if (direction.equals("down")) + { + logger.debug("moving map down"); + shiftableIndex=new Integer(questionIndex).intValue() + 1; + } + else + { + logger.debug("moving map up"); + shiftableIndex=new Integer(questionIndex).intValue() - 1; + } + + logger.debug("shiftableIndex: " + shiftableIndex); + shiftableEntry=(String)mapQuestionsContent.get(new Integer(shiftableIndex).toString()); + logger.debug("shiftable entry: " + shiftableEntry); + + if (shiftableEntry != null) + { + Iterator itQuestionsMap = mapQuestionsContent.entrySet().iterator(); + long mapCounter=0; + while (itQuestionsMap.hasNext()) { + Map.Entry pairs = (Map.Entry)itQuestionsMap.next(); + logger.debug("comparing the pair: " + pairs.getKey() + " = " + pairs.getValue()); + mapCounter++; + logger.debug("mapCounter: " + mapCounter); + + if (!pairs.getKey().equals(questionIndex) && !pairs.getKey().equals(new Integer(shiftableIndex).toString())) + { + logger.debug("normal copy " + questionIndex); + mapTempQuestionsContent.put(new Long(mapCounter).toString(), pairs.getValue()); + } + else if (pairs.getKey().equals(questionIndex)) + { + logger.debug("move type 1 " + questionIndex); + mapTempQuestionsContent.put(new Long(mapCounter).toString(), shiftableEntry); + } + else if (pairs.getKey().equals(new Integer(shiftableIndex).toString())) + { + logger.debug("move type 2 " + shiftableIndex); + mapTempQuestionsContent.put(new Long(mapCounter).toString(), movableQuestionEntry); + } + } + } + else + { + logger.debug("no change to map"); + mapTempQuestionsContent=mapQuestionsContent; + } + return mapTempQuestionsContent; + } + + + public static boolean validateTotalWeight(HttpServletRequest request) + { + Map mapWeights= repopulateCurrentWeightsMap(request, "questionWeight"); + logger.debug("mapWeights: " + mapWeights); + + Iterator itMap = mapWeights.entrySet().iterator(); + int totalWeight=0; + while (itMap.hasNext()) { + Map.Entry pairs = (Map.Entry)itMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + + if ((pairs.getValue() != null) || (pairs.getValue().toString().length() > 0)) + { + totalWeight=totalWeight+ new Integer(pairs.getValue().toString()).intValue(); + } + } + + logger.debug("totalWeight: " + totalWeight); + if (totalWeight != 100) + { + return false; + } + return true; + } + + + public static boolean validateSubTotalWeights(HttpServletRequest request, McAuthoringForm mcAuthoringForm) + { + Map mapWeights= repopulateCurrentWeightsMap(request, "questionWeight"); + logger.debug("mapWeights: " + mapWeights); + + int totalWeight=0; + Iterator itMap = mapWeights.entrySet().iterator(); + while (itMap.hasNext()) { + Map.Entry pairs = (Map.Entry)itMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + + int currentWeight=new Integer(pairs.getValue().toString()).intValue(); + totalWeight= totalWeight + currentWeight; + logger.debug("sub totalWeight: " + totalWeight); + } + logger.debug("final totalWeight: " + totalWeight); + + if (totalWeight > 100) + return false; + else + return true; + } + + + public static boolean validateOptions(HttpServletRequest request) + { + logger.debug("will validateOptions"); + String parameterType="checkBoxSelected"; + for (int i=1; i <= MAX_OPTION_COUNT ; i++) + { + String isCorrect=request.getParameter(parameterType + i); + logger.debug("isCorrect: " + isCorrect); + + if (isCorrect != null) + { + if (isCorrect.equals("Correct")) + return true; + } + } + return false; + } + + + public static Map rebuildStartupGeneralOptionsQueIdfromDB(HttpServletRequest request, Map mapQuestionsUidContent) + { + IMcService mcService =McUtils.getToolService(request); + Map map= new TreeMap(new McComparator()); + + Iterator itMap = mapQuestionsUidContent.entrySet().iterator(); + Long mapIndex=new Long(1); + while (itMap.hasNext()) { + Map.Entry pairs = (Map.Entry)itMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + String currentQuestionUid=pairs.getValue().toString(); + logger.debug("currentQuestionUid: " + currentQuestionUid); + List listQuestionOptions=mcService.findMcOptionsContentByQueId(new Long(currentQuestionUid)); + logger.debug("listQuestionOptions: " + listQuestionOptions); + Map mapQuestionOptions=generateOptionsQueIdMap(listQuestionOptions); + map.put(mapIndex.toString(),mapQuestionOptions); + mapIndex=new Long(mapIndex.longValue()+1); + } + return map; + } + + + public static Map rebuildStartupGeneralSelectedOptionsContentMapfromDB(HttpServletRequest request, Map mapQuestionsUidContent) + { + IMcService mcService =McUtils.getToolService(request); + Map mapStartupGeneralOptionsContent= new TreeMap(new McComparator()); + + Iterator itMap = mapQuestionsUidContent.entrySet().iterator(); + Long mapIndex=new Long(1); + while (itMap.hasNext()) { + Map.Entry pairs = (Map.Entry)itMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + String currentQuestionUid=pairs.getValue().toString(); + logger.debug("currentQuestionUid: " + currentQuestionUid); + List listQuestionOptions=mcService.getPersistedSelectedOptions(new Long(currentQuestionUid)); + logger.debug("listQuestionOptions: " + listQuestionOptions); + Map mapQuestionOptions=generateOptionsMap(listQuestionOptions); + mapStartupGeneralOptionsContent.put(mapIndex.toString(),mapQuestionOptions); + mapIndex=new Long(mapIndex.longValue()+1); + } + return mapStartupGeneralOptionsContent; + } + + + public static Map rebuildStartupGeneralOptionsContentMapfromDB(HttpServletRequest request, Map mapQuestionsUidContent) + { + IMcService mcService =McUtils.getToolService(request); + Map mapStartupGeneralOptionsContent= new TreeMap(new McComparator()); + + Iterator itMap = mapQuestionsUidContent.entrySet().iterator(); + Long mapIndex=new Long(1); + while (itMap.hasNext()) { + Map.Entry pairs = (Map.Entry)itMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + String currentQuestionUid=pairs.getValue().toString(); + logger.debug("currentQuestionUid: " + currentQuestionUid); + List listQuestionOptions=mcService.findMcOptionsContentByQueId(new Long(currentQuestionUid)); + logger.debug("listQuestionOptions: " + listQuestionOptions); + Map mapQuestionOptions=generateOptionsMap(listQuestionOptions); + mapStartupGeneralOptionsContent.put(mapIndex.toString(),mapQuestionOptions); + mapIndex=new Long(mapIndex.longValue()+1); + } + return mapStartupGeneralOptionsContent; + } + + + public static Map generateOptionsMap(List listQuestionOptions) + { + Map mapOptsContent= new TreeMap(new McComparator()); + + Iterator listIterator=listQuestionOptions.iterator(); + Long mapIndex=new Long(1); + while (listIterator.hasNext()) + { + McOptsContent mcOptsContent=(McOptsContent)listIterator.next(); + logger.debug("mcOptsContent: " + mcOptsContent); + mapOptsContent.put(mapIndex.toString(),mcOptsContent.getMcQueOptionText()); + mapIndex=new Long(mapIndex.longValue()+1); + } + return mapOptsContent; + } + + + public static Map generateOptionsQueIdMap(List listQuestionOptions) + { + Map mapOptsContent= new TreeMap(new McComparator()); + + Iterator listIterator=listQuestionOptions.iterator(); + Long mapIndex=new Long(1); + while (listIterator.hasNext()) + { + McOptsContent mcOptsContent=(McOptsContent)listIterator.next(); + logger.debug("mcOptsContent: " + mcOptsContent); + mapOptsContent.put(mapIndex.toString(),mcOptsContent.getMcQueContentId().toString()); + mapIndex=new Long(mapIndex.longValue()+1); + } + return mapOptsContent; + } + + + + public static Map rebuildQuestionMapfromDB(HttpServletRequest request, Long toolContentId) + { + Map mapQuestionsContent= new TreeMap(new McComparator()); + + IMcService mcService =McUtils.getToolService(request); + logger.debug("toolContentId:" + toolContentId); + + McContent mcContent=mcService.retrieveMc(toolContentId); + logger.debug("mcContent:" + mcContent); + + List list=mcService.refreshQuestionContent(mcContent.getUid()); + logger.debug("refreshed list:" + list); + + Iterator listIterator=list.iterator(); + Long mapIndex=new Long(1); + while (listIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)listIterator.next(); + logger.debug("mcQueContent:" + mcQueContent); + mapQuestionsContent.put(mapIndex.toString(),mcQueContent.getQuestion()); + mapIndex=new Long(mapIndex.longValue()+1); + } + + logger.debug("refreshed Map:" + mapQuestionsContent); + return mapQuestionsContent; + } + + + public static Map rebuildQuestionUidMapfromDB(HttpServletRequest request, Long toolContentId) + { + Map mapQuestionsContent= new TreeMap(new McComparator()); + + IMcService mcService =McUtils.getToolService(request); + logger.debug("toolContentId:" + toolContentId); + + McContent mcContent=mcService.retrieveMc(toolContentId); + logger.debug("mcContent:" + mcContent); + + List list=mcService.refreshQuestionContent(mcContent.getUid()); + logger.debug("refreshed list:" + list); + + Iterator listIterator=list.iterator(); + Long mapIndex=new Long(1); + while (listIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)listIterator.next(); + logger.debug("mcQueContent:" + mcQueContent); + mapQuestionsContent.put(mapIndex.toString(),mcQueContent.getUid()); + mapIndex=new Long(mapIndex.longValue()+1); + } + + logger.debug("refreshed Map:" + mapQuestionsContent); + return mapQuestionsContent; + } + + + /** + * returns all the options for all the questions for a content + * generateGeneralOptionsContentMap(HttpServletRequest request, McContent mcContent) + * + * @param request + * @param mcContent + * @return Map + */ + public static Map generateGeneralOptionsContentMap(HttpServletRequest request, McContent mcContent) + { + Map mapGeneralOptionsContent= new TreeMap(new McComparator()); + IMcService mcService =McUtils.getToolService(request); + + Iterator mcQueIterator=mcContent.getMcQueContents().iterator(); + Long mapIndex=new Long(1); + while (mcQueIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)mcQueIterator.next(); + if (mcQueContent != null) + { + Long uid=mcQueContent.getUid(); + logger.debug("uid : " + uid); + /* get the options for this question */ + List listMcOptions=mcService.findMcOptionsContentByQueId(uid); + logger.debug("listMcOptions : " + listMcOptions); + Map mapOptionsContent=McUtils.generateOptionsMap(listMcOptions); + logger.debug("mapOptionsContent : " + mapOptionsContent); + mapGeneralOptionsContent.put(mapIndex.toString(), mapOptionsContent); + mapIndex=new Long(mapIndex.longValue()+1); + } + } + logger.debug("current mapGeneralOptionsContent: " + mapGeneralOptionsContent); + return mapGeneralOptionsContent; + } + + + public static Map rebuildWeightsMapfromDB(HttpServletRequest request, Long toolContentId) + { + Map mapWeightsContent= new TreeMap(new McComparator()); + + IMcService mcService =McUtils.getToolService(request); + logger.debug("toolContentId:" + toolContentId); + + McContent mcContent=mcService.retrieveMc(toolContentId); + logger.debug("mcContent:" + mcContent); + + List list=mcService.refreshQuestionContent(mcContent.getUid()); + logger.debug("refreshed list:" + list); + + Iterator listIterator=list.iterator(); + Long mapIndex=new Long(1); + while (listIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)listIterator.next(); + logger.debug("mcQueContent:" + mcQueContent); + mapWeightsContent.put(mapIndex.toString(),mcQueContent.getWeight().toString()); + mapIndex=new Long(mapIndex.longValue()+1); + } + + logger.debug("refreshed Map:" + mapWeightsContent); + return mapWeightsContent; + } + + + public static Map buildInCorrectFeedbackMap(HttpServletRequest request, Long toolContentId) + { + IMcService mcService =McUtils.getToolService(request); + Map mapIncorrectFeedback= new TreeMap(new McComparator()); + + McContent mcContent=mcService.retrieveMc(toolContentId); + logger.debug("mcContent:" + mcContent); + + List questionsContent=mcService.refreshQuestionContent(mcContent.getUid()); + logger.debug("questionsContent:" + questionsContent); + + Iterator listIterator=questionsContent.iterator(); + Long mapIndex=new Long(1); + while (listIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)listIterator.next(); + logger.debug("mcQueContent:" + mcQueContent); + mapIncorrectFeedback.put(mapIndex.toString(),mcQueContent.getFeedbackIncorrect()); + mapIndex=new Long(mapIndex.longValue()+1); + } + return mapIncorrectFeedback; + } + + + public static Map buildCorrectFeedbackMap(HttpServletRequest request, Long toolContentId) + { + IMcService mcService =McUtils.getToolService(request); + Map mapCorrectFeedback= new TreeMap(new McComparator()); + + McContent mcContent=mcService.retrieveMc(toolContentId); + logger.debug("mcContent:" + mcContent); + + List questionsContent=mcService.refreshQuestionContent(mcContent.getUid()); + logger.debug("questionsContent:" + questionsContent); + + Iterator listIterator=questionsContent.iterator(); + Long mapIndex=new Long(1); + while (listIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)listIterator.next(); + logger.debug("mcQueContent:" + mcQueContent); + mapCorrectFeedback.put(mapIndex.toString(),mcQueContent.getFeedbackCorrect()); + mapIndex=new Long(mapIndex.longValue()+1); + } + return mapCorrectFeedback; + } + + + /** + * creates the options for a particular question in the db + * persistOptionsFinal(HttpServletRequest request, Map currentOptions, Map selectedOptions, McQueContent mcQueContent) + * + * @param request + * @param currentOptions + * @param selectedOptions + * @param mcQueContent + */ + public static void persistOptionsFinal(HttpServletRequest request, Map currentOptions, Map selectedOptions, McQueContent mcQueContent) + { + logger.debug("doing persistOptionsFinal..."); + IMcService mcService =McUtils.getToolService(request); + logger.debug("passed currentOptions: " + currentOptions); + logger.debug("passed selectedOptions: " + selectedOptions); + + Iterator itCurrentOptions = currentOptions.entrySet().iterator(); + boolean selected=false; + while (itCurrentOptions.hasNext()) + { + Map.Entry pairs = (Map.Entry)itCurrentOptions.next(); + logger.debug("checking the current options pair: " + pairs.getKey() + " = " + pairs.getValue()); + + selected=false; + Iterator itSelectedOptions = selectedOptions.entrySet().iterator(); + while (itSelectedOptions.hasNext()) + { + Map.Entry selectedPairs = (Map.Entry)itSelectedOptions.next(); + logger.debug("checking the selected options pair: " + selectedPairs.getKey() + " = " + selectedPairs.getValue()); + selected=false; + if (pairs.getValue().equals(selectedPairs.getValue())) + { + selected=true; + logger.debug("set selected to true for: " + pairs.getValue()); + break; + } + } + + logger.debug("pre-persist mcOptionsContent: " + pairs.getValue() + " " + selected); + logger.debug("pre-persist mcOptionsContent, using mcQueContent: " + mcQueContent); + McOptsContent mcOptionsContent= new McOptsContent(selected,pairs.getValue().toString() , mcQueContent, new HashSet()); + logger.debug("created mcOptionsContent: " + mcOptionsContent); + mcService.saveMcOptionsContent(mcOptionsContent); + logger.debug("persisted the answer: " + pairs.getValue().toString()); + } + } + + + + /** + * prepares the data to persist options in the db + * persistOptions(HttpServletRequest request, Map mapGeneralOptionsContent, Map mapGeneralSelectedOptionsContent, McQueContent mcQueContent, String questionIndex) + * + * @param request + * @param mapGeneralOptionsContent + * @param mapGeneralSelectedOptionsContent + * @param mcQueContent + * @param questionIndex + */ + public static void persistOptions(HttpServletRequest request, Map mapGeneralOptionsContent, Map mapGeneralSelectedOptionsContent, McQueContent mcQueContent, String questionIndex) + { + logger.debug("doing persistOptions..."); + IMcService mcService =McUtils.getToolService(request); + logger.debug("passed questionIndex: " + questionIndex); + + Iterator itOptionsMap = mapGeneralOptionsContent.entrySet().iterator(); + while (itOptionsMap.hasNext()) { + Map.Entry pairs = (Map.Entry)itOptionsMap.next(); + logger.debug("checking the general options pair: " + pairs.getKey() + " = " + pairs.getValue()); + if ((pairs.getValue() != null) && (!pairs.getValue().equals(""))) + { + Iterator itSelectedOptionsMap = mapGeneralSelectedOptionsContent.entrySet().iterator(); + while (itSelectedOptionsMap.hasNext()) + { + Map.Entry selectedPairs = (Map.Entry)itSelectedOptionsMap.next(); + logger.debug("checking the general selected options pair: " + selectedPairs.getKey() + " = " + selectedPairs.getValue()); + + logger.debug("dubuging: " + pairs.getKey() + "---" + questionIndex); + if (pairs.getKey().equals(selectedPairs.getKey()) && questionIndex.equals(pairs.getKey())) + { + logger.debug("using updated equal question: " + pairs.getKey()); + Map currentOptions=(Map) pairs.getValue(); + Map selectedOptions=(Map) selectedPairs.getValue(); + + persistOptionsFinal(request, currentOptions,selectedOptions,mcQueContent); + } + } + } + } + } + + + /** + * creates the questions content in the db. + * createContent(HttpServletRequest request, McAuthoringForm mcAuthoringForm) + * + * @param request + * @param mcAuthoringForm + * @return + */ + public static McContent createContent(HttpServletRequest request, McAuthoringForm mcAuthoringForm) + { + logger.debug("doing createContent..."); + IMcService mcService =McUtils.getToolService(request); + + /* the tool content id is passed from the container to the tool and placed into session in the McStarterAction */ + Long toolContentId=(Long)request.getSession().getAttribute(TOOL_CONTENT_ID); + if ((toolContentId != null) && (toolContentId.longValue() != 0)) + { + logger.debug("passed TOOL_CONTENT_ID : " + toolContentId); + /*delete the existing content in the database before applying new content*/ + mcService.deleteMcById(toolContentId); + logger.debug("post-deletion existing content"); + } + + String title; + String instructions; + Long createdBy; + String monitoringReportTitle=""; + String reportTitle=""; + + String offlineInstructions=""; + String onlineInstructions=""; + String endLearningMessage=""; + String creationDate=""; + int passmark=0; + + boolean isQuestionsSequenced=false; + boolean isSynchInMonitor=false; + boolean isUsernameVisible=false; + boolean isRunOffline=false; + boolean isDefineLater=false; + boolean isContentInUse=false; + boolean isRetries=false; + boolean isShowFeedback=false; + boolean isSln=false; + + logger.debug("isQuestionsSequenced: " + mcAuthoringForm.getQuestionsSequenced()); + if (mcAuthoringForm.getQuestionsSequenced().equalsIgnoreCase(ON)) + isQuestionsSequenced=true; + + logger.debug("isSynchInMonitor: " + mcAuthoringForm.getSynchInMonitor()); + if (mcAuthoringForm.getSynchInMonitor().equalsIgnoreCase(ON)) + isSynchInMonitor=true; + + logger.debug("isUsernameVisible: " + mcAuthoringForm.getUsernameVisible()); + if (mcAuthoringForm.getUsernameVisible().equalsIgnoreCase(ON)) + isUsernameVisible=true; + + logger.debug("isRetries: " + mcAuthoringForm.getRetries()); + if (mcAuthoringForm.getRetries().equalsIgnoreCase(ON)) + isRetries=true; + + logger.debug("isSln" + mcAuthoringForm.getSln()); + if (mcAuthoringForm.getSln().equalsIgnoreCase(ON)) + isSln=true; + + logger.debug("passmark: " + mcAuthoringForm.getPassmark()); + if ((mcAuthoringForm.getPassmark() != null) && (mcAuthoringForm.getPassmark().length() > 0)) + passmark= new Integer(mcAuthoringForm.getPassmark()).intValue(); + + logger.debug("isShowFeedback: " + mcAuthoringForm.getShowFeedback()); + if (mcAuthoringForm.getShowFeedback().equalsIgnoreCase(ON)) + isShowFeedback=true; + + logger.debug("MONITORING_REPORT_TITLE: " + mcAuthoringForm.getMonitoringReportTitle()); + monitoringReportTitle=mcAuthoringForm.getMonitoringReportTitle(); + if ((monitoringReportTitle == null) || (monitoringReportTitle.length() == 0)) + monitoringReportTitle=(String)request.getSession().getAttribute(MONITORING_REPORT_TITLE); + + reportTitle=mcAuthoringForm.getReportTitle(); + logger.debug("REPORT_TITLE: " + mcAuthoringForm.getReportTitle()); + if ((reportTitle == null) || (reportTitle.length() == 0)) + reportTitle=(String)request.getSession().getAttribute(REPORT_TITLE); + + + endLearningMessage=mcAuthoringForm.getEndLearningMessage(); + logger.debug("END_LEARNING_MESSAGE: " + mcAuthoringForm.getEndLearningMessage()); + if ((endLearningMessage == null) || (endLearningMessage.length() == 0)) + endLearningMessage=(String)request.getSession().getAttribute(END_LEARNING_MESSAGE); + + String richTextTitle=""; + richTextTitle = (String)request.getSession().getAttribute(RICHTEXT_TITLE); + logger.debug("createContent richTextTitle from session: " + richTextTitle); + if (richTextTitle == null) richTextTitle=""; + + String richTextInstructions=""; + richTextInstructions = (String)request.getSession().getAttribute(RICHTEXT_INSTRUCTIONS); + logger.debug("createContent richTextInstructions from session: " + richTextInstructions); + if (richTextInstructions == null) richTextInstructions=""; + + String richTextOfflineInstructions=""; + richTextOfflineInstructions = (String)request.getSession().getAttribute(RICHTEXT_OFFLINEINSTRUCTIONS); + logger.debug("createContent richTextOfflineInstructions from session: " + richTextOfflineInstructions); + if (richTextOfflineInstructions == null) richTextOfflineInstructions=""; + + String richTextOnlineInstructions=""; + richTextOnlineInstructions = (String)request.getSession().getAttribute(RICHTEXT_ONLINEINSTRUCTIONS); + logger.debug("createContent richTextOnlineInstructions from session: " + richTextOnlineInstructions); + if (richTextOnlineInstructions == null) richTextOnlineInstructions=""; + + + String richTextReportTitle=(String)request.getSession().getAttribute(RICHTEXT_REPORT_TITLE); + logger.debug("richTextReportTitle: " + richTextReportTitle); + + String richTextEndLearningMessage=(String)request.getSession().getAttribute(RICHTEXT_END_LEARNING_MSG); + logger.debug("richTextEndLearningMessage: " + richTextEndLearningMessage); + + creationDate=(String)request.getSession().getAttribute(CREATION_DATE); + if (creationDate == null) + creationDate=new Date(System.currentTimeMillis()).toString(); + + + /*obtain user object from the session*/ + HttpSession ss = SessionManager.getSession(); + /* get back login user DTO */ + UserDTO toolUser = (UserDTO) ss.getAttribute(AttributeNames.USER); + logger.debug("retrieving toolUser: " + toolUser); + logger.debug("retrieving toolUser userId: " + toolUser.getUserID()); + String fullName= toolUser.getFirstName() + " " + toolUser.getLastName(); + logger.debug("retrieving toolUser fullname: " + fullName); + long userId=toolUser.getUserID().longValue(); + logger.debug("userId: " + userId); + + /* create a new qa content and leave the default content intact*/ + McContent mc = new McContent(); + mc.setMcContentId(toolContentId); + mc.setTitle(richTextTitle); + mc.setInstructions(richTextInstructions); + mc.setCreationDate(creationDate); /*preserve this from the db*/ + mc.setUpdateDate(new Date(System.currentTimeMillis())); /* keep updating this one*/ + mc.setCreatedBy(userId); /* make sure we are setting the userId from the User object above*/ + mc.setUsernameVisible(isUsernameVisible); + mc.setQuestionsSequenced(isQuestionsSequenced); /* the default question listing in learner mode will be all in the same page*/ + mc.setOnlineInstructions(richTextOnlineInstructions); + mc.setOfflineInstructions(richTextOfflineInstructions); + mc.setRunOffline(false); + mc.setDefineLater(false); + mc.setSynchInMonitor(isSynchInMonitor); + mc.setContentInUse(isContentInUse); + mc.setEndLearningMessage(endLearningMessage); + mc.setRunOffline(isRunOffline); + mc.setReportTitle(richTextReportTitle); + mc.setMonitoringReportTitle(monitoringReportTitle); + mc.setEndLearningMessage(richTextEndLearningMessage); + mc.setRetries(isRetries); + mc.setPassMark(new Integer(passmark)); + mc.setShowReport(isSln); + mc.setShowFeedback(isShowFeedback); + mc.setMcQueContents(new TreeSet()); + mc.setMcSessions(new TreeSet()); + logger.debug("mc content :" + mc); + + /*create the content in the db*/ + mcService.createMc(mc); + logger.debug("mc created with content id: " + toolContentId); + + return mc; + } + + + public static void cleanupExistingQuestions(HttpServletRequest request, McContent mcContent) + { + IMcService mcService =McUtils.getToolService(request); + logger.debug("remove questions by mcQueContent uid : " + mcContent.getUid()); + mcService.cleanAllQuestionsSimple(mcContent.getUid()); + } + + + public static void cleanupRedundantQuestions(HttpServletRequest request, List existingQuestions, Map mapQuestionsContent, McContent mcContent) + { + logger.debug("doing cleanupRedundantQuestions..."); + IMcService mcService =McUtils.getToolService(request); + + /*remove ununsed question entries from the db */ + boolean questionFound=false; + Iterator itExistingQuestions = existingQuestions.iterator(); + while (itExistingQuestions.hasNext()) + { + McQueContent mcQueContent=(McQueContent)itExistingQuestions.next(); + logger.debug("mcQueContent:" + mcQueContent); + + Iterator itNewQuestionsMap = mapQuestionsContent.entrySet().iterator(); + questionFound=false; + while (itNewQuestionsMap.hasNext()) + { + Map.Entry pairs = (Map.Entry)itNewQuestionsMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + logger.debug("mcQueContent.getQuestion(): " + mcQueContent.getQuestion() + "--" + pairs.getValue()); + + if (mcQueContent.getQuestion().equals(pairs.getValue().toString())) + { + logger.debug("equals mcQueContent.getQuestion(): " + mcQueContent.getQuestion() + "--" + pairs.getValue()); + questionFound=true; + break; + } + } + + if (questionFound == false) + { + String deletableQuestion=mcQueContent.getQuestion(); + logger.debug("found is false, delete this question " + deletableQuestion); + mcQueContent=mcService.getQuestionContentByQuestionText(deletableQuestion, mcContent.getUid()); + logger.debug("found is false, delete this question " + mcQueContent); + if (mcQueContent != null) + { + mcService.removeMcQueContent(mcQueContent); + logger.debug("removed mcQueContent from the db: " + mcQueContent); + } + } + } + } + + + public static void selectAndPersistQuestions(HttpServletRequest request, List existingQuestions, Map mapQuestionsContent, Map mapFeedbackIncorrect, Map mapFeedbackCorrect, McContent mcContent) + { + logger.debug("doing selectAndPersistQuestions..."); + IMcService mcService =McUtils.getToolService(request); + + Iterator itQuestionsMap = mapQuestionsContent.entrySet().iterator(); + boolean questionContentFound=false; + while (itQuestionsMap.hasNext()) + { + Map.Entry pairs = (Map.Entry)itQuestionsMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + + questionContentFound = false; + String displayOrder="1"; + McQueContent mcQueContent=null; + Iterator itExistingQuestions = existingQuestions.iterator(); + while (itExistingQuestions.hasNext()) + { + mcQueContent=(McQueContent)itExistingQuestions.next(); + logger.debug("mcQueContent:" + mcQueContent); + + if (mcQueContent.getQuestion().equals(pairs.getValue())) + { + logger.debug("existing mcQueContent found :" + mcQueContent); + questionContentFound=true; + displayOrder=pairs.getKey().toString(); + logger.debug("new display order for " + mcQueContent.getQuestion()+ " will be: " + displayOrder); + break; + } + } + + if (questionContentFound == true) + { + logger.debug("questionContentFound is true: " + mcQueContent); + updateExistingQuestionContent(request,mapFeedbackIncorrect, mapFeedbackCorrect, mcQueContent, displayOrder); + } + else + { + logger.debug("questionContentFound is false: " + mcQueContent); + createQuestionContent(request,mapQuestionsContent, mapFeedbackIncorrect, mapFeedbackCorrect, pairs.getValue().toString(), mcContent); + } + } + } + + + public static void updateExistingQuestionContent(HttpServletRequest request, Map mapFeedbackIncorrect, Map mapFeedbackCorrect, McQueContent mcQueContent, String displayOrder) + { + logger.debug("doing updateExistingQuestionContent..."); + logger.debug("using displayOrder: " + displayOrder); + + Map mapWeights= (Map)request.getSession().getAttribute(MAP_WEIGHTS); + logger.debug("MAP_WEIGHTS:" + mapWeights); + + String incorrectFeedback=(String)mapFeedbackIncorrect.get(displayOrder); + logger.debug("new incorrectFeedback will be :" + incorrectFeedback); + String correctFeedback=(String)mapFeedbackCorrect.get(displayOrder); + logger.debug("new correctFeedback will be :" + correctFeedback); + + String weight=(String)mapWeights.get(displayOrder); + logger.debug("new weight will be:" + weight); + + IMcService mcService =McUtils.getToolService(request); + mcQueContent.setDisplayOrder(new Integer(displayOrder)); + mcQueContent.setDisabled(false); + mcQueContent.setWeight(new Integer(weight)); + + if ((incorrectFeedback != null) && !(incorrectFeedback.equals(""))) + mcQueContent.setFeedbackIncorrect(incorrectFeedback); + + if ((correctFeedback != null) && !(correctFeedback.equals(""))) + mcQueContent.setFeedbackCorrect(correctFeedback); + + mcService.saveOrUpdateMcQueContent(mcQueContent); + logger.debug("updated mcQueContent in the db: " + mcQueContent); + } + + + public static void removeRedundantOptionEntry(HttpServletRequest request, Map mapSGO, Map mapGO, Map options) + { + logger.debug("doing removeRedundantOptionEntry..."); + IMcService mcService =McUtils.getToolService(request); + Iterator itSGOMap = mapSGO.entrySet().iterator(); + boolean optionFound=false; + while (itSGOMap.hasNext()) + { + Map.Entry pairsSGO = (Map.Entry)itSGOMap.next(); + optionFound=false; + Iterator itGOMap = mapGO.entrySet().iterator(); + while (itGOMap.hasNext()) + { + Map.Entry pairsGO = (Map.Entry)itGOMap.next(); + if (pairsSGO.getValue().equals(pairsGO.getValue())) + { + logger.debug("equal option found: " + pairsGO.getValue()); + optionFound=true; + break; + } + } + + if (optionFound == false) + { + logger.debug("options optionFound is false: remove this option"); + int optionSize=options.size(); + logger.debug("optionSize:" + optionSize); + String mcQueContentUid=(String)options.get(new Integer(optionSize).toString()); + + logger.debug("mcQueContentUid: " + mcQueContentUid); + + String deletableOptionText=pairsSGO.getValue().toString(); + logger.debug("deletableOptionText: " + deletableOptionText); + + if (deletableOptionText != null && (!deletableOptionText.equals(""))) + { + McOptsContent mcOptsContent = mcService.getOptionContentByOptionText(deletableOptionText, new Long(mcQueContentUid)); + logger.debug("mcOptsContent: " + mcOptsContent); + mcService.removeMcOptionsContent(mcOptsContent); + logger.debug("removed mcOptsContent from db: " + mcOptsContent); + } + else + { + logger.debug("This should not happen: deletableOptionText is null.."); + } + } + } + } + + + public static void cleanupRedundantOptions(HttpServletRequest request, Map mapStartupGeneralOptionsContent, Map mapStartupGeneralSelectedOptionsContent, Map mapGeneralOptionsContent, Map mapGeneralSelectedOptionsContent, Map mapStartupGeneralOptionsQueId) + { + logger.debug("doing cleanupRedundantOptions..."); + logger.debug("starting cleanupRedundantOptions...:" + mapStartupGeneralOptionsContent); + logger.debug("using mapGeneralOptionsContent..: "+ mapGeneralOptionsContent); + IMcService mcService =McUtils.getToolService(request); + + Iterator itSGOMap = mapStartupGeneralOptionsContent.entrySet().iterator(); + int displayOrder=0; + boolean optionFound=false; + while (itSGOMap.hasNext()) + { + Map.Entry pairsSGO = (Map.Entry)itSGOMap.next(); + + optionFound=false; + Iterator itGOMap = mapGeneralOptionsContent.entrySet().iterator(); + while (itGOMap.hasNext()) + { + Map.Entry pairsGO = (Map.Entry)itGOMap.next(); + if (pairsSGO.getKey().equals(pairsGO.getKey())) + { + logger.debug("equal keys found: " + pairsSGO.getKey()); + Map mapSGO=(Map)pairsSGO.getValue(); + Map mapGO=(Map)pairsGO.getValue(); + logger.debug("mapSGO: " + mapSGO); + logger.debug("mapGO: " + mapGO); + + Map options=(Map)mapStartupGeneralOptionsQueId.get(pairsSGO.getKey()); + logger.debug("options: " + options); + removeRedundantOptionEntry(request, mapSGO, mapGO,options); + } + } + } + } + + + public static void selectAndPersistOptions(HttpServletRequest request, Map mapStartupGeneralOptionsContent, Map mapStartupGeneralSelectedOptionsContent, + Map mapGeneralOptionsContent, Map mapGeneralSelectedOptionsContent, Map mapStartupGeneralOptionsQueId) + { + logger.debug("doing selectAndPersistOptions..."); + logger.debug("starting selectAndPersistOptions..: "+ mapStartupGeneralOptionsContent); + logger.debug("using mapGeneralOptionsContent..: "+ mapGeneralOptionsContent); + IMcService mcService =McUtils.getToolService(request); + + Iterator itSGOMap = mapStartupGeneralOptionsContent.entrySet().iterator(); + int displayOrder=0; + boolean optionFound=false; + while (itSGOMap.hasNext()) + { + Map.Entry pairsSGO = (Map.Entry)itSGOMap.next(); + + optionFound=false; + Iterator itGOMap = mapGeneralOptionsContent.entrySet().iterator(); + while (itGOMap.hasNext()) + { + Map.Entry pairsGO = (Map.Entry)itGOMap.next(); + if (pairsSGO.getKey().equals(pairsGO.getKey())) + { + + logger.debug("equal keys found: " + pairsSGO.getKey()); + String questionIndex=pairsSGO.getKey().toString(); + Map mapSGO=(Map)pairsSGO.getValue(); + Map mapGO=(Map)pairsGO.getValue(); + logger.debug("mapSGO: " + mapSGO); + logger.debug("mapGO: " + mapGO); + + Map options=(Map)mapStartupGeneralOptionsQueId.get(pairsSGO.getKey()); + logger.debug("options: " + options); + updateOrCreateOptions(request, mapSGO, mapGO,options, questionIndex, mapGeneralSelectedOptionsContent); + } + } + } + + logger.debug("will do writePendingOptions for the new questions.."); + writePendingOptions(request, mapGeneralOptionsContent, mapGeneralSelectedOptionsContent); + } + + + public static void updateOrCreateOptions(HttpServletRequest request, Map mapSGO, Map mapGO, Map options, String questionIndex, Map mapGeneralSelectedOptionsContent) + { + logger.debug("doing updateOrCreateOptions..."); + Iterator itOptionsGoMap = mapGO.entrySet().iterator(); + boolean optionContentFound=false; + while (itOptionsGoMap.hasNext()) + { + Map.Entry pairs = (Map.Entry)itOptionsGoMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + + optionContentFound = false; + Iterator itOptionsSGO = mapSGO.entrySet().iterator(); + while (itOptionsSGO.hasNext()) + { + Map.Entry pairsSGO = (Map.Entry)itOptionsSGO.next(); + if (pairsSGO.getValue().equals(pairs.getValue())) + { + optionContentFound = true; + break; + } + } + + if (optionContentFound == false) + { + String optionText=pairs.getValue().toString(); + logger.debug("optionContentFound is false and option is: " + optionText); + createOptionContent(request, options, optionText, questionIndex, mapGeneralSelectedOptionsContent); + } + } + } + + + public static void updateExistingOptionContent(HttpServletRequest request, Map options, String optionText) + { + logger.debug("doing updateExistingOptionContent..."); + IMcService mcService =McUtils.getToolService(request); + int optionSize=options.size(); + logger.debug("optionSize:" + optionSize); + String mcQueContentUid=(String)options.get(new Integer(optionSize).toString()); + logger.debug("mcQueContentUid: " + mcQueContentUid); + + McOptsContent mcOptsContent = mcService.getOptionContentByOptionText(optionText, new Long(mcQueContentUid)); + logger.debug("mcOptsContent: " + mcOptsContent); + mcService.removeMcOptionsContent(mcOptsContent); + logger.debug("removed mcOptsContent from db: " + mcOptsContent); + } + + + public static void writePendingOptions(HttpServletRequest request, Map mapGeneralOptionsContent, Map mapGeneralSelectedOptionsContent) + { + logger.debug("doing writePendingQuestions..."); + Iterator itGO = mapGeneralOptionsContent.entrySet().iterator(); + while (itGO.hasNext()) + { + Map.Entry pairsGO = (Map.Entry)itGO.next(); + Map pendingOptions=(Map) pairsGO.getValue(); + logger.debug("pendingOptions: " + pendingOptions); + writePendingOption(request, pairsGO.getKey().toString(), pendingOptions, mapGeneralSelectedOptionsContent); + } + } + + + public static void writePendingOption(HttpServletRequest request, String questionIndex, Map pendingOptions, Map mapGeneralSelectedOptionsContent) + { + logger.debug("doing writePendingOption..."); + logger.debug("questionIndex: " + questionIndex); + logger.debug("pendingOptions: " + pendingOptions); + IMcService mcService =McUtils.getToolService(request); + + Long toolContentId=(Long)request.getSession().getAttribute(TOOL_CONTENT_ID); + logger.debug("getting existing content with id:" + toolContentId); + McContent mcContent=mcService.retrieveMc(toolContentId); + logger.debug("existing mcContent:" + mcContent); + McQueContent mcQueContent=mcService.getQuestionContentByDisplayOrder(new Long(questionIndex), mcContent.getUid()); + logger.debug("exracted mcQueContent:" + mcQueContent); + + if (mcQueContent != null) + { + Long mcQueContentUid=mcQueContent.getUid(); + logger.debug("mcQueContentUid:" + mcQueContentUid); + + Iterator itPQ = pendingOptions.entrySet().iterator(); + boolean isOptionSelected=false; + while (itPQ.hasNext()) + { + Map.Entry pairsPQ = (Map.Entry)itPQ.next(); + String optionText=pairsPQ.getValue().toString() ; + logger.debug("optionText: " + optionText); + isOptionSelected=false; + isOptionSelected=isOptionSelected(mapGeneralSelectedOptionsContent, optionText, questionIndex); + logger.debug("isOptionSelected: " + isOptionSelected); + + McOptsContent mcOptsContent = mcService.getOptionContentByOptionText(optionText, mcQueContentUid); + logger.debug("mcOptsContent: " + mcOptsContent); + + if (mcOptsContent == null) + { + mcOptsContent = new McOptsContent(isOptionSelected, pairsPQ.getValue().toString(),mcQueContent , new TreeSet()); + logger.debug("created new mcOptsContent:" + mcOptsContent); + } + else + { + logger.debug("this option is already persisted mcQueContent, just look after isOptionSelected:" + mcQueContent); + mcOptsContent.setCorrectOption(isOptionSelected); + } + mcService.saveMcOptionsContent(mcOptsContent); + logger.debug("persisted mcQueContent: " + mcQueContent); + } + } + } + + + public static void createOptionContent(HttpServletRequest request, Map options, String optionText, + String questionIndex, Map mapGeneralSelectedOptionsContent) + { + IMcService mcService =McUtils.getToolService(request); + logger.debug("doing createOptionContent..."); + int optionSize=options.size(); + logger.debug("optionSize:" + optionSize); + logger.debug("optionText:" + optionText); + + String mcQueContentUid=(String)options.get(new Integer(optionSize).toString()); + logger.debug("mcQueContentUid: " + mcQueContentUid); + + boolean isOptionSelected=isOptionSelected(mapGeneralSelectedOptionsContent, optionText, questionIndex); + logger.debug("isOptionSelected: " + isOptionSelected); + + if (mcQueContentUid != null) + { + McQueContent mcQueContent= mcService.getMcQueContentByUID(new Long(mcQueContentUid)); + logger.debug("mcQueContent: " + mcQueContent); + + McOptsContent mcOptsContent = mcService.getOptionContentByOptionText(optionText, new Long(mcQueContentUid)); + if (mcOptsContent == null) + { + mcOptsContent = new McOptsContent(isOptionSelected, optionText,mcQueContent , new TreeSet()); + mcService.saveMcOptionsContent(mcOptsContent); + logger.debug("persisted mcQueContent: " + mcQueContent); + } + else + { + logger.debug("mcOptsContent already exists: " + mcQueContent); + } + } + else + { + Long toolContentId=(Long)request.getSession().getAttribute(TOOL_CONTENT_ID); + logger.debug("getting existing content with id:" + toolContentId); + McContent mcContent=mcService.retrieveMc(toolContentId); + logger.debug("existing mcContent:" + mcContent); + logger.debug("mcOptsContent is null, get the mcQueContent in an alternative way, use pendingOptionsKey: " + questionIndex); + McQueContent mcQueContent=mcService.getQuestionContentByDisplayOrder(new Long(questionIndex), mcContent.getUid()); + logger.debug("exracted mcQueContent:" + mcQueContent); + + if (mcQueContent != null) + { + McOptsContent mcOptsContent = new McOptsContent(isOptionSelected, optionText,mcQueContent , new TreeSet()); + mcService.saveMcOptionsContent(mcOptsContent); + logger.debug("persisted mcQueContent: " + mcQueContent); + } + } + } + + + public static boolean isOptionSelected(Map mapGeneralSelectedOptionsContent, String optionText, String questionIndex) + { + Iterator itGSOMap = mapGeneralSelectedOptionsContent.entrySet().iterator(); + logger.debug("questionIndex: " + questionIndex); + logger.debug("optionText: " + optionText); + while (itGSOMap.hasNext()) + { + Map.Entry pairs = (Map.Entry)itGSOMap.next(); + if (pairs.getKey().toString().equals(questionIndex)) + { + Map currentOptionsMap= (Map)pairs.getValue(); + logger.debug("currentOptionsMap: " + currentOptionsMap); + boolean isOptionSelectedInMap=isOptionSelectedInMap(optionText, currentOptionsMap); + logger.debug("isOptionSelectedInMap: " + isOptionSelectedInMap); + return isOptionSelectedInMap; + } + } + return false; + } + + + public static boolean isOptionSelectedInMap(String optionText, Map currentOptionsMap) + { + logger.debug("optionText: " + optionText); + Iterator itCOMap = currentOptionsMap.entrySet().iterator(); + while (itCOMap.hasNext()) + { + Map.Entry pairs = (Map.Entry)itCOMap.next(); + if (pairs.getValue().toString().equals(optionText)) + { + logger.debug("option text found in the map: " + optionText); + return true; + } + } + return false; + } + + + public static void createDefaultOptionContent(HttpServletRequest request, McQueContent mcQueContent) + { + logger.debug("doing createDefaultOptionContent..."); + IMcService mcService =McUtils.getToolService(request); + + String mcQueContentUid=mcQueContent.getUid().toString(); + logger.debug("mcQueContentUid:" + mcQueContentUid); + + if (mcQueContentUid != null) + { + McOptsContent mcOptsContent= new McOptsContent(true,"a sample answer", mcQueContent, new TreeSet()); + mcService.saveMcOptionsContent(mcOptsContent); + logger.debug("created a new mcOptsContent in the db: " + mcOptsContent); + } + } + + + public static void createQuestionContent(HttpServletRequest request, Map mapQuestionsContent, Map mapFeedbackIncorrect, Map mapFeedbackCorrect, String question, McContent mcContent) + { + logger.debug("using createQuestionContent with question: " + question); + IMcService mcService =McUtils.getToolService(request); + + int displayOrder= getNewDisplayOrder(mapQuestionsContent, question); + logger.debug("displayOrder: " + displayOrder); + + Map mapWeights= (Map)request.getSession().getAttribute(MAP_WEIGHTS); + logger.debug("MAP_WEIGHTS: " + MAP_WEIGHTS); + + String weight=(String)mapWeights.get(new Integer(displayOrder).toString()); + logger.debug("new weight will be:" + weight); + + String incorrectFeedback=(String)mapFeedbackIncorrect.get(new Integer(displayOrder).toString()); + logger.debug("new incorrectFeedback will be :" + incorrectFeedback); + + String correctFeedback=(String)mapFeedbackCorrect.get(new Integer(displayOrder).toString()); + logger.debug("new correctFeedback will be :" + correctFeedback); + + McQueContent mcQueContent= new McQueContent(question, + new Integer(displayOrder), + new Integer(weight), + false, + incorrectFeedback, + correctFeedback, + mcContent, + new HashSet(), + new HashSet() + ); + + mcService.saveOrUpdateMcQueContent(mcQueContent); + logger.debug("created a new mcQueContent in the db: " + mcQueContent); + } + + + public static int getNewDisplayOrder(Map mapQuestionsContent, String question) + { + Iterator itQuestionsMap = mapQuestionsContent.entrySet().iterator(); + int displayOrder=0; + while (itQuestionsMap.hasNext()) + { + Map.Entry pairs = (Map.Entry)itQuestionsMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + if (pairs.getValue().equals(question)) + { + logger.debug("question found:" + question); + displayOrder=new Integer(pairs.getKey().toString()).intValue(); + logger.debug("displayOrder:" + displayOrder); + } + } + return displayOrder; + } + + + /** + * creates the questions from the user in the db and makes a call to persist options. + * persistQuestions(HttpServletRequest request, Map mapQuestionsContent, Map mapFeedbackIncorrect, Map mapFeedbackCorrect, McContent mcContent) + * + * @param request + * @param mapQuestionsContent + * @param mapFeedbackIncorrect + * @param mapFeedbackCorrect + * @param mcContent + */ + public static void persistQuestions(HttpServletRequest request, Map mapQuestionsContent, Map mapFeedbackIncorrect, Map mapFeedbackCorrect, McContent mcContent) + { + IMcService mcService =McUtils.getToolService(request); + logger.debug("mapQuestionsContent to be persisted :" + mapQuestionsContent); + logger.debug("mapFeedbackIncorrect :" + mapFeedbackIncorrect); + logger.debug("mapFeedbackCorrect :" + mapFeedbackCorrect); + + Map mapGeneralOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_OPTIONS_CONTENT); + logger.debug("final MAP_GENERAL_OPTIONS_CONTENT :" + mapGeneralOptionsContent); + + Map mapGeneralSelectedOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_SELECTED_OPTIONS_CONTENT); + logger.debug("final MAP_GENERAL_SELECTED_OPTIONS_CONTENT :" + mapGeneralSelectedOptionsContent); + + Map mapWeights= AuthoringUtil.repopulateMap(request, "questionWeight"); + request.getSession().setAttribute(MAP_WEIGHTS, mapWeights); + logger.debug("MAP_WEIGHTS:" + request.getSession().getAttribute(MAP_WEIGHTS)); + + Iterator itQuestionsMap = mapQuestionsContent.entrySet().iterator(); + while (itQuestionsMap.hasNext()) { + Map.Entry pairs = (Map.Entry)itQuestionsMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + if ((pairs.getValue() != null) && (!pairs.getValue().equals(""))) + { + logger.debug("checking existing question text: " + pairs.getValue().toString() + " and mcContent uid():" + mcContent.getUid()); + + String currentFeedbackIncorrect=(String)mapFeedbackIncorrect.get(pairs.getKey()); + logger.debug("currentFeedbackIncorrect: " + currentFeedbackIncorrect); + if (currentFeedbackIncorrect == null) currentFeedbackIncorrect=""; + + String currentFeedbackCorrect=(String)mapFeedbackCorrect.get(pairs.getKey()); + logger.debug("currentFeedbackCorrect: " + currentFeedbackCorrect); + if (currentFeedbackCorrect == null) currentFeedbackCorrect=""; + + String currentWeight=(String) mapWeights.get(pairs.getKey().toString()); + logger.debug("currentWeight: " + currentWeight); + + McQueContent mcQueContent= new McQueContent(pairs.getValue().toString(), + new Integer(pairs.getKey().toString()), + new Integer(currentWeight), + false, + currentFeedbackIncorrect, + currentFeedbackCorrect, + mcContent, + new HashSet(), + new HashSet() + ); + mcService.createMcQue(mcQueContent); + logger.debug("persisted mcQueContent: " + mcQueContent); + + logger.debug("remove existing options for mcQueContent : " + mcQueContent.getUid()); + mcService.removeMcOptionsContentByQueId(mcQueContent.getUid()); + logger.debug("removed all mcOptionsContents for mcQueContentId :" + mcQueContent.getUid()); + + if (mcQueContent != null) + { + logger.debug("pre persistOptions for: " + mcQueContent); + logger.debug("sending :" + pairs.getKey().toString()); + AuthoringUtil.persistOptions(request, mapGeneralOptionsContent, mapGeneralSelectedOptionsContent, mcQueContent, pairs.getKey().toString()); + logger.debug("post persistOptions"); + } + } + } + } + + + /** + * includes the new question entry in the questions Map + * addQuestionMemory(HttpServletRequest request, McAuthoringForm mcAuthoringForm, Map mapQuestionsContent, boolean increaseMapSize) + * + * @param request + * @param mcAuthoringForm + * @param mapQuestionsContent + * @param increaseMapSize + */ + public static void addQuestionMemory(HttpServletRequest request, McAuthoringForm mcAuthoringForm, Map mapQuestionsContent, boolean increaseMapSize) + { + if (increaseMapSize) + { + int mapSize=mapQuestionsContent.size(); + mapQuestionsContent.put(new Long(++mapSize).toString(), ""); + logger.debug("updated Questions Map size: " + mapQuestionsContent.size()); + request.getSession().setAttribute(MAP_QUESTIONS_CONTENT, mapQuestionsContent); + logger.debug("updated Questions Map: " + request.getSession().getAttribute(MAP_QUESTIONS_CONTENT)); + + Map mapWeights = (Map) request.getSession().getAttribute(MAP_WEIGHTS); + logger.debug("current mapWeights: " + mapWeights); + int mapWeightsSize=mapWeights.size(); + mapWeights.put(new Long(++mapWeightsSize).toString(), ""); + logger.debug("updated mapWeights size: " + mapWeights.size()); + request.getSession().setAttribute(MAP_WEIGHTS, mapWeights); + logger.debug("updated mapWeights: " + request.getSession().getAttribute(MAP_WEIGHTS)); + } + } + + + public static int getNextAvailableDisplayOrder(HttpServletRequest request, Long mcContentId) + { + IMcService mcService =McUtils.getToolService(request); + List listDisplayOrder=mcService.getNextAvailableDisplayOrder(mcContentId.longValue()); + + Iterator itListDisplayOrder = listDisplayOrder.iterator(); + int maxDisplayOrder=1; + while (itListDisplayOrder.hasNext()) + { + McQueContent mcQueContent=(McQueContent)itListDisplayOrder.next(); + logger.debug("mcQueContent:" + mcQueContent); + int currentDisplayOrder=mcQueContent.getDisplayOrder().intValue(); + if (currentDisplayOrder > maxDisplayOrder) + maxDisplayOrder = currentDisplayOrder; + } + logger.debug("current biggest displayOrder is: " + maxDisplayOrder); + return maxDisplayOrder+1; + + } + + + public static void refreshMaps(HttpServletRequest request, long toolContentId) + { + Map mapQuestionsUidContent=AuthoringUtil.rebuildQuestionUidMapfromDB(request, new Long(toolContentId)); + logger.debug("mapQuestionsUidContent:" + mapQuestionsUidContent); + + Map mapStartupGeneralOptionsContent=AuthoringUtil.rebuildStartupGeneralOptionsContentMapfromDB(request, mapQuestionsUidContent); + logger.debug("mapStartupGeneralOptionsContent:" + mapStartupGeneralOptionsContent); + request.getSession().setAttribute(MAP_STARTUP_GENERAL_OPTIONS_CONTENT, mapStartupGeneralOptionsContent); + + Map mapStartupGeneralSelectedOptionsContent=AuthoringUtil.rebuildStartupGeneralSelectedOptionsContentMapfromDB(request, mapQuestionsUidContent); + logger.debug("mapStartupGeneralSelectedOptionsContent:" + mapStartupGeneralSelectedOptionsContent); + request.getSession().setAttribute(MAP_STARTUP_GENERAL_SELECTED_OPTIONS_CONTENT, mapStartupGeneralSelectedOptionsContent); + + Map mapStartupGeneralOptionsQueId=AuthoringUtil.rebuildStartupGeneralOptionsQueIdfromDB(request, mapQuestionsUidContent); + logger.debug("mapStartupGeneralOptionsQueId:" + mapStartupGeneralOptionsQueId); + request.getSession().setAttribute(MAP_STARTUP_GENERAL_OPTIONS_QUEID, mapStartupGeneralOptionsQueId); + } + + + public void simulatePropertyInspector_RunOffline(HttpServletRequest request) + { + IMcService mcService =McUtils.getToolService(request); + + String toolContentId=(String)request.getSession().getAttribute(TOOL_CONTENT_ID); + if ((toolContentId != null) && (!toolContentId.equals(""))) + { + logger.debug("passed TOOL_CONTENT_ID : " + new Long(toolContentId)); + try + { + mcService.setAsRunOffline(new Long(toolContentId)); + } + catch(ToolException e) + { + logger.debug("we should never come here"); + } + + logger.debug("post-RunAsOffline"); + } + logger.debug("end of simulating RunOffline on content id: " + toolContentId); + } + + /** + * Normally, a request to set defineLaterproperty of the content comes directly from container through the property inspector. + * What we do below is simulate that for development purposes. + * @param request + */ + public void simulatePropertyInspector_setAsDefineLater(HttpServletRequest request) + { + IMcService mcService =McUtils.getToolService(request); + + String toolContentId=(String)request.getSession().getAttribute(TOOL_CONTENT_ID); + if ((toolContentId != null) && (!toolContentId.equals(""))) + { + logger.debug("passed TOOL_CONTENT_ID : " + new Long(toolContentId)); + try + { + mcService.setAsDefineLater(new Long(toolContentId)); + } + catch(ToolException e) + { + logger.debug("we should never come here"); + } + + logger.debug("post-setAsDefineLater"); + } + logger.debug("end of simulating setAsDefineLater on content id: " + toolContentId); + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/LearningUtil.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/LearningUtil.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/LearningUtil.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,662 @@ +/* + * Created on 16/05/2005 + */ +package org.lamsfoundation.lams.tool.mc.web; + +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.TreeSet; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.log4j.Logger; +import org.lamsfoundation.lams.tool.mc.McAppConstants; +import org.lamsfoundation.lams.tool.mc.McComparator; +import org.lamsfoundation.lams.tool.mc.McContent; +import org.lamsfoundation.lams.tool.mc.McOptsContent; +import org.lamsfoundation.lams.tool.mc.McQueContent; +import org.lamsfoundation.lams.tool.mc.McQueUsr; +import org.lamsfoundation.lams.tool.mc.McSession; +import org.lamsfoundation.lams.tool.mc.McUsrAttempt; +import org.lamsfoundation.lams.tool.mc.McUtils; +import org.lamsfoundation.lams.tool.mc.service.IMcService; + +/** + * + * Keeps all operations needed for Authoring mode. + * @author Ozgur Demirtas + * + */ +public class LearningUtil implements McAppConstants { + static Logger logger = Logger.getLogger(LearningUtil.class.getName()); + + /** + * updates the Map based on learner activity + * selectOptionsCheckBox(HttpServletRequest request,McLearningForm mcLearningForm, String questionIndex) + * + * @param request + * @param form + */ + public static void selectOptionsCheckBox(HttpServletRequest request,McLearningForm mcLearningForm, String questionIndex) + { + logger.debug("requested optionCheckBoxSelected..."); + logger.debug("questionIndex: " + mcLearningForm.getQuestionIndex()); + logger.debug("optionIndex: " + mcLearningForm.getOptionIndex()); + logger.debug("optionValue: " + mcLearningForm.getOptionValue()); + logger.debug("checked: " + mcLearningForm.getChecked()); + + Map mapGeneralCheckedOptionsContent=(Map) request.getSession().getAttribute(MAP_GENERAL_CHECKED_OPTIONS_CONTENT); + logger.debug("mapGeneralCheckedOptionsContent: " + mapGeneralCheckedOptionsContent); + + if (mapGeneralCheckedOptionsContent.size() == 0) + { + logger.debug("mapGeneralCheckedOptionsContent size is 0"); + Map mapLeanerCheckedOptionsContent= new TreeMap(new McComparator()); + + if (mcLearningForm.getChecked().equals("true")) + mapLeanerCheckedOptionsContent.put(mcLearningForm.getOptionIndex(), mcLearningForm.getOptionValue()); + else + mapLeanerCheckedOptionsContent.remove(mcLearningForm.getOptionIndex()); + + mapGeneralCheckedOptionsContent.put(mcLearningForm.getQuestionIndex(),mapLeanerCheckedOptionsContent); + request.getSession().setAttribute(MAP_GENERAL_CHECKED_OPTIONS_CONTENT, mapGeneralCheckedOptionsContent); + } + else + { + Map mapCurrentOptions=(Map) mapGeneralCheckedOptionsContent.get(questionIndex); + + logger.debug("mapCurrentOptions: " + mapCurrentOptions); + if (mapCurrentOptions != null) + { + if (mcLearningForm.getChecked().equals("true")) + mapCurrentOptions.put(mcLearningForm.getOptionIndex(), mcLearningForm.getOptionValue()); + else + mapCurrentOptions.remove(mcLearningForm.getOptionIndex()); + + logger.debug("updated mapCurrentOptions: " + mapCurrentOptions); + + mapGeneralCheckedOptionsContent.put(mcLearningForm.getQuestionIndex(),mapCurrentOptions); + request.getSession().setAttribute(MAP_GENERAL_CHECKED_OPTIONS_CONTENT, mapGeneralCheckedOptionsContent); + } + else + { + logger.debug("no options for this questions has been selected yet"); + Map mapLeanerCheckedOptionsContent= new TreeMap(new McComparator()); + + if (mcLearningForm.getChecked().equals("true")) + mapLeanerCheckedOptionsContent.put(mcLearningForm.getOptionIndex(), mcLearningForm.getOptionValue()); + else + mapLeanerCheckedOptionsContent.remove(mcLearningForm.getOptionIndex()); + + mapGeneralCheckedOptionsContent.put(mcLearningForm.getQuestionIndex(),mapLeanerCheckedOptionsContent); + request.getSession().setAttribute(MAP_GENERAL_CHECKED_OPTIONS_CONTENT, mapGeneralCheckedOptionsContent); + } + } + + mapGeneralCheckedOptionsContent=(Map) request.getSession().getAttribute(MAP_GENERAL_CHECKED_OPTIONS_CONTENT); + logger.debug("final mapGeneralCheckedOptionsContent: " + mapGeneralCheckedOptionsContent); + } + + + /** + * continueOptions(HttpServletRequest request) + * + * @param request + * @return boolean + */ + public static boolean continueOptions(HttpServletRequest request) + { + IMcService mcService =McUtils.getToolService(request); + + logger.debug("continue options requested."); + String currentQuestionIndex=(String)request.getSession().getAttribute(CURRENT_QUESTION_INDEX); + logger.debug("currentQuestionIndex:" + currentQuestionIndex); + + int newQuestionIndex=new Integer(currentQuestionIndex).intValue() + 1; + request.getSession().setAttribute(CURRENT_QUESTION_INDEX, new Integer(newQuestionIndex).toString()); + logger.debug("updated questionIndex:" + request.getSession().getAttribute(CURRENT_QUESTION_INDEX)); + + Long toolContentID= (Long) request.getSession().getAttribute(TOOL_CONTENT_ID); + logger.debug("TOOL_CONTENT_ID: " + toolContentID); + + McContent mcContent=mcService.retrieveMc(toolContentID); + logger.debug("mcContent: " + mcContent); + + /* + * fetch question content from content + */ + logger.debug("newQuestionIndex: " + newQuestionIndex); + Iterator contentIterator=mcContent.getMcQueContents().iterator(); + boolean questionFound=false; + while (contentIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)contentIterator.next(); + if (mcQueContent != null) + { + int displayOrder=mcQueContent.getDisplayOrder().intValue(); + logger.debug("displayOrder: " + displayOrder); + + /* prepare the next question's candidate answers for presentation*/ + if (newQuestionIndex == displayOrder) + { + logger.debug("get the next question... "); + Long uid=mcQueContent.getUid(); + logger.debug("uid : " + uid); + /* get the options for this question */ + List listMcOptions=mcService.findMcOptionsContentByQueId(uid); + logger.debug("listMcOptions : " + listMcOptions); + Map mapOptionsContent=McUtils.generateOptionsMap(listMcOptions); + request.getSession().setAttribute(MAP_OPTIONS_CONTENT, mapOptionsContent); + logger.debug("updated Options Map: " + request.getSession().getAttribute(MAP_OPTIONS_CONTENT)); + questionFound=true; + } + } + } + logger.debug("questionFound: " + questionFound); + return questionFound; + } + + + /** + * readParameters(HttpServletRequest request, McLearningForm mcLearningForm) + * + * @param request + * @param mcLearningForm + */ + public static void readParameters(HttpServletRequest request, McLearningForm mcLearningForm) + { + String optionCheckBoxSelected=request.getParameter("optionCheckBoxSelected"); + logger.debug("parameter optionCheckBoxSelected: " + optionCheckBoxSelected); + if ((optionCheckBoxSelected != null) && optionCheckBoxSelected.equals("1")) + { + logger.debug("parameter optionCheckBoxSelected is selected " + optionCheckBoxSelected); + mcLearningForm.setOptionCheckBoxSelected("1"); + } + + String questionIndex=request.getParameter("questionIndex"); + logger.debug("parameter questionIndex: " + questionIndex); + if ((questionIndex != null)) + { + logger.debug("parameter questionIndex is selected " + questionIndex); + mcLearningForm.setQuestionIndex(questionIndex); + } + + String optionIndex=request.getParameter("optionIndex"); + logger.debug("parameter optionIndex: " + optionIndex); + if (optionIndex != null) + { + logger.debug("parameter optionIndex is selected " + optionIndex); + mcLearningForm.setOptionIndex(optionIndex); + } + + String optionValue=request.getParameter("optionValue"); + logger.debug("parameter optionValue: " + optionValue); + if (optionValue != null) + { + mcLearningForm.setOptionValue(optionValue); + } + + String checked=request.getParameter("checked"); + logger.debug("parameter checked: " + checked); + if (checked != null) + { + logger.debug("parameter checked is selected " + checked); + mcLearningForm.setChecked(checked); + } + } + + + /** + * assess(HttpServletRequest request, Map mapGeneralCheckedOptionsContent) + * + * @param request + * @param mapGeneralCheckedOptionsContent + */ + public static Map assess(HttpServletRequest request, Map mapGeneralCheckedOptionsContent, Long toolContentId) + { + Map mapGeneralCorrectOptions= new TreeMap(new McComparator()); + + IMcService mcService =McUtils.getToolService(request); + + Map mapQuestionsUidContent=AuthoringUtil.rebuildQuestionUidMapfromDB(request,toolContentId); + logger.debug("mapQuestionsUidContent : " + mapQuestionsUidContent); + + Iterator itMap = mapQuestionsUidContent.entrySet().iterator(); + Long mapIndex=new Long(1); + while (itMap.hasNext()) { + Map.Entry pairs = (Map.Entry)itMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + + logger.debug("using mcQueContentId: " + pairs.getValue()); + List correctOptions=(List) mcService.getPersistedSelectedOptions(new Long(pairs.getValue().toString())); + Map mapCorrectOptions=buildMapCorrectOptions(correctOptions); + logger.debug("mapCorrectOptions: " + mapCorrectOptions); + mapGeneralCorrectOptions.put(mapIndex.toString(),mapCorrectOptions); + mapIndex=new Long(mapIndex.longValue()+1); + } + logger.debug("mapGeneralCorrectOptions : " + mapGeneralCorrectOptions); + + Map mapLeanerAssessmentResults=compare(mapGeneralCorrectOptions,mapGeneralCheckedOptionsContent); + logger.debug("mapLeanerAssessmentResults : " + mapLeanerAssessmentResults); + request.getSession().setAttribute(MAP_LEARNER_ASSESSMENT_RESULTS, mapLeanerAssessmentResults); + + return mapLeanerAssessmentResults; + + } + + + public static int calculateWeights(Map mapLeanerAssessmentResults, Map mapQuestionWeights) + { + logger.debug("starting calculate weights..."); + logger.debug("mapLeanerAssessmentResults : " + mapLeanerAssessmentResults); + logger.debug("mapQuestionWeights : " + mapQuestionWeights); + + int totalUserWeight=0; + Iterator itLearnerAssessmentMap = mapLeanerAssessmentResults.entrySet().iterator(); + while (itLearnerAssessmentMap.hasNext()) + { + Map.Entry pairs = (Map.Entry)itLearnerAssessmentMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + + Iterator itWeightsMap = mapQuestionWeights.entrySet().iterator(); + while (itWeightsMap.hasNext()) + { + Map.Entry pairsWeight = (Map.Entry)itWeightsMap.next(); + logger.debug("using the weight pair: " + pairsWeight.getKey() + " = " + pairsWeight.getValue()); + if (pairs.getKey().toString().equals(pairsWeight.getKey().toString())) + { + logger.debug("equal question found " + pairsWeight.getKey() + " = " + pairsWeight.getValue() + " and " + pairs.getValue()); + + if (pairs.getValue().toString().equalsIgnoreCase("true")) + { + logger.debug("equal question found " + pairsWeight.getKey() + " is a correct answer."); + int weight= new Integer(pairsWeight.getValue().toString()).intValue(); + logger.debug("weight: " + weight); + + totalUserWeight=totalUserWeight + weight; + } + } + } + } + logger.debug("totalUserWeight: " + totalUserWeight); + return totalUserWeight; + } + + + public static int getMark(Map mapLeanerAssessmentResults) + { + int totalUserWeight=0; + Iterator itLearnerAssessmentMap = mapLeanerAssessmentResults.entrySet().iterator(); + int correctAnswerCount=0; + while (itLearnerAssessmentMap.hasNext()) + { + Map.Entry pairs = (Map.Entry)itLearnerAssessmentMap.next(); + if (pairs.getValue().toString().equalsIgnoreCase("true")) + { + ++correctAnswerCount; + } + } + return correctAnswerCount; + } + + + public static int getHighestAttemptOrder(HttpServletRequest request, Long queUsrId) + { + IMcService mcService =McUtils.getToolService(request); + List listMarks=mcService.getHighestAttemptOrder(queUsrId); + + Iterator itMarks=listMarks.iterator(); + int highestAO=0; + while (itMarks.hasNext()) + { + McUsrAttempt mcUsrAttempt=(McUsrAttempt)itMarks.next(); + int currentAO=mcUsrAttempt.getAttemptOrder().intValue(); + if (currentAO > highestAO) + highestAO= currentAO; + } + return highestAO; + } + + + /** + * returns the highest mark a learner has achieved + * getHighestMark(HttpServletRequest request, Long queUsrId) + * + * @param request + * @param queUsrId + * @return + */ + public static int getHighestMark(HttpServletRequest request, Long queUsrId) + { + IMcService mcService =McUtils.getToolService(request); + List listMarks=mcService.getHighestMark(queUsrId); + + Iterator itMarks=listMarks.iterator(); + int highestMark=0; + while (itMarks.hasNext()) + { + McUsrAttempt mcUsrAttempt=(McUsrAttempt)itMarks.next(); + int currentMark=mcUsrAttempt.getMark().intValue(); + if (currentMark > highestMark) + highestMark= currentMark; + } + return highestMark; + } + + /** + * return the top mark for all learners + * getTopMark(HttpServletRequest request) + * + * @param request + * @return + */ + public static int getTopMark(HttpServletRequest request) + { + IMcService mcService =McUtils.getToolService(request); + List listMarks=mcService.getMarks(); + + Iterator itMarks=listMarks.iterator(); + int highestMark=0; + while (itMarks.hasNext()) + { + McUsrAttempt mcUsrAttempt=(McUsrAttempt)itMarks.next(); + int currentMark=mcUsrAttempt.getMark().intValue(); + if (currentMark > highestMark) + highestMark= currentMark; + } + return highestMark; + } + + + /** + * return the lowest mark for all learners + * getTopMark(HttpServletRequest request) + * + * @param request + * @return + */ + public static int getLowestMark(HttpServletRequest request) + { + IMcService mcService =McUtils.getToolService(request); + List listMarks=mcService.getMarks(); + + Iterator itMarks=listMarks.iterator(); + int lowestMark=100; + while (itMarks.hasNext()) + { + McUsrAttempt mcUsrAttempt=(McUsrAttempt)itMarks.next(); + int currentMark=mcUsrAttempt.getMark().intValue(); + if (currentMark < lowestMark) + lowestMark= currentMark; + } + return lowestMark; + } + + /** + * return the average mark for all learners + * getTopMark(HttpServletRequest request) + * + * @param request + * @return + */ + public static int getAverageMark(HttpServletRequest request) + { + IMcService mcService =McUtils.getToolService(request); + List listMarks=mcService.getMarks(); + + Iterator itMarks=listMarks.iterator(); + int marksTotal=0; + int count=0; + while (itMarks.hasNext()) + { + McUsrAttempt mcUsrAttempt=(McUsrAttempt)itMarks.next(); + int currentMark=mcUsrAttempt.getMark().intValue(); + marksTotal=marksTotal + currentMark; + count++; + } + logger.debug("marksTotal: " + marksTotal); + logger.debug("count: " + count); + + int averageMark= (marksTotal / count); + logger.debug("averageMark: " + averageMark); + return averageMark; + } + + + public static Map buildMapCorrectOptions(List correctOptions) + { + Map mapCorrectOptions= new TreeMap(new McComparator()); + Iterator correctOptionsIterator=correctOptions.iterator(); + Long mapIndex=new Long(1); + while (correctOptionsIterator.hasNext()) + { + McOptsContent mcOptsContent=(McOptsContent)correctOptionsIterator.next(); + if (mcOptsContent != null) + { + mapCorrectOptions.put(mapIndex.toString(),mcOptsContent.getMcQueOptionText()); + mapIndex=new Long(mapIndex.longValue()+1); + } + } + logger.debug("mapCorrectOptions : " + mapCorrectOptions); + return mapCorrectOptions; + } + + + public static Map compare(Map mapGeneralCorrectOptions,Map mapGeneralCheckedOptionsContent) + { + logger.debug("incoming mapGeneralCorrectOptions : " + mapGeneralCorrectOptions); + logger.debug("incoming mapGeneralCheckedOptionsContent : " + mapGeneralCheckedOptionsContent); + + Map mapLeanerAssessmentResults= new TreeMap(new McComparator()); + + Iterator itMap = mapGeneralCorrectOptions.entrySet().iterator(); + boolean compareResult= false; + while (itMap.hasNext()) { + compareResult= false; + Map.Entry pairs = (Map.Entry)itMap.next(); + + Iterator itCheckedMap = mapGeneralCheckedOptionsContent.entrySet().iterator(); + while (itCheckedMap.hasNext()) + { + compareResult= false; + Map.Entry checkedPairs = (Map.Entry)itCheckedMap.next(); + if (pairs.getKey().toString().equals(checkedPairs.getKey().toString())) + { + Map mapCorrectOptions=(Map) pairs.getValue(); + Map mapCheckedOptions=(Map) checkedPairs.getValue(); + + boolean isEqual=compareMaps(mapCorrectOptions, mapCheckedOptions); + boolean isEqualCross=compareMapsCross(mapCorrectOptions, mapCheckedOptions); + + compareResult= isEqual && isEqualCross; + mapLeanerAssessmentResults.put(pairs.getKey(), new Boolean(compareResult).toString()); + } + } + } + logger.debug("constructed mapLeanerAssessmentResults: " + mapLeanerAssessmentResults); + return mapLeanerAssessmentResults; + } + + + public static boolean compareMaps(Map mapCorrectOptions, Map mapCheckedOptions) + { + logger.debug("mapCorrectOptions: " + mapCorrectOptions); + logger.debug("mapCheckedOptions: " + mapCheckedOptions); + + Iterator itMap = mapCorrectOptions.entrySet().iterator(); + boolean response=false; + while (itMap.hasNext()) + { + Map.Entry pairs = (Map.Entry)itMap.next(); + boolean optionExists=optionExists(pairs.getValue().toString(), mapCheckedOptions); + + if (optionExists == false) + { + return false; + } + } + return true; + } + + + public static boolean compareMapsCross(Map mapCorrectOptions, Map mapCheckedOptions) + { + logger.debug("mapCorrectOptions: " + mapCorrectOptions); + logger.debug("mapCheckedOptions: " + mapCheckedOptions); + + Iterator itMap = mapCheckedOptions.entrySet().iterator(); + boolean response=false; + while (itMap.hasNext()) + { + Map.Entry pairs = (Map.Entry)itMap.next(); + boolean optionExists=optionExists(pairs.getValue().toString(), mapCorrectOptions); + + if (optionExists == false) + { + return false; + } + } + return true; + } + + + public static boolean optionExists(String optionValue, Map generalMap) + { + Iterator itMap = generalMap.entrySet().iterator(); + while (itMap.hasNext()) + { + Map.Entry pairsChecked = (Map.Entry)itMap.next(); + if (pairsChecked.getValue().equals(optionValue)) + return true; + } + return false; + } + + + /** + * creates the user in the db + * createUser(HttpServletRequest request) + * + * @param request + */ + public static void createUser(HttpServletRequest request) + { + IMcService mcService =McUtils.getToolService(request); + Long queUsrId=McUtils.getUserId(); + String username=McUtils.getUserName(); + String fullname=McUtils.getUserFullName(); + Long toolSessionId=(Long) request.getSession().getAttribute(TOOL_SESSION_ID); + + McSession mcSession=mcService.retrieveMcSession(toolSessionId); + McQueUsr mcQueUsr= new McQueUsr(queUsrId, + username, + fullname, + mcSession, + new TreeSet()); + mcService.createMcQueUsr(mcQueUsr); + logger.debug("created mcQueUsr in the db: " + mcQueUsr); + } + + + /** + * checks if the user is in the db + * doesUserExists(HttpServletRequest request) + * + * @param request + */ + public static boolean doesUserExists(HttpServletRequest request) + { + IMcService mcService =McUtils.getToolService(request); + Long queUsrId=McUtils.getUserId(); + McQueUsr mcQueUsr=mcService.retrieveMcQueUsr(queUsrId); + + if (mcQueUsr != null) + return true; + + return false; + } + + + public static McQueUsr getUser(HttpServletRequest request) + { + IMcService mcService =McUtils.getToolService(request); + Long queUsrId=McUtils.getUserId(); + McQueUsr mcQueUsr=mcService.retrieveMcQueUsr(queUsrId); + return mcQueUsr; + } + + + /** + * creates a user attempt in the db + * createAttempt(HttpServletRequest request) + * + * @param request + */ + public static void createAttempt(HttpServletRequest request, McQueUsr mcQueUsr, Map mapGeneralCheckedOptionsContent, int mark, boolean passed, int highestAttemptOrder, Map mapLeanerAssessmentResults) + { + IMcService mcService =McUtils.getToolService(request); + Date attempTime=McUtils.getGMTDateTime(); + String timeZone= McUtils.getCurrentTimeZone(); + logger.debug("timeZone: " + timeZone); + + Long toolContentUID= (Long) request.getSession().getAttribute(TOOL_CONTENT_UID); + logger.debug("toolContentUID: " + toolContentUID); + + Iterator itCheckedMap = mapGeneralCheckedOptionsContent.entrySet().iterator(); + while (itCheckedMap.hasNext()) + { + Map.Entry checkedPairs = (Map.Entry)itCheckedMap.next(); + Map mapCheckedOptions=(Map) checkedPairs.getValue(); + Long questionDisplayOrder=new Long(checkedPairs.getKey().toString()); + + logger.debug("questionDisplayOrder: " + questionDisplayOrder); + String isAttemptCorrect=(String)mapLeanerAssessmentResults.get(questionDisplayOrder.toString()); + logger.debug("isAttemptCorrect: " + isAttemptCorrect); + + McQueContent mcQueContent=mcService.getQuestionContentByDisplayOrder(questionDisplayOrder, toolContentUID); + createIndividualOptions(request, mapCheckedOptions, mcQueContent, mcQueUsr, attempTime, timeZone, mark, passed, new Integer(highestAttemptOrder), isAttemptCorrect); + } + } + + + public static void createIndividualOptions(HttpServletRequest request, Map mapCheckedOptions, McQueContent mcQueContent, McQueUsr mcQueUsr, Date attempTime, String timeZone, int mark, boolean passed, Integer highestAttemptOrder, String isAttemptCorrect) + { + IMcService mcService =McUtils.getToolService(request); + Integer IntegerMark= new Integer(mark); + + logger.debug("createIndividualOptions-> isAttemptCorrect: " + isAttemptCorrect); + + Iterator itCheckedMap = mapCheckedOptions.entrySet().iterator(); + while (itCheckedMap.hasNext()) + { + Map.Entry checkedPairs = (Map.Entry)itCheckedMap.next(); + McOptsContent mcOptsContent= mcService.getOptionContentByOptionText(checkedPairs.getValue().toString(), mcQueContent.getUid()); + McUsrAttempt mcUsrAttempt=new McUsrAttempt(attempTime, timeZone, mcQueContent, mcQueUsr, mcOptsContent, IntegerMark, passed, highestAttemptOrder, new Boolean(isAttemptCorrect).booleanValue()); + mcService.createMcUsrAttempt(mcUsrAttempt); + logger.debug("created mcUsrAttempt in the db :" + mcUsrAttempt); + } + } + + + public static Map buildWeightsMap(HttpServletRequest request, Long toolContentId) + { + IMcService mcService =McUtils.getToolService(request); + Map mapWeights= new TreeMap(new McComparator()); + McContent mcContent=mcService.retrieveMc(toolContentId); + + List questionsContent=mcService.refreshQuestionContent(mcContent.getUid()); + + Iterator listIterator=questionsContent.iterator(); + Long mapIndex=new Long(1); + while (listIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)listIterator.next(); + mapWeights.put(mapIndex.toString(),mcQueContent.getWeight().toString()); + mapIndex=new Long(mapIndex.longValue()+1); + } + return mapWeights; + } + } Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McAction.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McAction.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McAction.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,2319 @@ +/* *Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * + *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; either version 2 of the License, or + *(at your option) any later version. + * + *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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + *USA + * + *http://www.gnu.org/licenses/gpl.txt + */ +package org.lamsfoundation.lams.tool.mc.web; + +import java.io.DataInputStream; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; +import org.apache.struts.Globals; +import org.apache.struts.action.ActionForm; +import org.apache.struts.action.ActionForward; +import org.apache.struts.action.ActionMapping; +import org.apache.struts.action.ActionMessage; +import org.apache.struts.action.ActionMessages; +import org.apache.struts.actions.DispatchAction; +import org.lamsfoundation.lams.tool.mc.McAppConstants; +import org.lamsfoundation.lams.tool.mc.McApplicationException; +import org.lamsfoundation.lams.tool.mc.McComparator; +import org.lamsfoundation.lams.tool.mc.McContent; +import org.lamsfoundation.lams.tool.mc.McOptsContent; +import org.lamsfoundation.lams.tool.mc.McQueContent; +import org.lamsfoundation.lams.tool.mc.McQueUsr; +import org.lamsfoundation.lams.tool.mc.McUsrAttempt; +import org.lamsfoundation.lams.tool.mc.McUtils; +import org.lamsfoundation.lams.tool.mc.service.IMcService; + +/** + * * @author Ozgur Demirtas + * + *

Action class that controls the logic of tool behavior.

+ * + *

Note that Struts action class only has the responsibility to navigate + * page flow. All database operation should go to service layer and data + * transformation from domain model to struts form bean should go to form + * bean class. This ensure clean and maintainable code. + *

+ * + * SystemException is thrown whenever an known error condition is + * identified. No system exception error handling code should appear in the + * Struts action class as all of them are handled in + * CustomStrutsExceptionHandler. + * + + + + + + + + + + + +*/ +public class McAction extends DispatchAction implements McAppConstants +{ + /* + * change the logic about completion status + + * once lams_learning is ready and appContext file is src/ then FINISH toool session will work. + * + * when to reset define later and synchin monitor etc.. + * + * make sure the tool gets called on: + * setAsForceComplete(Long userId) throws McApplicationException + * + * Note: the tool must support deletion of an existing content from within the authoring environment. + * The current support for this is by implementing the tool contract : removeToolContent(Long toolContentId) + */ + static Logger logger = Logger.getLogger(McAction.class.getName()); + + /** + *

Struts dispatch method.

+ * + *

It is assuming that progress engine should pass in the tool access + * mode and the tool session id as http parameters.

+ * + * @param mapping An ActionMapping class that will be used by the Action class to tell + * the ActionServlet where to send the end-user. + * + * @param form The ActionForm class that will contain any data submitted + * by the end-user via a form. + * @param request A standard Servlet HttpServletRequest class. + * @param response A standard Servlet HttpServletResponse class. + * @return An ActionForward class that will be returned to the ActionServlet indicating where + * the user is to go next. + * @throws IOException + * @throws ServletException + * @throws McApplicationException the known runtime exception + * + * loadQ(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + + * main content/question content management and workflow logic + * + * if the passed toolContentId exists in the db, we need to get the relevant data into the Map + * if not, create the default Map + */ + public ActionForward loadQ(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + /** define the next tab as Basic tab by default*/ + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("resetting EDIT_OPTIONS_MODE to 0"); + + McUtils.persistRichText(request); + AuthoringUtil.populateParameters(request, mcAuthoringForm); + + String userAction=null; + if (mcAuthoringForm.getAddQuestion() != null) + { + return addNewQuestion(mapping, form, request, response); + } + else if (mcAuthoringForm.getRemoveQuestion() != null) + { + return removeQuestion(mapping, form, request, response); + } + else if (mcAuthoringForm.getEditOptions() != null) + { + return editOptions(mapping, form, request, response); + } + else if (mcAuthoringForm.getMoveDown() != null) + { + return moveQuestionDown(mapping, form, request, response); + } + else if (mcAuthoringForm.getMoveUp() != null) + { + return moveQuestionUp(mapping, form, request, response); + } + else if (mcAuthoringForm.getAddOption() != null) + { + return addOption(mapping, form, request, response); + } + else if (mcAuthoringForm.getRemoveOption() != null) + { + return removeOption(mapping, form, request, response); + } + else if (mcAuthoringForm.getDoneOptions() != null) + { + return doneOptions(mapping, form, request, response); + } + else if (mcAuthoringForm.getSubmitQuestions() != null) + { + return submitQuestions(mapping, form, request, response); + } + else if (mcAuthoringForm.getAdvancedTabDone() != null) + { + return doneAdvancedTab(mapping, form, request, response); + } + else if (mcAuthoringForm.getInstructionsTabDone() != null) + { + return doneInstructionsTab(mapping, form, request, response); + } + else if (mcAuthoringForm.getSubmitOfflineFile() != null) + { + return submitOfflineFiles(mapping, form, request, response); + } + else if (mcAuthoringForm.getSubmitOnlineFile() != null) + { + return submitOnlineFiles(mapping, form, request, response); + } + else if (mcAuthoringForm.getViewFileItem() != null) + { + return viewFileItem(mapping, form, request, response); + } + + mcAuthoringForm.resetUserAction(); + return null; + } + + + /** + * adds a new entry to the questions Map + * + * addNewQuestion(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward addNewQuestion(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching addNewQuestion..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="addQuestion"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + Map mapQuestionsContent=AuthoringUtil.repopulateMap(request, "questionContent"); + logger.debug("mapQuestionsContent after shrinking: " + mapQuestionsContent); + logger.debug("mapQuestionsContent size after shrinking: " + mapQuestionsContent.size()); + + logger.debug("will validate questions are not empty"); + boolean questionsNotEmptyValid=AuthoringUtil.validateQuestionsNotEmpty(mapQuestionsContent); + logger.debug("questionsNotEmptyValid:" + questionsNotEmptyValid); + + if (questionsNotEmptyValid == false) + { + ActionMessages errors= new ActionMessages(); + errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.question.empty")); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + persistError(request,"error.question.empty"); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + + mcAuthoringForm.setAddQuestion(null); + mcAuthoringForm.setSubmitQuestions(null); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + logger.debug("will validate weights"); + Map mapWeights= AuthoringUtil.repopulateCurrentWeightsMap(request, "questionWeight"); + logger.debug("mapWeights: " + mapWeights); + + boolean weightsValid=validateQuestionWeights(request,mapWeights, mcAuthoringForm); + logger.debug("weightsValid:" + weightsValid); + if (weightsValid == false) + { + mcAuthoringForm.resetUserAction(); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + + mcAuthoringForm.setAddQuestion(null); + mcAuthoringForm.setSubmitQuestions(null); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + logger.debug("will validate SubTotalWeights"); + boolean subWeightsValid=AuthoringUtil.validateSubTotalWeights(request,mcAuthoringForm); + logger.debug("subWeightsValid:" + subWeightsValid); + if (subWeightsValid == false) + { + ActionMessages errors= new ActionMessages(); + errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.question.weight.total")); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + persistError(request,"error.question.weight.total"); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + + mcAuthoringForm.setAddQuestion(null); + mcAuthoringForm.setSubmitQuestions(null); + return (mapping.findForward(LOAD_QUESTIONS)); + } + request.getSession().setAttribute(MAP_WEIGHTS, mapWeights); + logger.debug("MAP_WEIGHTS:" + request.getSession().getAttribute(MAP_WEIGHTS)); + + AuthoringUtil.addQuestionMemory(request, mcAuthoringForm, mapQuestionsContent, true); + logger.debug("after addQuestionMemory"); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("resetting EDIT_OPTIONS_MODE to 0"); + mcAuthoringForm.resetUserAction(); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + + mcAuthoringForm.setAddQuestion(null); + mcAuthoringForm.setSubmitQuestions(null); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + /** + * removes an entry from the questions Map + removeQuestion(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * removeQuestion(HttpServletRequest request, McAuthoringForm mcAuthoringForm, ActionMapping mapping) + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward removeQuestion(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching removeQuestion..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="removeQuestion"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + Map mapWeights= AuthoringUtil.repopulateMap(request, "questionWeight"); + request.getSession().setAttribute(MAP_WEIGHTS, mapWeights); + logger.debug("MAP_WEIGHTS:" + request.getSession().getAttribute(MAP_WEIGHTS)); + + Map mapQuestionsContent=AuthoringUtil.repopulateMap(request, "questionContent"); + logger.debug("mapQuestionsContent after shrinking: " + mapQuestionsContent); + logger.debug("mapQuestionsContent size after shrinking: " + mapQuestionsContent.size()); + + String questionIndex =mcAuthoringForm.getQuestionIndex(); + logger.debug("questionIndex:" + questionIndex); + String deletableQuestionEntry=(String)mapQuestionsContent.get(questionIndex); + logger.debug("deletableQuestionEntry:" + deletableQuestionEntry); + + if (deletableQuestionEntry != null) + { + if (!(deletableQuestionEntry.equals(""))) + { + mapQuestionsContent.remove(questionIndex); + logger.debug("removed entry:" + deletableQuestionEntry + " from the Map"); + request.getSession().setAttribute(MAP_QUESTIONS_CONTENT, mapQuestionsContent); + logger.debug("updated Questions Map: " + request.getSession().getAttribute(MAP_QUESTIONS_CONTENT)); + } + } + else + { + request.getSession().setAttribute(MAP_QUESTIONS_CONTENT, mapQuestionsContent); + logger.debug("updated Questions Map: " + request.getSession().getAttribute(MAP_QUESTIONS_CONTENT)); + } + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("resetting EDIT_OPTIONS_MODE to 0"); + mcAuthoringForm.resetUserAction(); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + /** + * prepares the UI so that candidate answers for a question can be edited + * editOptions(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward editOptions(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching editOptions..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="editOption"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + Map mapGeneralOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_OPTIONS_CONTENT); + logger.debug("initial test: current mapGeneralOptionsContent: " + mapGeneralOptionsContent); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(1)); + logger.debug("setting EDIT_OPTIONS_MODE to 1"); + + Map mapQuestionsContent=AuthoringUtil.repopulateMap(request, "questionContent"); + logger.debug("mapQuestionsContent after shrinking: " + mapQuestionsContent); + logger.debug("mapQuestionsContent size after shrinking: " + mapQuestionsContent.size()); + request.getSession().setAttribute(MAP_QUESTIONS_CONTENT, mapQuestionsContent); + + Map mapWeights= AuthoringUtil.repopulateMap(request, "questionWeight"); + request.getSession().setAttribute(MAP_WEIGHTS, mapWeights); + logger.debug("MAP_WEIGHTS:" + request.getSession().getAttribute(MAP_WEIGHTS)); + + String questionIndex =mcAuthoringForm.getQuestionIndex(); + logger.debug("questionIndex:" + questionIndex); + request.getSession().setAttribute(SELECTED_QUESTION_INDEX, questionIndex); + logger.debug("set SELECTED_QUESTION_INDEX to:" + questionIndex); + + String editableQuestionEntry=(String)mapQuestionsContent.get(questionIndex); + logger.debug("editableQuestionEntry:" + editableQuestionEntry); + request.getSession().setAttribute(SELECTED_QUESTION, editableQuestionEntry); + + if ((editableQuestionEntry == null) || (editableQuestionEntry.equals(""))) + { + ActionMessages errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.emptyQuestion")); + logger.debug("add error.emptyQuestion to ActionMessages"); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + logger.debug("return to LOAD_QUESTIONS to fix error."); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("setting EDIT_OPTIONS_MODE to 0"); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + Long toolContentId=(Long)request.getSession().getAttribute(TOOL_CONTENT_ID); + logger.debug("toolContentId:" + toolContentId); + + String selectedQuestionIndex=(String) request.getSession().getAttribute(SELECTED_QUESTION_INDEX); + logger.debug("SELECTED_QUESTION_INDEX to:" + selectedQuestionIndex); + + logger.debug("mapGeneralOptionsContent to be checked: " + mapGeneralOptionsContent); + Iterator itMapGeneral = mapGeneralOptionsContent.entrySet().iterator(); + boolean optionsPresentationValid=false; + + Map mapOptionsContent= new TreeMap(new McComparator()); + Map mapSelectedOptions= new TreeMap(new McComparator()); + Map mapGsoc=(Map)request.getSession().getAttribute(MAP_GENERAL_SELECTED_OPTIONS_CONTENT); + logger.debug("mapGsoc from the cache: " + mapGsoc); + + /* extract the relavent question's option from the larger Map */ + boolean optionsCacheDataFound=false; + while (itMapGeneral.hasNext()) + { + optionsCacheDataFound=false; + Map.Entry pairs = (Map.Entry)itMapGeneral.next(); + logger.debug("using the pair: " + pairs); + logger.debug("using the pair entries: " + pairs.getKey() + " = " + pairs.getValue()); + + if ((pairs.getKey() != null)) + { + if (pairs.getKey().equals(selectedQuestionIndex)) + { + logger.debug("question found with options in the cache"); + mapOptionsContent=(Map) pairs.getValue(); + logger.debug("mapOptionsContent from the cache: " + mapOptionsContent); + request.getSession().setAttribute(MAP_OPTIONS_CONTENT, mapOptionsContent); + logger.debug("updated MAP_OPTIONS_CONTENT: " + mapOptionsContent); + + logger.debug("mapGsoc: " + mapGsoc); + Iterator itMapSelected = mapGsoc.entrySet().iterator(); + + while (itMapSelected.hasNext()) { + + Map.Entry spairs = (Map.Entry)itMapSelected.next(); + logger.debug("using the spairs entries: " + spairs.getKey() + " = " + spairs.getValue()); + + if ((spairs.getKey() != null)) + { + if (spairs.getKey().equals(selectedQuestionIndex)) + { + logger.debug("selected options for question found in the cache"); + + mapSelectedOptions=(Map) spairs.getValue(); + logger.debug("mapSelectedOptionsContent from the cache: " + mapSelectedOptions); + request.getSession().setAttribute(MAP_SELECTED_OPTIONS, mapSelectedOptions); + logger.debug("updated MAP_SELECTED_OPTIONS: " + mapSelectedOptions); + } + } + } + optionsCacheDataFound=true; + break; + } + } + } + + logger.debug("optionsCacheDataFound to be checked: " + optionsCacheDataFound); + if (optionsCacheDataFound == true) + { + Map mapFeedbackIncorrect =(Map)request.getSession().getAttribute(MAP_FEEDBACK_INCORRECT); + logger.debug("cached MAP_FEEDBACK_INCORRECT :" + mapFeedbackIncorrect); + if (mapFeedbackIncorrect != null) + { + String richTextFeedbackInCorrect=(String)mapFeedbackIncorrect.get(selectedQuestionIndex); + logger.debug("cached richTextFeedbackInCorrect:" + richTextFeedbackInCorrect); + request.getSession().setAttribute(RICHTEXT_FEEDBACK_INCORRECT,richTextFeedbackInCorrect); + } + else + { + logger.debug("mapFeedbackIncorrect is null"); + request.getSession().setAttribute(RICHTEXT_FEEDBACK_INCORRECT,""); + } + + Map mapFeedbackCorrect =(Map)request.getSession().getAttribute(MAP_FEEDBACK_CORRECT); + logger.debug("Submit final MAP_FEEDBACK_CORRECT :" + mapFeedbackCorrect); + if (mapFeedbackCorrect != null) + { + String richTextFeedbackCorrect=(String)mapFeedbackCorrect.get(selectedQuestionIndex); + logger.debug("cached richTextFeedbackCorrect:" + richTextFeedbackCorrect); + request.getSession().setAttribute(RICHTEXT_FEEDBACK_CORRECT,richTextFeedbackCorrect); + } + else + { + logger.debug("mapFeedbackCorrect is null"); + request.getSession().setAttribute(RICHTEXT_FEEDBACK_CORRECT,""); + } + } + else + { + McContent mcContent=mcService.retrieveMc(toolContentId); + logger.debug("mcContent:" + mcContent); + + McQueContent mcQueContent=null; + if (mcContent != null) + { + logger.debug("mcContent is not null"); + mcQueContent=mcService.getQuestionContentByQuestionText(editableQuestionEntry, mcContent.getUid()); + logger.debug("mcQueContent:" + mcQueContent); + } + + if (mcQueContent != null) + { + logger.debug("mcQueContent is not null " + mcQueContent.getUid()); + List listOptionsContent=mcService.findMcOptionsContentByQueId(mcQueContent.getUid()); + logger.debug("listOptionsContent: " + listOptionsContent); + + mapOptionsContent= new TreeMap(new McComparator()); + mapSelectedOptions= new TreeMap(new McComparator()); + + /* options have been persisted before */ + if (listOptionsContent != null) + { + logger.debug("listOptionsContent not null" ); + Iterator listIteratorOptions=listOptionsContent.iterator(); + Long mapIndex=new Long(1); + while (listIteratorOptions.hasNext()) + { + McOptsContent mcOptsContent=(McOptsContent)listIteratorOptions.next(); + logger.debug("option text:" + mcOptsContent.getMcQueOptionText()); + mapOptionsContent.put(mapIndex.toString(),mcOptsContent.getMcQueOptionText()); + mapIndex=new Long(mapIndex.longValue()+1); + } + request.getSession().setAttribute(MAP_OPTIONS_CONTENT, mapOptionsContent); + logger.debug("MAP_OPTIONS_CONTENT reconstructed from db" ); + + + /* we have to assume that some of the optons are selected as this is forced in the ui. + * retrieve and present the selected options from the db + * */ + List listSelectedOptions=mcService.getPersistedSelectedOptions(mcQueContent.getUid()); + logger.debug("listSelectedOptions:" + listSelectedOptions); + + if (listSelectedOptions != null) + { + Iterator listIteratorSelectedOptions=listSelectedOptions.iterator(); + mapIndex=new Long(1); + while (listIteratorSelectedOptions.hasNext()) + { + McOptsContent mcOptsContent=(McOptsContent)listIteratorSelectedOptions.next(); + logger.debug("option text:" + mcOptsContent.getMcQueOptionText()); + mapSelectedOptions.put(mapIndex.toString(),mcOptsContent.getMcQueOptionText()); + mapIndex=new Long(mapIndex.longValue()+1); + } + } + request.getSession().setAttribute(MAP_SELECTED_OPTIONS, mapSelectedOptions); + logger.debug("MAP_SELECTED_OPTIONS reconstructed from db:" + mapSelectedOptions); + } + else + { + logger.debug("listOptionsContent is null: no options persisted yet" ); + logger.debug("present default options content" ); + Long queContentUID=(Long)request.getSession().getAttribute(DEFAULT_QUESTION_UID); + logger.debug("DEFAULT_QUESTION_UID: " + queContentUID); + List listDefaultOption=mcService.findMcOptionsContentByQueId(queContentUID); + logger.debug("listDefaultOption: " + listDefaultOption); + + /** normally iterates only once */ + Iterator itDefaultOption=listDefaultOption.iterator(); + Long mapIndex=new Long(1); + while (itDefaultOption.hasNext()) + { + McOptsContent mcOptsContent=(McOptsContent)itDefaultOption.next(); + logger.debug("option text:" + mcOptsContent.getMcQueOptionText()); + mapOptionsContent.put(mapIndex.toString(),mcOptsContent.getMcQueOptionText()); + mapIndex=new Long(mapIndex.longValue()+1); + } + logger.debug("mapOptionsContent from default content: " + mapOptionsContent); + request.getSession().setAttribute(MAP_OPTIONS_CONTENT, mapOptionsContent); + logger.debug("MAP_OPTIONS_CONTENT reconstructed from default option content" ); + + request.getSession().setAttribute(MAP_SELECTED_OPTIONS, mapSelectedOptions); + logger.debug("MAP_SELECTED_OPTIONS set as empty list :" + mapSelectedOptions); + } + + /* present the feedback content the same way for the conditions above*/ + String richTextFeedbackInCorrect=mcQueContent.getFeedbackIncorrect(); + logger.debug("richTextFeedbackInCorrect: " + richTextFeedbackInCorrect); + if (richTextFeedbackInCorrect == null) richTextFeedbackInCorrect=""; + request.getSession().setAttribute(RICHTEXT_FEEDBACK_INCORRECT,richTextFeedbackInCorrect); + + String richTextFeedbackCorrect=mcQueContent.getFeedbackCorrect(); + logger.debug("richTextFeedbackCorrect: " + richTextFeedbackCorrect); + if (richTextFeedbackCorrect == null) richTextFeedbackCorrect=""; + request.getSession().setAttribute(RICHTEXT_FEEDBACK_CORRECT,richTextFeedbackCorrect); + } + else + { + logger.debug("mcQueContent is null " + mcQueContent); + logger.debug("optionsPresentationValid is false, present default content"); + logger.debug("listOptionsContent is null: no options persisted yet" ); + logger.debug("present default options content" ); + Long queContentUID=(Long)request.getSession().getAttribute(DEFAULT_QUESTION_UID); + logger.debug("DEFAULT_QUESTION_UID: " + queContentUID); + List listDefaultOption=mcService.findMcOptionsContentByQueId(queContentUID); + logger.debug("listDefaultOption: " + listDefaultOption); + + /* normally iterates only once */ + Iterator itDefaultOption=listDefaultOption.iterator(); + Long mapIndex=new Long(1); + while (itDefaultOption.hasNext()) + { + McOptsContent mcOptsContent=(McOptsContent)itDefaultOption.next(); + logger.debug("option text:" + mcOptsContent.getMcQueOptionText()); + mapOptionsContent.put(mapIndex.toString(),mcOptsContent.getMcQueOptionText()); + mapIndex=new Long(mapIndex.longValue()+1); + } + logger.debug("mapOptionsContent from default content: " + mapOptionsContent); + request.getSession().setAttribute(MAP_OPTIONS_CONTENT, mapOptionsContent); + logger.debug("MAP_OPTIONS_CONTENT reconstructed from default option content" ); + + request.getSession().setAttribute(MAP_SELECTED_OPTIONS, mapSelectedOptions); + logger.debug("MAP_SELECTED_OPTIONS set as empty list :" + mapSelectedOptions); + } + } + + logger.debug("final mapOptionsContent used is: " + mapOptionsContent); + if (mapOptionsContent.isEmpty()) + { + logger.debug("mapOptionsContent is empty"); + mapOptionsContent.put("1","sample answer 1"); + mapSelectedOptions = mapOptionsContent; + request.getSession().setAttribute(MAP_OPTIONS_CONTENT, mapOptionsContent); + request.getSession().setAttribute(MAP_SELECTED_OPTIONS, mapSelectedOptions); + + + mapGeneralOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_OPTIONS_CONTENT); + logger.debug("current mapGeneralOptionsContent:"+ mapGeneralOptionsContent); + mapGeneralOptionsContent.put(questionIndex,mapOptionsContent); + request.getSession().setAttribute(MAP_GENERAL_OPTIONS_CONTENT, mapGeneralOptionsContent); + + Map mapGeneralSelectedOptionsContent=mapGeneralOptionsContent; + request.getSession().setAttribute(MAP_GENERAL_SELECTED_OPTIONS_CONTENT, mapGeneralSelectedOptionsContent); + } + + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(1)); + logger.debug("resetting EDIT_OPTIONS_MODE to 1"); + mcAuthoringForm.resetUserAction(); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + /** + * adds an option entry to the options Map + * addOption(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward addOption(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching addOption..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="addOption"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(1)); + logger.debug("setting EDIT_OPTIONS_MODE to 1"); + + Map mapOptionsContent=AuthoringUtil.repopulateMap(request,"optionContent"); + logger.debug("mapOptionsContent after shrinking: " + mapOptionsContent); + logger.debug("mapOptionsContent size after shrinking: " + mapOptionsContent.size()); + + boolean verifyDuplicatesOptionsMap=AuthoringUtil.verifyDuplicatesOptionsMap(mapOptionsContent); + logger.debug("verifyDuplicatesOptionsMap: " + verifyDuplicatesOptionsMap); + if (verifyDuplicatesOptionsMap == false) + { + ActionMessages errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.answers.duplicate")); + logger.debug("add error.answers.duplicate to ActionMessages"); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + logger.debug("return to LOAD_QUESTIONS to fix error."); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(1)); + logger.debug("setting EDIT_OPTIONS_MODE to 1"); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + String selectedQuestionIndex=(String)request.getSession().getAttribute(SELECTED_QUESTION_INDEX); + logger.debug("selectedQuestionIndex:" + selectedQuestionIndex); + + int mapSize=mapOptionsContent.size(); + mapOptionsContent.put(new Long(++mapSize).toString(), ""); + logger.debug("updated mapOptionsContent Map size: " + mapOptionsContent.size()); + request.getSession().setAttribute(MAP_OPTIONS_CONTENT, mapOptionsContent); + logger.debug("updated Options Map: " + request.getSession().getAttribute(MAP_OPTIONS_CONTENT)); + + + Map mapGeneralOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_OPTIONS_CONTENT); + logger.debug("current mapGeneralOptionsContent: " + mapGeneralOptionsContent); + mapGeneralOptionsContent.put(selectedQuestionIndex,mapOptionsContent); + request.getSession().setAttribute(MAP_GENERAL_OPTIONS_CONTENT, mapGeneralOptionsContent); + logger.debug("updated MAP_GENERAL_OPTIONS_CONTENT after add: " + mapGeneralOptionsContent); + + + Map mapSelectedOptions= (Map) request.getSession().getAttribute(MAP_SELECTED_OPTIONS); + mapSelectedOptions.clear(); + mapSelectedOptions = AuthoringUtil.repopulateCurrentCheckBoxStatesMap(request); + logger.debug("after add mapSelectedOptions: " + mapSelectedOptions); + request.getSession().setAttribute(MAP_SELECTED_OPTIONS, mapSelectedOptions); + + Map mapGeneralSelectedOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_SELECTED_OPTIONS_CONTENT); + logger.debug("current mapGeneralSelectedOptionsContent: " + mapGeneralSelectedOptionsContent); + mapGeneralSelectedOptionsContent.put(selectedQuestionIndex,mapSelectedOptions); + request.getSession().setAttribute(MAP_GENERAL_SELECTED_OPTIONS_CONTENT, mapGeneralSelectedOptionsContent); + logger.debug("updated MAP_GENERAL_SELECTED_OPTIONS_CONTENT after add: " + mapGeneralSelectedOptionsContent); + + /* update feedback Maps*/ + Map mapFeedbackIncorrect =(Map)request.getSession().getAttribute(MAP_FEEDBACK_INCORRECT); + logger.debug("current mapFeedbackIncorrect:" + mapFeedbackIncorrect); + String richTextFeedbackInCorrect=(String) request.getSession().getAttribute(RICHTEXT_FEEDBACK_INCORRECT); + logger.debug("richTextFeedbackInCorrect: " + richTextFeedbackInCorrect); + + if (richTextFeedbackInCorrect == null) richTextFeedbackInCorrect=""; + mapFeedbackIncorrect.put(selectedQuestionIndex, richTextFeedbackInCorrect); + request.getSession().setAttribute(MAP_FEEDBACK_INCORRECT, mapFeedbackIncorrect); + logger.debug("updated MAP_FEEDBACK_INCORRECT:" + mapFeedbackIncorrect); + + Map mapFeedbackCorrect =(Map)request.getSession().getAttribute(MAP_FEEDBACK_CORRECT); + logger.debug("current mapFeedbackCorrect:" + mapFeedbackCorrect); + String richTextFeedbackCorrect=(String) request.getSession().getAttribute(RICHTEXT_FEEDBACK_CORRECT); + logger.debug("richTextFeedbackCorrect: " + richTextFeedbackCorrect); + + if (richTextFeedbackCorrect == null) richTextFeedbackCorrect=""; + mapFeedbackCorrect.put(selectedQuestionIndex, richTextFeedbackCorrect); + request.getSession().setAttribute(MAP_FEEDBACK_CORRECT, mapFeedbackCorrect); + logger.debug("updated MAP_FEEDBACK_INCORRECT:" + mapFeedbackCorrect); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(1)); + logger.debug("resetting EDIT_OPTIONS_MODE to 1"); + mcAuthoringForm.resetUserAction(); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + /** + * removes an option entry from the options Map + * removeOption(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward removeOption(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching removeOption..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="removeOption"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(1)); + logger.debug("setting EDIT_OPTIONS_MODE to 1"); + + String optionIndex =mcAuthoringForm.getDeletableOptionIndex(); + logger.debug("optionIndex:" + optionIndex); + + Map mapOptionsContent=AuthoringUtil.repopulateMap(request, "optionContent"); + logger.debug("mapOptionsContent after shrinking: " + mapOptionsContent); + logger.debug("mapOptionsContent size after shrinking: " + mapOptionsContent.size()); + int mapSize=mapOptionsContent.size(); + if ((mapSize == 1) && (optionIndex.equals("1"))) + { + ActionMessages errors= new ActionMessages(); + errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("options.count.zero")); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + persistError(request,"options.count.zero"); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(1)); + logger.debug("setting EDIT_OPTIONS_MODE :" + 1); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + String deletableOptionEntry=(String)mapOptionsContent.get(optionIndex); + logger.debug("deletableOptionEntry:" + deletableOptionEntry); + + if (deletableOptionEntry != null) + { + if (!(deletableOptionEntry.equals(""))) + { + mapOptionsContent.remove(optionIndex); + logger.debug("removed entry:" + deletableOptionEntry + " from the Map"); + request.getSession().setAttribute(MAP_OPTIONS_CONTENT, mapOptionsContent); + logger.debug("updated Options Map: " + request.getSession().getAttribute(MAP_OPTIONS_CONTENT)); + } + } + + String selectedQuestionIndex=(String)request.getSession().getAttribute(SELECTED_QUESTION_INDEX); + logger.debug("selectedQuestionIndex:" + selectedQuestionIndex); + + Map mapGeneralOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_OPTIONS_CONTENT); + logger.debug("current mapGeneralOptionsContent: " + mapGeneralOptionsContent); + mapGeneralOptionsContent.put(selectedQuestionIndex,mapOptionsContent); + request.getSession().setAttribute(MAP_GENERAL_OPTIONS_CONTENT, mapGeneralOptionsContent); + logger.debug("updated MAP_GENERAL_OPTIONS_CONTENT after remove: " + mapGeneralOptionsContent); + + + Map mapSelectedOptions= (Map) request.getSession().getAttribute(MAP_SELECTED_OPTIONS); + mapSelectedOptions.clear(); + mapSelectedOptions = AuthoringUtil.repopulateCurrentCheckBoxStatesMap(request); + logger.debug("after add mapSelectedOptions: " + mapSelectedOptions); + request.getSession().setAttribute(MAP_SELECTED_OPTIONS, mapSelectedOptions); + + Map mapGeneralSelectedOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_SELECTED_OPTIONS_CONTENT); + logger.debug("current mapGeneralSelectedOptionsContent: " + mapGeneralSelectedOptionsContent); + mapGeneralSelectedOptionsContent.put(selectedQuestionIndex,mapSelectedOptions); + request.getSession().setAttribute(MAP_GENERAL_SELECTED_OPTIONS_CONTENT, mapGeneralSelectedOptionsContent); + logger.debug("updated MAP_GENERAL_SELECTED_OPTIONS_CONTENT after add: " + mapGeneralSelectedOptionsContent); + + /* update feedback Maps*/ + Map mapFeedbackIncorrect =(Map)request.getSession().getAttribute(MAP_FEEDBACK_INCORRECT); + logger.debug("current mapFeedbackIncorrect:" + mapFeedbackIncorrect); + String richTextFeedbackInCorrect=(String) request.getSession().getAttribute(RICHTEXT_FEEDBACK_INCORRECT); + logger.debug("richTextFeedbackInCorrect: " + richTextFeedbackInCorrect); + + if (richTextFeedbackInCorrect == null) richTextFeedbackInCorrect=""; + mapFeedbackIncorrect.put(selectedQuestionIndex, richTextFeedbackInCorrect); + request.getSession().setAttribute(MAP_FEEDBACK_INCORRECT, mapFeedbackIncorrect); + logger.debug("updated MAP_FEEDBACK_INCORRECT:" + mapFeedbackIncorrect); + + Map mapFeedbackCorrect =(Map)request.getSession().getAttribute(MAP_FEEDBACK_CORRECT); + logger.debug("current mapFeedbackCorrect:" + mapFeedbackCorrect); + String richTextFeedbackCorrect=(String) request.getSession().getAttribute(RICHTEXT_FEEDBACK_CORRECT); + logger.debug("richTextFeedbackCorrect: " + richTextFeedbackCorrect); + + if (richTextFeedbackCorrect == null) richTextFeedbackCorrect=""; + mapFeedbackCorrect.put(selectedQuestionIndex, richTextFeedbackCorrect); + request.getSession().setAttribute(MAP_FEEDBACK_CORRECT, mapFeedbackCorrect); + logger.debug("updated MAP_FEEDBACK_INCORRECT:" + mapFeedbackCorrect); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(1)); + logger.debug("resetting EDIT_OPTIONS_MODE to 1"); + mcAuthoringForm.resetUserAction(); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + /** + * moves a question entry a step down the questions Map + * moveQuestionDown(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward moveQuestionDown(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching moveQuestionDown..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="moveDown"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + Map mapQuestionsContent=AuthoringUtil.repopulateMap(request, "questionContent"); + logger.debug("mapQuestionsContent before move down: " + mapQuestionsContent); + + String questionIndex =mcAuthoringForm.getQuestionIndex(); + logger.debug("questionIndex:" + questionIndex); + String movableQuestionEntry=(String)mapQuestionsContent.get(questionIndex); + logger.debug("movableQuestionEntry:" + movableQuestionEntry); + + mapQuestionsContent= AuthoringUtil.shiftMap(mapQuestionsContent, questionIndex,movableQuestionEntry, "down"); + logger.debug("mapQuestionsContent after move down: " + mapQuestionsContent); + + request.getSession().setAttribute(MAP_QUESTIONS_CONTENT, mapQuestionsContent); + logger.debug("updated Questions Map: " + request.getSession().getAttribute(MAP_QUESTIONS_CONTENT)); + + mcAuthoringForm.resetUserAction(); + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("resetting EDIT_OPTIONS_MODE to 0"); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + /** + * moves a question entry a step up the questions Map + * moveQuestionUp(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward moveQuestionUp(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching moveQuestionUp..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="moveUp"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + Map mapQuestionsContent=AuthoringUtil.repopulateMap(request, "questionContent"); + logger.debug("mapQuestionsContent before move down: " + mapQuestionsContent); + + String questionIndex =mcAuthoringForm.getQuestionIndex(); + logger.debug("questionIndex:" + questionIndex); + String movableQuestionEntry=(String)mapQuestionsContent.get(questionIndex); + logger.debug("movableQuestionEntry:" + movableQuestionEntry); + + mapQuestionsContent= AuthoringUtil.shiftMap(mapQuestionsContent, questionIndex,movableQuestionEntry, "up"); + logger.debug("mapQuestionsContent after move down: " + mapQuestionsContent); + + request.getSession().setAttribute(MAP_QUESTIONS_CONTENT, mapQuestionsContent); + logger.debug("updated Questions Map: " + request.getSession().getAttribute(MAP_QUESTIONS_CONTENT)); + + mcAuthoringForm.resetUserAction(); + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("resetting EDIT_OPTIONS_MODE to 0"); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + /** + * completes the candidate options screen + * doneOptions(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward doneOptions(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching doneOptions..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="doneOptions"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("setting EDIT_OPTIONS_MODE to 0"); + + boolean validateOptions=AuthoringUtil.validateOptions(request); + logger.debug("validateOptions:" + validateOptions); + + if (validateOptions == false) + { + ActionMessages errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.checkBoxes.empty")); + logger.debug("add error.checkBoxes.empty to ActionMessages"); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + logger.debug("return to LOAD_QUESTIONS to fix error."); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(1)); + logger.debug("setting EDIT_OPTIONS_MODE to 1"); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + Map mapOptionsContent=AuthoringUtil.repopulateMap(request, "optionContent"); + logger.debug("mapOptionsContent after shrinking: " + mapOptionsContent); + request.getSession().setAttribute(MAP_OPTIONS_CONTENT, mapOptionsContent); + logger.debug("final done MAP_OPTIONS_CONTENT: " + mapOptionsContent); + + + String selectedQuestionIndex=(String) request.getSession().getAttribute(SELECTED_QUESTION_INDEX); + logger.debug("retrieved SELECTED_QUESTION_INDEX to:" + selectedQuestionIndex); + + /** update the questions Map with the new question*/ + Map mapQuestionsContent=(Map) request.getSession().getAttribute(MAP_QUESTIONS_CONTENT); + logger.debug("mapQuestionsContent: " + mapQuestionsContent); + String selectedQuestion=(String) request.getSession().getAttribute(SELECTED_QUESTION); + logger.debug("final selectedQuestion:" + selectedQuestion); + mapQuestionsContent.put(selectedQuestionIndex,selectedQuestion); + logger.debug("updated mapQuestionsContent with:" + selectedQuestionIndex + " and " + selectedQuestion); + request.getSession().setAttribute(MAP_QUESTIONS_CONTENT, mapQuestionsContent); + logger.debug("updated MAP_QUESTIONS_CONTENT:" + mapQuestionsContent); + + + Map mapSelectedOptions= (Map) request.getSession().getAttribute(MAP_SELECTED_OPTIONS); + mapSelectedOptions.clear(); + mapSelectedOptions = AuthoringUtil.repopulateCurrentCheckBoxStatesMap(request); + logger.debug("after add mapSelectedOptions: " + mapSelectedOptions); + request.getSession().setAttribute(MAP_SELECTED_OPTIONS, mapSelectedOptions); + + Map mapGeneralSelectedOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_SELECTED_OPTIONS_CONTENT); + logger.debug("current mapGeneralSelectedOptionsContent: " + mapGeneralSelectedOptionsContent); + mapGeneralSelectedOptionsContent.put(selectedQuestionIndex,mapSelectedOptions); + request.getSession().setAttribute(MAP_GENERAL_SELECTED_OPTIONS_CONTENT, mapGeneralSelectedOptionsContent); + logger.debug("updated MAP_GENERAL_SELECTED_OPTIONS_CONTENT after add: " + mapGeneralSelectedOptionsContent); + + + /* update feedback Maps*/ + Map mapFeedbackIncorrect =(Map)request.getSession().getAttribute(MAP_FEEDBACK_INCORRECT); + logger.debug("current mapFeedbackIncorrect:" + mapFeedbackIncorrect); + String richTextFeedbackInCorrect=(String) request.getSession().getAttribute(RICHTEXT_FEEDBACK_INCORRECT); + logger.debug("richTextFeedbackInCorrect: " + richTextFeedbackInCorrect); + + if (richTextFeedbackInCorrect == null) richTextFeedbackInCorrect=""; + mapFeedbackIncorrect.put(selectedQuestionIndex, richTextFeedbackInCorrect); + request.getSession().setAttribute(MAP_FEEDBACK_INCORRECT, mapFeedbackIncorrect); + logger.debug("updated MAP_FEEDBACK_INCORRECT:" + mapFeedbackIncorrect); + + Map mapFeedbackCorrect =(Map)request.getSession().getAttribute(MAP_FEEDBACK_CORRECT); + logger.debug("current mapFeedbackCorrect:" + mapFeedbackCorrect); + String richTextFeedbackCorrect=(String) request.getSession().getAttribute(RICHTEXT_FEEDBACK_CORRECT); + logger.debug("richTextFeedbackCorrect: " + richTextFeedbackCorrect); + + if (richTextFeedbackCorrect == null) richTextFeedbackCorrect=""; + mapFeedbackCorrect.put(selectedQuestionIndex, richTextFeedbackCorrect); + request.getSession().setAttribute(MAP_FEEDBACK_CORRECT, mapFeedbackCorrect); + logger.debug("updated MAP_FEEDBACK_CORRECT:" + mapFeedbackCorrect); + + + Map mapGeneralOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_OPTIONS_CONTENT); + logger.debug("current mapGeneralOptionsContent: " + mapGeneralOptionsContent); + mapGeneralOptionsContent.put(selectedQuestionIndex,mapOptionsContent); + request.getSession().setAttribute(MAP_GENERAL_OPTIONS_CONTENT, mapGeneralOptionsContent); + logger.debug("updated MAP_GENERAL_OPTIONS_CONTENT after done: " + mapGeneralOptionsContent); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("setting EDIT_OPTIONS_MODE to 0"); + mcAuthoringForm.resetUserAction(); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + /** + * submits questions Map and persists questions as well as options information in the db. + * submitQuestions(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward submitQuestions(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + + { + logger.debug("dispatching submitQuestions..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + /* persist the final Questions Map */ + String userAction="submitQuestions"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("setting EDIT_OPTIONS_MODE to 0"); + + ActionMessages errors= new ActionMessages(); + Map mapQuestionsContent=AuthoringUtil.repopulateMap(request, "questionContent"); + logger.debug("mapQuestionsContent before submit: " + mapQuestionsContent); + request.getSession().setAttribute(MAP_QUESTIONS_CONTENT, mapQuestionsContent); + + /* make sure the questions Map is not empty*/ + int mapSize=mapQuestionsContent.size(); + logger.debug("mapSize: " + mapSize); + + if (mapSize == 0) + { + errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.questions.submitted.none")); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + persistError(request,"error.questions.submitted.none"); + + mcAuthoringForm.setAddQuestion(null); + mcAuthoringForm.setSubmitQuestions(null); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + Map mapWeights= AuthoringUtil.repopulateCurrentWeightsMap(request, "questionWeight"); + logger.debug("mapWeights: " + mapWeights); + boolean weightsValid=validateQuestionWeights(request,mapWeights, mcAuthoringForm); + logger.debug("weightsValid:" + weightsValid); + if (weightsValid == false) + { + mcAuthoringForm.resetUserAction(); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + + mcAuthoringForm.setAddQuestion(null); + mcAuthoringForm.setSubmitQuestions(null); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + boolean isTotalWeightsValid=AuthoringUtil.validateTotalWeight(request); + logger.debug("isTotalWeightsValid:" + isTotalWeightsValid); + if (isTotalWeightsValid == false) + { + errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.weights.total.invalid")); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + persistError(request,"error.weights.total.invalid"); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("setting EDIT_OPTIONS_MODE to 0"); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + + mcAuthoringForm.setAddQuestion(null); + mcAuthoringForm.setSubmitQuestions(null); + return (mapping.findForward(LOAD_QUESTIONS)); + } + logger.debug("MAP_WEIGHTS is valid, persist it to session"); + request.getSession().setAttribute(MAP_WEIGHTS, mapWeights); + + boolean isQuestionsSequenced=false; + boolean isSynchInMonitor=false; + boolean isUsernameVisible=false; + boolean isRetries=false; + boolean isShowFeedback=false; + boolean isSln=false; + + String monitoringReportTitle=""; + String reportTitle=""; + String endLearningMessage=""; + int passmark=0; + + logger.debug("isQuestionsSequenced: " + mcAuthoringForm.getQuestionsSequenced()); + if (mcAuthoringForm.getQuestionsSequenced().equalsIgnoreCase(ON)) + isQuestionsSequenced=true; + + logger.debug("isSynchInMonitor: " + mcAuthoringForm.getSynchInMonitor()); + if (mcAuthoringForm.getSynchInMonitor().equalsIgnoreCase(ON)) + isSynchInMonitor=true; + + logger.debug("isUsernameVisible: " + mcAuthoringForm.getUsernameVisible()); + if (mcAuthoringForm.getUsernameVisible().equalsIgnoreCase(ON)) + isUsernameVisible=true; + + logger.debug("isRetries: " + mcAuthoringForm.getRetries()); + if (mcAuthoringForm.getRetries().equalsIgnoreCase(ON)) + isRetries=true; + + logger.debug("isSln" + mcAuthoringForm.getSln()); + if (mcAuthoringForm.getSln().equalsIgnoreCase(ON)) + isSln=true; + + logger.debug("passmark: " + mcAuthoringForm.getPassmark()); + + if (mcAuthoringForm.getPassmark() != null) + { + try + { + passmark= new Integer(mcAuthoringForm.getPassmark()).intValue(); + logger.debug("tried passmark: " + passmark); + } + catch(Exception e) + { + errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.passmark.notInteger")); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + persistError(request,"error.passmark.notInteger"); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("setting EDIT_OPTIONS_MODE to 0"); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + + mcAuthoringForm.setAddQuestion(null); + mcAuthoringForm.setSubmitQuestions(null); + return (mapping.findForward(LOAD_QUESTIONS)); + } + } + + if ((mcAuthoringForm.getPassmark() != null) && (mcAuthoringForm.getPassmark().length() > 0)) + { + passmark= new Integer(mcAuthoringForm.getPassmark()).intValue(); + logger.debug("populated passmark: " + passmark); + } + else + { + errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.passMark.empty")); + logger.debug("add error.passMark.empty to ActionMessages"); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + logger.debug("return to LOAD_QUESTIONS to fix error."); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("setting EDIT_OPTIONS_MODE to 0"); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + + mcAuthoringForm.setAddQuestion(null); + mcAuthoringForm.setSubmitQuestions(null); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + logger.debug("isShowFeedback: " + mcAuthoringForm.getShowFeedback()); + if (mcAuthoringForm.getShowFeedback().equalsIgnoreCase(ON)) + isShowFeedback=true; + + logger.debug("MONITORING_REPORT_TITLE: " + mcAuthoringForm.getMonitoringReportTitle()); + monitoringReportTitle=mcAuthoringForm.getMonitoringReportTitle(); + if ((monitoringReportTitle == null) || (monitoringReportTitle.length() == 0)) + monitoringReportTitle=(String)request.getSession().getAttribute(MONITORING_REPORT_TITLE); + + reportTitle=mcAuthoringForm.getReportTitle(); + logger.debug("REPORT_TITLE: " + mcAuthoringForm.getReportTitle()); + if ((reportTitle == null) || (reportTitle.length() == 0)) + reportTitle=(String)request.getSession().getAttribute(REPORT_TITLE); + + endLearningMessage=mcAuthoringForm.getEndLearningMessage(); + logger.debug("END_LEARNING_MESSAGE: " + mcAuthoringForm.getEndLearningMessage()); + if ((endLearningMessage == null) || (endLearningMessage.length() == 0)) + endLearningMessage=(String)request.getSession().getAttribute(END_LEARNING_MESSAGE); + + + String richTextTitle=(String) request.getSession().getAttribute(RICHTEXT_TITLE); + logger.debug("richTextTitle: " + richTextTitle); + + String richTextInstructions=(String) request.getSession().getAttribute(RICHTEXT_INSTRUCTIONS); + logger.debug("richTextInstructions: " + richTextInstructions); + + + if ((richTextTitle == null) || (richTextTitle.length() == 0) || richTextTitle.equalsIgnoreCase(RICHTEXT_BLANK)) + { + errors.add(Globals.ERROR_KEY,new ActionMessage("error.title")); + logger.debug("add title to ActionMessages"); + } + + if ((richTextInstructions == null) || (richTextInstructions.length() == 0) || richTextInstructions.equalsIgnoreCase(RICHTEXT_BLANK)) + { + errors.add(Globals.ERROR_KEY, new ActionMessage("error.instructions")); + logger.debug("add instructions to ActionMessages: "); + } + + if (errors.size() > 0) + { + logger.debug("either title or instructions or both is missing. Returning back to from to fix errors:"); + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("setting EDIT_OPTIONS_MODE to 0"); + + mcAuthoringForm.resetUserAction(); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + + mcAuthoringForm.setAddQuestion(null); + mcAuthoringForm.setSubmitQuestions(null); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + String richTextOfflineInstructions=(String) request.getSession().getAttribute(RICHTEXT_OFFLINEINSTRUCTIONS); + logger.debug("richTextOfflineInstructions: " + richTextOfflineInstructions); + if (richTextOfflineInstructions == null) richTextOfflineInstructions=""; + + String richTextOnlineInstructions=(String) request.getSession().getAttribute(RICHTEXT_ONLINEINSTRUCTIONS); + logger.debug("richTextOnlineInstructions: " + richTextOnlineInstructions); + if (richTextOnlineInstructions == null) richTextOnlineInstructions=""; + + String richTextReportTitle=(String)request.getSession().getAttribute(RICHTEXT_REPORT_TITLE); + logger.debug("richTextReportTitle: " + richTextReportTitle); + + String richTextEndLearningMessage=(String)request.getSession().getAttribute(RICHTEXT_END_LEARNING_MSG); + logger.debug("richTextEndLearningMessage: " + richTextEndLearningMessage); + + mapQuestionsContent=AuthoringUtil.repopulateMap(request, "questionContent"); + logger.debug("FINAL mapQuestionsContent after shrinking: " + mapQuestionsContent); + logger.debug("mapQuestionsContent size after shrinking: " + mapQuestionsContent.size()); + request.getSession().setAttribute(MAP_QUESTIONS_CONTENT, mapQuestionsContent); + + Long toolContentId=(Long)request.getSession().getAttribute(TOOL_CONTENT_ID); + logger.debug("toolContentId:" + toolContentId); + + McContent mcContent=mcService.retrieveMc(toolContentId); + logger.debug("existing mcContent:" + mcContent); + + if (mcContent != null) + { + logger.debug("updating mcContent title and instructions:" + mcContent); + mcContent.setTitle(richTextTitle); + mcContent.setInstructions(richTextInstructions); + + mcContent.setQuestionsSequenced(isQuestionsSequenced); + mcContent.setSynchInMonitor(isSynchInMonitor); + mcContent.setUsernameVisible(isUsernameVisible); + mcContent.setRetries(isRetries); + mcContent.setPassMark(new Integer(passmark)); + mcContent.setShowFeedback(isShowFeedback); + mcContent.setShowReport(isSln); + mcContent.setEndLearningMessage(endLearningMessage); + mcContent.setReportTitle(richTextReportTitle); + mcContent.setMonitoringReportTitle(monitoringReportTitle); + mcContent.setEndLearningMessage(richTextEndLearningMessage); + mcContent.setOfflineInstructions(richTextOfflineInstructions); + mcContent.setOnlineInstructions(richTextOnlineInstructions); + } + else + { + mcContent=AuthoringUtil.createContent(request, mcAuthoringForm); + logger.debug("mcContent created"); + } + + mapQuestionsContent=(Map) request.getSession().getAttribute(MAP_QUESTIONS_CONTENT); + logger.debug("Submit final MAP_QUESTIONS_CONTENT :" + mapQuestionsContent); + + Map mapFeedbackIncorrect =(Map)request.getSession().getAttribute(MAP_FEEDBACK_INCORRECT); + logger.debug("Submit final MAP_FEEDBACK_INCORRECT :" + mapFeedbackIncorrect); + + Map mapFeedbackCorrect =(Map)request.getSession().getAttribute(MAP_FEEDBACK_CORRECT); + logger.debug("Submit final MAP_FEEDBACK_CORRECT :" + mapFeedbackCorrect); + + AuthoringUtil.refreshMaps(request, toolContentId.longValue()); + logger.debug("refreshed maps..."); + + logger.debug("start processing questions content..."); + Long mcContentId =mcContent.getUid(); + List existingQuestions = mcService.refreshQuestionContent(mcContentId); + logger.debug("existingQuestions: " + existingQuestions); + + logger.debug("will cleanupRedundantQuestions:"); + /* Removes only unused question entries from the db. It keeps the valid entries since they get updated. */ + AuthoringUtil.cleanupRedundantQuestions(request, existingQuestions, mapQuestionsContent, mcContent); + + logger.debug("calling selectAndPersistQuestions: " + existingQuestions); + AuthoringUtil.selectAndPersistQuestions(request, existingQuestions, mapQuestionsContent, mapFeedbackIncorrect, mapFeedbackCorrect, mcContent); + logger.debug("finished processing questions content..."); + + logger.debug("start processing options content..."); + Map mapStartupGeneralOptionsContent= (Map) request.getSession().getAttribute(MAP_STARTUP_GENERAL_OPTIONS_CONTENT); + logger.debug("mapStartupGeneralOptionsContent: " + mapStartupGeneralOptionsContent); + Map mapStartupGeneralSelectedOptionsContent=(Map)request.getSession().getAttribute(MAP_STARTUP_GENERAL_SELECTED_OPTIONS_CONTENT); + logger.debug("mapStartupGeneralSelectedOptionsContent: " + mapStartupGeneralSelectedOptionsContent); + Map mapStartupGeneralOptionsQueId=(Map) request.getSession().getAttribute(MAP_STARTUP_GENERAL_OPTIONS_QUEID); + logger.debug("mapStartupGeneralOptionsQueId: " + mapStartupGeneralOptionsQueId); + + Map mapGeneralOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_OPTIONS_CONTENT); + logger.debug("mapGeneralOptionsContent: " + mapGeneralOptionsContent); + Map mapGeneralSelectedOptionsContent=(Map)request.getSession().getAttribute(MAP_GENERAL_SELECTED_OPTIONS_CONTENT); + logger.debug("mapGeneralSelectedOptionsContent: " + mapGeneralSelectedOptionsContent); + + logger.debug("calling cleanupRedundantOptions"); + AuthoringUtil.cleanupRedundantOptions(request, mapStartupGeneralOptionsContent, mapStartupGeneralSelectedOptionsContent, mapGeneralOptionsContent, mapGeneralSelectedOptionsContent, mapStartupGeneralOptionsQueId); + logger.debug("calling selectAndPersistOptions"); + AuthoringUtil.selectAndPersistOptions(request, mapStartupGeneralOptionsContent, mapStartupGeneralSelectedOptionsContent, mapGeneralOptionsContent, mapGeneralSelectedOptionsContent, mapStartupGeneralOptionsQueId); + + + logger.debug("will do addUploadedFilesMetaData"); + McUtils.addUploadedFilesMetaData(request,mcContent); + logger.debug("done addUploadedFilesMetaData"); + + errors.clear(); + errors.add(Globals.ERROR_KEY,new ActionMessage("submit.successful")); + logger.debug("add submit.successful to ActionMessages"); + saveErrors(request,errors); + request.setAttribute(SUBMIT_SUCCESS, new Integer(1)); + logger.debug("set SUBMIT_SUCCESS to 1"); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("setting EDIT_OPTIONS_MODE to 0"); + + mcAuthoringForm.resetUserAction(); + + int maxQuestionIndex=mapQuestionsContent.size(); + request.getSession().setAttribute(MAX_QUESTION_INDEX, new Integer(maxQuestionIndex)); + logger.debug("MAX_QUESTION_INDEX: " + request.getSession().getAttribute(MAX_QUESTION_INDEX)); + + mcAuthoringForm.setAddQuestion(null); + mcAuthoringForm.setSubmitQuestions(null); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + /** + * prepares data to view the contents of uploaded files + * viewFileItem(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward viewFileItem(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + + { + logger.debug("dispatching viewFileItem..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="viewFileItem"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + String filename= request.getParameter("fileItem"); + logger.debug("filename:" + filename); + + String uuid=mcService.getFileUuid(filename); + logger.debug("uuid:" + uuid); + + if (uuid == null) + { + ActionMessages errors= new ActionMessages(); + errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.file.notPersisted")); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + persistError(request,"error.file.notPersisted"); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(2)); + logger.debug("setting EDIT_OPTIONS_MODE :" + 2); + return (mapping.findForward(ALL_INSTRUCTIONS)); + } + + InputStream fileInputStream=mcService.downloadFile(new Long(uuid), null); + logger.debug("fileInputStream:" + fileInputStream); + + DataInputStream dis = new DataInputStream(fileInputStream); + logger.debug("dis:" + dis); + + String allFileText=""; + try + { + String input=""; + while ((input = dis.readLine()) != null) + { + logger.debug("input:" + input); + allFileText = allFileText + input + "\r\n"; + } + } catch (EOFException e) { + logger.debug("error reading the file :" + e); + logger.debug("error msg reading the file :" + e.getMessage()); + } + catch (IOException e) { + logger.debug("error reading the file :" + e); + logger.debug("error msg reading the file :" + e.getMessage()); + } + + logger.debug("allFileText:" + allFileText); + request.getSession().setAttribute(FILE_CONTENT, allFileText); + + request.setAttribute(FILE_CONTENT_READY, new Integer(1)); + logger.debug("set FILE_CONTENT_READY to 1"); + + request.getSession().setAttribute(FILE_NAME, filename); + + mcAuthoringForm.resetUserAction(); + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(2)); + logger.debug("setting EDIT_OPTIONS_MODE :" + 2); + return (mapping.findForward(ALL_INSTRUCTIONS)); + } + + + /** + * moves from Advanced Tab to Basic Tab + * doneAdvancedTab(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward doneAdvancedTab(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching doneAdvancedTab..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="advancedTabDone"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + mcAuthoringForm.resetUserAction(); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + /** + * moves from Instructions Tab to Basic Tab + * doneInstructionsTab(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward doneInstructionsTab(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching doneInstructionsTab..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="dispinstructionsTabDone"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + mcAuthoringForm.resetUserAction(); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + + /** + * adds the offline file information in the content repository. + * submitOfflineFiles(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward submitOfflineFiles(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching submitOfflineFile..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="submitOfflineFile"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + McUtils.addFileToContentRepository(request, mcAuthoringForm, true); + logger.debug("offline file added to repository successfully."); + + mcAuthoringForm.resetUserAction(); + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(2)); + logger.debug("setting EDIT_OPTIONS_MODE :" + 2 ); + return (mapping.findForward(ALL_INSTRUCTIONS)); + } + + + /** + * adds the online file information in the content repository. + * submitOnlineFiles(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward submitOnlineFiles(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching submitOnlineFiles..."); + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + IMcService mcService =McUtils.getToolService(request); + + String userAction="submitOnlineFile"; + request.setAttribute(USER_ACTION, userAction); + logger.debug("userAction:" + userAction); + + McUtils.addFileToContentRepository(request, mcAuthoringForm, false); + logger.debug("online file added to repository successfully."); + + mcAuthoringForm.resetUserAction(); + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(2)); + logger.debug("setting EDIT_OPTIONS_MODE :" + 2); + return (mapping.findForward(ALL_INSTRUCTIONS)); + } + + + /** + * ensures that the weight valued entered are valid + * validateQuestionWeights(HttpServletRequest request, McAuthoringForm mcAuthoringForm) + * + * @param request + * @param mcAuthoringForm + * @return + */ + protected boolean validateQuestionWeights(HttpServletRequest request, Map mapWeights, McAuthoringForm mcAuthoringForm) + { + logger.debug("mapWeights: " + mapWeights); + + Iterator itMap = mapWeights.entrySet().iterator(); + while (itMap.hasNext()) { + Map.Entry pairs = (Map.Entry)itMap.next(); + logger.debug("using the pair: " + pairs.getKey() + " = " + pairs.getValue()); + + if ((pairs.getValue() == null) || (pairs.getValue().toString().length() == 0)) + { + ActionMessages errors= new ActionMessages(); + errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.weights.empty")); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + persistError(request,"error.weights.empty"); + return false; + } + + try + { + int weight= new Integer(pairs.getValue().toString()).intValue(); + logger.debug("tried weight: " + weight); + } + catch(Exception e) + { + ActionMessages errors= new ActionMessages(); + errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.weights.notInteger")); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + persistError(request,"error.weights.notInteger"); + return false; + } + + + int weight= new Integer(pairs.getValue().toString()).intValue(); + if (weight == 0) + { + ActionMessages errors= new ActionMessages(); + errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY,new ActionMessage("error.weights.zero")); + saveErrors(request,errors); + mcAuthoringForm.resetUserAction(); + persistError(request,"error.weights.zero"); + return false; + } + } + mcAuthoringForm.resetUserAction(); + return true; + } + + + /** + * persists error messages to request scope + * @param request + * @param message + */ + public void persistError(HttpServletRequest request, String message) + { + ActionMessages errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY, new ActionMessage(message)); + logger.debug("add " + message +" to ActionMessages:"); + saveErrors(request,errors); + } + + + /** + * responds to learner activity in learner mode. + * + * ActionForward displayMc(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + * + * + * @param mapping + * @param form + * @param request + * @param response + * @return + * @throws IOException + * @throws ServletException + + + + + + + + + + + + + + + + + + + + * + * responds to learner activity in learner mode. + * + * ActionForward displayMc(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + * + * + * @param mapping + * @param form + * @param request + * @param response + * @return + * @throws IOException + * @throws ServletException + */ + public ActionForward displayMc(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("displayMc starting.."); + + McLearningForm mcLearningForm = (McLearningForm) form; + IMcService mcService =McUtils.getToolService(request); + + mcLearningForm.resetParameters(); + LearningUtil.readParameters(request, mcLearningForm); + + if (mcLearningForm.getContinueOptionsCombined() != null) + { + return continueOptionsCombined(mapping, form, request, response); + } + else if (mcLearningForm.getNextOptions() != null) + { + return getNextOptions(mapping, form, request, response); + } + else if (mcLearningForm.getOptionCheckBoxSelected() != null) + { + logger.debug("requested selectOptionsCheckBox..."); + mcLearningForm.resetCommands(); + LearningUtil.selectOptionsCheckBox(request,mcLearningForm, mcLearningForm.getQuestionIndex()); + } + else if (mcLearningForm.getRedoQuestions() != null) + { + return redoQuestions(mapping, form, request, response); + } + else if (mcLearningForm.getRedoQuestionsOk() != null) + { + logger.debug("requested redoQuestionsOk, user is sure to redo the questions."); + mcLearningForm.resetCommands(); + return redoQuestions(request, mcLearningForm, mapping); + } + else if (mcLearningForm.getViewAnswers() != null) + { + return viewAnswers(mapping, form, request, response); + } + else if (mcLearningForm.getViewSummary() != null) + { + return viewSummary(mapping, form, request, response); + } + else if (mcLearningForm.getLearnerFinished() != null) + { + logger.debug("requested learner finished, the learner should be directed to next activity."); + mcLearningForm.resetCommands(); + //fix this + return (mapping.findForward(VIEW_SUMMARY)); + } + + mcLearningForm.resetCommands(); + return (mapping.findForward(LOAD_LEARNER)); + } + + + /** + * takes care of the assessment + * continueOptionsCombined(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward continueOptionsCombined(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching continueOptionsCombined..."); + McLearningForm mcLearningForm = (McLearningForm) form; + IMcService mcService =McUtils.getToolService(request); + + /* process the answers */ + Map mapGeneralCheckedOptionsContent=(Map) request.getSession().getAttribute(MAP_GENERAL_CHECKED_OPTIONS_CONTENT); + logger.debug("final mapGeneralCheckedOptionsContent: " + mapGeneralCheckedOptionsContent); + + Long toolContentId=(Long) request.getSession().getAttribute(TOOL_CONTENT_ID); + logger.debug("toolContentId: " + toolContentId); + + logger.debug("will assess"); + Integer passMark=(Integer) request.getSession().getAttribute(PASSMARK); + logger.debug("passMark: " + passMark); + + Map mapLeanerAssessmentResults=LearningUtil.assess(request, mapGeneralCheckedOptionsContent, toolContentId); + logger.debug("mapLeanerAssessmentResults: " + mapLeanerAssessmentResults); + logger.debug("assesment complete"); + + int mark=LearningUtil.getMark(mapLeanerAssessmentResults); + logger.debug("mark: " + mark); + request.getSession().setAttribute(LEARNER_MARK, new Integer(mark).toString()); + request.getSession().setAttribute(LEARNER_MARK_ATLEAST, new Integer(mark+1).toString()); + + Map mapQuestionWeights =(Map) request.getSession().getAttribute(MAP_QUESTION_WEIGHTS); + logger.debug("mapQuestionWeights: " + mapQuestionWeights); + + boolean passed=false; + if ((passMark != null) && (passMark.intValue() != 0)) + { + int totalUserWeight=LearningUtil.calculateWeights(mapLeanerAssessmentResults, mapQuestionWeights); + logger.debug("totalUserWeight: " + totalUserWeight); + + if (totalUserWeight < passMark.intValue()) + { + logger.debug("USER FAILED"); + request.getSession().setAttribute(USER_PASSED, new Boolean(false).toString()); + logger.debug("totalUserWeight is less than passmark: " + totalUserWeight + " < " + passMark.intValue()); + passed=false; + } + else + { + logger.debug("USER PASSED"); + request.getSession().setAttribute(USER_PASSED, new Boolean(true).toString()); + passed=true; + } + } + + boolean isUserDefined=LearningUtil.doesUserExists(request); + logger.debug("isUserDefined"); + if (isUserDefined == false) + { + LearningUtil.createUser(request); + logger.debug("created user in the db"); + } + McQueUsr mcQueUsr=LearningUtil.getUser(request); + logger.debug("mcQueUsr: " + mcQueUsr); + + + String highestAttemptOrder=(String)request.getSession().getAttribute(LEARNER_LAST_ATTEMPT_ORDER); + logger.debug("current highestAttemptOrder:" + highestAttemptOrder); + + logger.debug("passed: " + passed); + LearningUtil.createAttempt(request, mcQueUsr, mapGeneralCheckedOptionsContent, mark, passed, new Integer(highestAttemptOrder).intValue(), mapLeanerAssessmentResults); + logger.debug("created user attempt in the db"); + + int intHighestAttemptOrder=new Integer(highestAttemptOrder).intValue()+ 1 ; + logger.debug("updated highestAttemptOrder:" + intHighestAttemptOrder); + request.getSession().setAttribute(LEARNER_LAST_ATTEMPT_ORDER, new Integer(intHighestAttemptOrder).toString()); + + mcLearningForm.resetCommands(); + return (mapping.findForward(INDIVIDUAL_REPORT)); + } + + + /** + * takes care of the assessment + * continueOptionsCombined(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward getNextOptions(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching getNextOptions..."); + McLearningForm mcLearningForm = (McLearningForm) form; + IMcService mcService =McUtils.getToolService(request); + + String currentQuestionIndex=(String)request.getSession().getAttribute(CURRENT_QUESTION_INDEX); + logger.debug("currentQuestionIndex:" + currentQuestionIndex); + + String totalQuestionCount=(String)request.getSession().getAttribute(TOTAL_QUESTION_COUNT); + logger.debug("totalQuestionCount:" + totalQuestionCount); + + int intTotalQuestionCount=new Integer(totalQuestionCount).intValue(); + int intCurrentQuestionIndex=new Integer(currentQuestionIndex).intValue(); + + if (intTotalQuestionCount-1 == intCurrentQuestionIndex) + { + logger.debug("totalQuestionCount has been reached :" + totalQuestionCount); + request.getSession().setAttribute(TOTAL_COUNT_REACHED, new Boolean(true).toString()); + } + + mcLearningForm.resetCommands(); + + int newQuestionIndex=new Integer(currentQuestionIndex).intValue() + 1; + request.getSession().setAttribute(CURRENT_QUESTION_INDEX, new Integer(newQuestionIndex).toString()); + logger.debug("updated questionIndex:" + request.getSession().getAttribute(CURRENT_QUESTION_INDEX)); + return (mapping.findForward(LOAD_LEARNER)); + } + + + /** + * allows the learner to take the activity again + * redoQuestions(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward redoQuestions(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching redoQuestions..."); + McLearningForm mcLearningForm = (McLearningForm) form; + IMcService mcService =McUtils.getToolService(request); + + request.getSession().setAttribute(CURRENT_QUESTION_INDEX, "1"); + request.getSession().setAttribute(TOTAL_COUNT_REACHED, new Boolean(false).toString()); + + McQueUsr mcQueUsr=LearningUtil.getUser(request); + Long queUsrId=mcQueUsr.getUid(); + logger.debug("queUsrId: " + queUsrId); + + int learnerBestMark=LearningUtil.getHighestMark(request, queUsrId); + logger.debug("learnerBestMark: " + learnerBestMark); + request.getSession().setAttribute(LEARNER_BEST_MARK,new Integer(learnerBestMark).toString()); + + mcLearningForm.resetCommands(); + return (mapping.findForward(REDO_QUESTIONS)); + } + + + /** + * allows the learner to take the activity again + * viewAnswers(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward viewAnswers(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching viewAnswers..."); + McLearningForm mcLearningForm = (McLearningForm) form; + IMcService mcService =McUtils.getToolService(request); + String totalQuestionCount= (String) request.getSession().getAttribute(TOTAL_QUESTION_COUNT); + logger.debug("totalQuestionCount: " + totalQuestionCount); + + Long toolContentUID= (Long) request.getSession().getAttribute(TOOL_CONTENT_UID); + logger.debug("toolContentUID: " + toolContentUID); + + McQueUsr mcQueUsr=LearningUtil.getUser(request); + Long queUsrId=mcQueUsr.getUid(); + logger.debug("queUsrId: " + queUsrId); + + Map mapQueAttempts= new TreeMap(new McComparator()); + Map mapQueCorrectAttempts= new TreeMap(new McComparator()); + Map mapQueIncorrectAttempts= new TreeMap(new McComparator()); + for (int i=1; i<= new Integer(totalQuestionCount).intValue(); i++) + { + logger.debug("doing question with display order: " + i); + McQueContent mcQueContent=mcService.getQuestionContentByDisplayOrder(new Long(i), toolContentUID); + logger.debug("mcQueContent uid: " + mcQueContent.getUid()); + + Map mapAttemptOrderAttempts= new TreeMap(new McComparator()); + Map mapAttemptOrderCorrectAttempts= new TreeMap(new McComparator()); + Map mapAttemptOrderIncorrectAttempts= new TreeMap(new McComparator()); + for (int j=1; j <= MAX_ATTEMPTY_HISTORY ; j++ ) + { + List attemptsByAttemptOrder=mcService.getAttemptByAttemptOrder(queUsrId, mcQueContent.getUid(), new Integer(j)); + logger.debug("attemptsByAttemptOrder: " + j + " is: " + attemptsByAttemptOrder); + + Map mapAttempts= new TreeMap(new McComparator()); + Map mapAttemptsIncorrect= new TreeMap(new McComparator()); + Map mapAttemptsCorrect= new TreeMap(new McComparator()); + Iterator attemptIterator=attemptsByAttemptOrder.iterator(); + Long mapIndex=new Long(1); + while (attemptIterator.hasNext()) + { + McUsrAttempt mcUsrAttempt=(McUsrAttempt)attemptIterator.next(); + + if (mcUsrAttempt.isAttemptCorrect()) + { + mapAttemptsCorrect.put(mapIndex.toString(), mcUsrAttempt.getMcOptionsContent().getMcQueOptionText()); + } + else + { + mapAttemptsIncorrect.put(mapIndex.toString(), mcUsrAttempt.getMcOptionsContent().getMcQueOptionText()); + } + mapAttempts.put(mapIndex.toString(), mcUsrAttempt.getMcOptionsContent().getMcQueOptionText()); + + logger.debug("added attempt with order: " + mcUsrAttempt.getAttemptOrder() + " , option text is: " + mcUsrAttempt.getMcOptionsContent().getMcQueOptionText()); + mapIndex=new Long(mapIndex.longValue()+1); + } + + logger.debug("final mapAttempts is: " + mapAttempts); + if (mapAttempts.size() > 0) + { + mapAttemptOrderAttempts.put(new Integer(j).toString(), mapAttempts); + } + if (mapAttemptsCorrect.size() > 0) + { + mapAttemptOrderCorrectAttempts.put(new Integer(j).toString(), mapAttemptsCorrect); + } + if (mapAttemptsIncorrect.size() > 0) + { + mapAttemptOrderIncorrectAttempts.put(new Integer(j).toString(), mapAttemptsIncorrect); + } + } + + logger.debug("final mapAttemptOrderAttempts is: " + mapAttemptOrderAttempts); + if (mapAttemptOrderAttempts.size() > 0) + { + mapQueAttempts.put(new Integer(i).toString(), mapAttemptOrderAttempts); + } + if (mapAttemptOrderCorrectAttempts.size() > 0) + { + mapQueCorrectAttempts.put(new Integer(i).toString(), mapAttemptOrderCorrectAttempts); + } + if (mapAttemptOrderIncorrectAttempts.size() > 0) + { + mapQueIncorrectAttempts.put(new Integer(i).toString(), mapAttemptOrderIncorrectAttempts); + } + } + request.getSession().setAttribute(MAP_QUE_ATTEMPTS, mapQueAttempts); + request.getSession().setAttribute(MAP_QUE_CORRECT_ATTEMPTS, mapQueCorrectAttempts); + request.getSession().setAttribute(MAP_QUE_INCORRECT_ATTEMPTS, mapQueIncorrectAttempts); + + logger.debug("final mapQueAttempts is: " + mapQueAttempts); + logger.debug("final mapQueCorrectAttempts is: " + mapQueCorrectAttempts); + logger.debug("final mapQueIncorrectAttempts is: " + mapQueIncorrectAttempts); + mcLearningForm.resetCommands(); + return (mapping.findForward(VIEW_ANSWERS)); + } + + + /** + * allows the learner to view all the other learners' activity summary + * viewSummary(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) + * + * @param request + * @param form + * @param mapping + * @return ActionForward + */ + public ActionForward viewSummary(ActionMapping mapping, + ActionForm form, + HttpServletRequest request, + HttpServletResponse response) throws IOException, + ServletException + { + logger.debug("dispatching viewSummary..."); + McLearningForm mcLearningForm = (McLearningForm) form; + IMcService mcService =McUtils.getToolService(request); + + int countSessionComplete=mcService.countSessionComplete(); + int topMark=LearningUtil.getTopMark(request); + int lowestMark=LearningUtil.getLowestMark(request); + int averageMark=LearningUtil.getAverageMark(request); + + logger.debug("countSessionComplete: " + countSessionComplete); + logger.debug("topMark: " + topMark); + logger.debug("lowestMark: " + lowestMark); + logger.debug("averageMark: " + averageMark); + + request.getSession().setAttribute(COUNT_SESSION_COMPLETE, new Integer(countSessionComplete).toString()); + request.getSession().setAttribute(TOP_MARK, new Integer(topMark).toString()); + request.getSession().setAttribute(LOWEST_MARK, new Integer(lowestMark).toString()); + request.getSession().setAttribute(AVERAGE_MARK, new Integer(averageMark).toString()); + + mcLearningForm.resetCommands(); + return (mapping.findForward(RESULTS_SUMMARY)); + } + + + /** + * redoQuestions(HttpServletRequest request, McLearningForm mcLearningForm, ActionMapping mapping) + * + * @param request + * @param mcLearningForm + * @param mapping + * @return + */ + protected ActionForward redoQuestions(HttpServletRequest request, McLearningForm mcLearningForm, ActionMapping mapping) + { + logger.debug("requested redoQuestions..."); + /* reset the checked options MAP */ + Map mapGeneralCheckedOptionsContent= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_GENERAL_CHECKED_OPTIONS_CONTENT, mapGeneralCheckedOptionsContent); + mcLearningForm.resetCommands(); + return (mapping.findForward(LOAD_LEARNER)); + } + + +} + \ No newline at end of file Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McAuthoringForm.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McAuthoringForm.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McAuthoringForm.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,896 @@ +package org.lamsfoundation.lams.tool.mc.web; + + +import org.apache.struts.action.ActionForm; +import org.lamsfoundation.lams.tool.mc.McAppConstants; +import org.apache.struts.upload.FormFile; + +/** + * @author ozgurd + * + * ActionForm for the Authoring environment + */ +public class McAuthoringForm extends ActionForm implements McAppConstants { + /* form controllers */ + protected String addOptionContent; + protected String addQuestion; + protected String removeQuestion; + protected String submitQuestions; + + protected String editOptions; + protected String addOption; + protected String removeOption; + protected String doneOptions; + protected String moveDown; + protected String moveUp; + + protected String questionIndex; + protected String optionIndex; + protected String selectedIndex; + protected String deletableOptionIndex; + + protected String editDefaultQuestion; + protected String removeOptionContent; + protected String advancedTabDone; + protected String instructionsTabDone; + + protected String fileItem; + protected String viewFileItem; + protected FormFile receivedFile; + + protected String addContent; + protected String removeContent; + protected String removeAllContent; + protected String submitAllContent; + protected String submitTabDone; + protected String submitOfflineFile; + protected String submitOnlineFile; + + + /* tab controller, these may go away once the Flash wraps the jsp */ + protected String choice; + protected String choiceBasic; + protected String choiceAdvanced; + protected String choiceInstructions; + + /* basic content */ + protected String title; + protected String instructions; + + protected String isRemoveContent; + protected String toolContentId; + /* instructions content */ + protected String onlineInstructions; + protected String offlineInstructions; + protected FormFile theOfflineFile; + protected FormFile theOnlineFile; + + protected String richTextOfflineInstructions; + protected String richTextOnlineInstructions; + + /* advanced content */ + protected String synchInMonitor; + protected String showFeedback; + protected String retries; + protected String sln; + + protected String passmark; + + protected String reportTitle; + protected String monitoringReportTitle; + protected String endLearningMessage; + protected String usernameVisible; + protected String questionsSequenced; + + /* proxy controllers for Monitoring tabs */ + protected String summaryMonitoring; + protected String instructionsMonitoring; + protected String editActivityMonitoring; + protected String statsMonitoring; + + protected String edit; + + + public void resetUserAction() + { + this.editDefaultQuestion=null; + this.addOptionContent=null; + this.removeOptionContent=null; + this.addQuestion=null; + this.removeQuestion=null; + this.editOptions=null; + this.addOption=null; + this.removeOption=null; + this.doneOptions=null; + this.submitQuestions=null; + this.advancedTabDone=null; + this.instructionsTabDone=null; + this.moveDown=null; + this.moveUp=null; + + this.fileItem=null; + this.viewFileItem=null; + + this.addContent=null; + this.removeContent=null; + this.removeAllContent=null; + this.submitAllContent=null; + this.submitTabDone=null; + this.submitOfflineFile=null; + this.submitOnlineFile=null; + + this.summaryMonitoring=null; + this.instructionsMonitoring=null; + this.editActivityMonitoring=null; + this.statsMonitoring=null; + this.edit=null; + } + + public void reset() + { + this.editDefaultQuestion=null; + this.addOptionContent=null; + this.removeOptionContent=null; + this.addQuestion=null; + this.removeQuestion=null; + this.editOptions=null; + this.addOption=null; + this.removeOption=null; + this.doneOptions=null; + this.submitQuestions=null; + this.advancedTabDone=null; + this.instructionsTabDone=null; + this.moveDown=null; + this.moveUp=null; + + this.fileItem=null; + this.viewFileItem=null; + this.receivedFile=null; + + this.addContent=null; + this.removeContent=null; + this.removeAllContent=null; + this.submitAllContent=null; + this.submitTabDone=null; + this.submitOfflineFile=null; + this.submitOnlineFile=null; + + this.choice=null; + this.choiceBasic=null; + this.choiceAdvanced=null; + this.choiceInstructions=null; + + this.title=null; + this.instructions=null; + this.questionIndex=null; + this.optionIndex=null; + this.selectedIndex=null; + this.deletableOptionIndex=null; + this.isRemoveContent=null; + this.toolContentId=null; + + this.onlineInstructions=null; + this.offlineInstructions=null; + + this.richTextOfflineInstructions=null; + this.richTextOnlineInstructions=null; + + this.endLearningMessage=null; + this.synchInMonitor=null; + this.reportTitle=null; + this.monitoringReportTitle=null; + this.questionsSequenced=null; + this.showFeedback=null; + this.retries=null; + this.sln=null; + this.passmark=null; + + this.summaryMonitoring=null; + this.instructionsMonitoring=null; + this.editActivityMonitoring=null; + this.statsMonitoring=null; + this.edit=null; + } + + public void resetRadioBoxes() + { + this.synchInMonitor =OPTION_OFF; + this.questionsSequenced =OPTION_OFF; + this.retries =OPTION_OFF; + this.sln =OPTION_OFF; + this.showFeedback =OPTION_OFF; + this.usernameVisible =OPTION_OFF; + } + + + /** + * @return Returns the isRemoveContent. + */ + public String getIsRemoveContent() { + return isRemoveContent; + } + /** + * @param isRemoveContent The isRemoveContent to set. + */ + public void setIsRemoveContent(String isRemoveContent) { + this.isRemoveContent = isRemoveContent; + } + /** + * @return Returns the questionIndex. + */ + public String getQuestionIndex() { + return questionIndex; + } + /** + * @param questionIndex The questionIndex to set. + */ + public void setQuestionIndex(String questionIndex) { + this.questionIndex = questionIndex; + } + + /** + * @return Returns the addContent. + */ + public String getAddContent() { + return addContent; + } + /** + * @param addContent The addContent to set. + */ + public void setAddContent(String addContent) { + this.addContent = addContent; + } + /** + * @return Returns the removeContent. + */ + public String getRemoveContent() { + return removeContent; + } + /** + * @param removeContent The removeContent to set. + */ + public void setRemoveContent(String removeContent) { + this.removeContent = removeContent; + } + /** + * @return Returns the removeAllContent. + */ + public String getRemoveAllContent() { + return removeAllContent; + } + /** + * @param removeAllContent The removeAllContent to set. + */ + public void setRemoveAllContent(String removeAllContent) { + this.removeAllContent = removeAllContent; + } + /** + * @return Returns the submitAllContent. + */ + public String getSubmitAllContent() { + return submitAllContent; + } + /** + * @param submitAllContent The submitAllContent to set. + */ + public void setSubmitAllContent(String submitAllContent) { + this.submitAllContent = submitAllContent; + } + /** + * @return Returns the instructions. + */ + public String getInstructions() { + return instructions; + } + /** + * @param instructions The instructions to set. + */ + public void setInstructions(String instructions) { + this.instructions = instructions; + } + /** + * @return Returns the title. + */ + public String getTitle() { + return title; + } + /** + * @param title The title to set. + */ + public void setTitle(String title) { + this.title = title; + } + /** + * @return Returns the toolContentId. + */ + public String getToolContentId() { + return toolContentId; + } + /** + * @param toolContentId The toolContentId to set. + */ + public void setToolContentId(String toolContentId) { + this.toolContentId = toolContentId; + } + /** + * @return Returns the offlineInstructions. + */ + public String getOfflineInstructions() { + return offlineInstructions; + } + /** + * @param offlineInstructions The offlineInstructions to set. + */ + public void setOfflineInstructions(String offlineInstructions) { + this.offlineInstructions = offlineInstructions; + } + /** + * @return Returns the onlineInstructions. + */ + public String getOnlineInstructions() { + return onlineInstructions; + } + /** + * @param onlineInstructions The onlineInstructions to set. + */ + public void setOnlineInstructions(String onlineInstructions) { + this.onlineInstructions = onlineInstructions; + } + + /** + * @return Returns the syncInMonitor. + */ + public String getSynchInMonitor() { + return synchInMonitor; + } + /** + * @param syncInMonitor The syncInMonitor to set. + */ + public void setSynchInMonitor(String synchInMonitor) { + this.synchInMonitor = synchInMonitor; + } + + /** + * @return Returns the choiceAdvanced. + */ + public String getChoiceAdvanced() { + return choiceAdvanced; + } + /** + * @param choiceAdvanced The choiceAdvanced to set. + */ + public void setChoiceAdvanced(String choiceAdvanced) { + this.choiceAdvanced = choiceAdvanced; + } + /** + * @return Returns the choiceBasic. + */ + public String getChoiceBasic() { + return choiceBasic; + } + /** + * @param choiceBasic The choiceBasic to set. + */ + public void setChoiceBasic(String choiceBasic) { + this.choiceBasic = choiceBasic; + } + /** + * @return Returns the choiceInstructions. + */ + public String getChoiceInstructions() { + return choiceInstructions; + } + /** + * @param choiceInstructions The choiceInstructions to set. + */ + public void setChoiceInstructions(String choiceInstructions) { + this.choiceInstructions = choiceInstructions; + } + /** + * @return Returns the choice. + */ + public String getChoice() { + return choice; + } + /** + * @param choice The choice to set. + */ + public void setChoice(String choice) { + this.choice = choice; + } + /** + * @return Returns the reportTitle. + */ + public String getReportTitle() { + return reportTitle; + } + /** + * @param reportTitle The reportTitle to set. + */ + public void setReportTitle(String reportTitle) { + this.reportTitle = reportTitle; + } + /** + * @return Returns the usernameVisible. + */ + public String getUsernameVisible() { + return usernameVisible; + } + /** + * @param usernameVisible The usernameVisible to set. + */ + public void setUsernameVisible(String usernameVisible) { + this.usernameVisible = usernameVisible; + } + /** + * @return Returns the submitTabDone. + */ + public String getSubmitTabDone() { + return submitTabDone; + } + /** + * @param submitTabDone The submitTabDone to set. + */ + public void setSubmitTabDone(String submitTabDone) { + this.submitTabDone = submitTabDone; + } + + /** + * @return Returns the questionsSequenced. + */ + public String getQuestionsSequenced() { + return questionsSequenced; + } + /** + * @param questionsSequenced The questionsSequenced to set. + */ + public void setQuestionsSequenced(String questionsSequenced) { + this.questionsSequenced = questionsSequenced; + } + /** + * @return Returns the endLearningMessage. + */ + public String getEndLearningMessage() { + return endLearningMessage; + } + /** + * @param endLearningMessage The endLearningMessage to set. + */ + public void setEndLearningMessage(String endLearningMessage) { + this.endLearningMessage = endLearningMessage; + } + /** + * @return Returns the monitoringReportTitle. + */ + public String getMonitoringReportTitle() { + return monitoringReportTitle; + } + /** + * @param monitoringReportTitle The monitoringReportTitle to set. + */ + public void setMonitoringReportTitle(String monitoringReportTitle) { + this.monitoringReportTitle = monitoringReportTitle; + } + /** + * @return Returns the editActivityMonitoring. + */ + public String getEditActivityMonitoring() { + return editActivityMonitoring; + } + /** + * @param editActivityMonitoring The editActivityMonitoring to set. + */ + public void setEditActivityMonitoring(String editActivityMonitoring) { + this.editActivityMonitoring = editActivityMonitoring; + } + /** + * @return Returns the instructionsMonitoring. + */ + public String getInstructionsMonitoring() { + return instructionsMonitoring; + } + /** + * @param instructionsMonitoring The instructionsMonitoring to set. + */ + public void setInstructionsMonitoring(String instructionsMonitoring) { + this.instructionsMonitoring = instructionsMonitoring; + } + /** + * @return Returns the statsMonitoring. + */ + public String getStatsMonitoring() { + return statsMonitoring; + } + /** + * @param statsMonitoring The statsMonitoring to set. + */ + public void setStatsMonitoring(String statsMonitoring) { + this.statsMonitoring = statsMonitoring; + } + /** + * @return Returns the summaryMonitoring. + */ + public String getSummaryMonitoring() { + return summaryMonitoring; + } + /** + * @param summaryMonitoring The summaryMonitoring to set. + */ + public void setSummaryMonitoring(String summaryMonitoring) { + this.summaryMonitoring = summaryMonitoring; + } + /** + * @return Returns the edit. + */ + public String getEdit() { + return edit; + } + /** + * @param edit The edit to set. + */ + public void setEdit(String edit) { + this.edit = edit; + } + + /** + * @return Returns the submitOfflineFile. + */ + public String getSubmitOfflineFile() { + return submitOfflineFile; + } + /** + * @param submitOfflineFile The submitOfflineFile to set. + */ + public void setSubmitOfflineFile(String submitOfflineFile) { + this.submitOfflineFile = submitOfflineFile; + } + /** + * @param theOfflineFile The theOfflineFile to set. + */ + public void setTheOfflineFile(FormFile theOfflineFile) { + this.theOfflineFile = theOfflineFile; + } + /** + * @param theOnlineFile The theOnlineFile to set. + */ + public void setTheOnlineFile(FormFile theOnlineFile) { + this.theOnlineFile = theOnlineFile; + } + /** + * @return Returns the theOfflineFile. + */ + public FormFile getTheOfflineFile() { + return theOfflineFile; + } + /** + * @return Returns the theOnlineFile. + */ + public FormFile getTheOnlineFile() { + return theOnlineFile; + } + /** + * @return Returns the submitOnlineFile. + */ + public String getSubmitOnlineFile() { + return submitOnlineFile; + } + /** + * @param submitOnlineFile The submitOnlineFile to set. + */ + public void setSubmitOnlineFile(String submitOnlineFile) { + this.submitOnlineFile = submitOnlineFile; + } + /** + * @return Returns the richTextOfflineInstructions. + */ + public String getRichTextOfflineInstructions() { + return richTextOfflineInstructions; + } + /** + * @param richTextOfflineInstructions The richTextOfflineInstructions to set. + */ + public void setRichTextOfflineInstructions( + String richTextOfflineInstructions) { + this.richTextOfflineInstructions = richTextOfflineInstructions; + } + /** + * @return Returns the richTextOnlineInstructions. + */ + public String getRichTextOnlineInstructions() { + return richTextOnlineInstructions; + } + /** + * @param richTextOnlineInstructions The richTextOnlineInstructions to set. + */ + public void setRichTextOnlineInstructions(String richTextOnlineInstructions) { + this.richTextOnlineInstructions = richTextOnlineInstructions; + } + /** + * @return Returns the editDefaultQuestion. + */ + public String getEditDefaultQuestion() { + return editDefaultQuestion; + } + /** + * @param editDefaultQuestion The editDefaultQuestion to set. + */ + public void setEditDefaultQuestion(String editDefaultQuestion) { + this.editDefaultQuestion = editDefaultQuestion; + } + /** + * @return Returns the addOptionContent. + */ + public String getAddOptionContent() { + return addOptionContent; + } + /** + * @param addOptionContent The addOptionContent to set. + */ + public void setAddOptionContent(String addOptionContent) { + this.addOptionContent = addOptionContent; + } + /** + * @return Returns the removeOptionContent. + */ + public String getRemoveOptionContent() { + return removeOptionContent; + } + /** + * @param removeOptionContent The removeOptionContent to set. + */ + public void setRemoveOptionContent(String removeOptionContent) { + this.removeOptionContent = removeOptionContent; + } + /** + * @return Returns the addQuestion. + */ + public String getAddQuestion() { + return addQuestion; + } + /** + * @param addQuestion The addQuestion to set. + */ + public void setAddQuestion(String addQuestion) { + this.addQuestion = addQuestion; + } + /** + * @return Returns the removeQuestion. + */ + public String getRemoveQuestion() { + return removeQuestion; + } + /** + * @param removeQuestion The removeQuestion to set. + */ + public void setRemoveQuestion(String removeQuestion) { + this.removeQuestion = removeQuestion; + } + /** + * @return Returns the editOptions. + */ + public String getEditOptions() { + return editOptions; + } + /** + * @param editOptions The editOptions to set. + */ + public void setEditOptions(String editOptions) { + this.editOptions = editOptions; + } + /** + * @return Returns the addOption. + */ + public String getAddOption() { + return addOption; + } + /** + * @param addOption The addOption to set. + */ + public void setAddOption(String addOption) { + this.addOption = addOption; + } + /** + * @return Returns the optionIndex. + */ + public String getOptionIndex() { + return optionIndex; + } + /** + * @param optionIndex The optionIndex to set. + */ + public void setOptionIndex(String optionIndex) { + this.optionIndex = optionIndex; + } + /** + * @return Returns the retries. + */ + public String getRetries() { + return retries; + } + /** + * @param retries The retries to set. + */ + public void setRetries(String retries) { + this.retries = retries; + } + /** + * @return Returns the showFeedback. + */ + public String getShowFeedback() { + return showFeedback; + } + /** + * @param showFeedback The showFeedback to set. + */ + public void setShowFeedback(String showFeedback) { + this.showFeedback = showFeedback; + } + /** + * @return Returns the passmark. + */ + public String getPassmark() { + return passmark; + } + /** + * @param passmark The passmark to set. + */ + public void setPassmark(String passmark) { + this.passmark = passmark; + } + /** + * @return Returns the removeOption. + */ + public String getRemoveOption() { + return removeOption; + } + /** + * @param removeOption The removeOption to set. + */ + public void setRemoveOption(String removeOption) { + this.removeOption = removeOption; + } + /** + * @return Returns the doneOptions. + */ + public String getDoneOptions() { + return doneOptions; + } + /** + * @param doneOptions The doneOptions to set. + */ + public void setDoneOptions(String doneOptions) { + this.doneOptions = doneOptions; + } + /** + * @return Returns the submitQuestions. + */ + public String getSubmitQuestions() { + return submitQuestions; + } + /** + * @param submitQuestions The submitQuestions to set. + */ + public void setSubmitQuestions(String submitQuestions) { + this.submitQuestions = submitQuestions; + } + /** + * @return Returns the selectedIndex. + */ + public String getSelectedIndex() { + return selectedIndex; + } + /** + * @param selectedIndex The selectedIndex to set. + */ + public void setSelectedIndex(String selectedIndex) { + this.selectedIndex = selectedIndex; + } + /** + * @return Returns the advancedTabDone. + */ + public String getAdvancedTabDone() { + return advancedTabDone; + } + /** + * @param advancedTabDone The advancedTabDone to set. + */ + public void setAdvancedTabDone(String advancedTabDone) { + this.advancedTabDone = advancedTabDone; + } + /** + * @return Returns the instructionsTabDone. + */ + public String getInstructionsTabDone() { + return instructionsTabDone; + } + /** + * @param instructionsTabDone The instructionsTabDone to set. + */ + public void setInstructionsTabDone(String instructionsTabDone) { + this.instructionsTabDone = instructionsTabDone; + } + /** + * @return Returns the deletableOptionIndex. + */ + public String getDeletableOptionIndex() { + return deletableOptionIndex; + } + /** + * @param deletableOptionIndex The deletableOptionIndex to set. + */ + public void setDeletableOptionIndex(String deletableOptionIndex) { + this.deletableOptionIndex = deletableOptionIndex; + } + /** + * @return Returns the sln. + */ + public String getSln() { + return sln; + } + /** + * @param sln The sln to set. + */ + public void setSln(String sln) { + this.sln = sln; + } + /** + * @return Returns the moveDown. + */ + public String getMoveDown() { + return moveDown; + } + /** + * @param moveDown The moveDown to set. + */ + public void setMoveDown(String moveDown) { + this.moveDown = moveDown; + } + /** + * @return Returns the moveUp. + */ + public String getMoveUp() { + return moveUp; + } + /** + * @param moveUp The moveUp to set. + */ + public void setMoveUp(String moveUp) { + this.moveUp = moveUp; + } + /** + * @return Returns the fileItem. + */ + public String getFileItem() { + return fileItem; + } + /** + * @param fileItem The fileItem to set. + */ + public void setFileItem(String fileItem) { + this.fileItem = fileItem; + } + /** + * @return Returns the viewFileItem. + */ + public String getViewFileItem() { + return viewFileItem; + } + /** + * @param viewFileItem The viewFileItem to set. + */ + public void setViewFileItem(String viewFileItem) { + this.viewFileItem = viewFileItem; + } + /** + * @return Returns the receivedFile. + */ + public FormFile getReceivedFile() { + return receivedFile; + } + /** + * @param receivedFile The receivedFile to set. + */ + public void setReceivedFile(FormFile receivedFile) { + this.receivedFile = receivedFile; + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McLearningForm.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McLearningForm.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McLearningForm.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,207 @@ +package org.lamsfoundation.lams.tool.mc.web; + + +import org.apache.struts.action.ActionForm; +import org.lamsfoundation.lams.tool.mc.McAppConstants; + +/** + * @author Ozgur Demirtas + * + * ActionForm for the Learning environment + */ +public class McLearningForm extends ActionForm implements McAppConstants { + protected String optionCheckBoxSelected; + protected String questionIndex; + protected String optionIndex; + protected String optionValue; + protected String checked; + + protected String continueOptions; + protected String nextOptions; + protected String continueOptionsCombined; + protected String redoQuestions; + protected String viewSummary; + protected String viewAnswers; + protected String learnerFinished; + protected String redoQuestionsOk; + + public void resetCommands() + { + this.setContinueOptions(null); + this.setNextOptions(null); + this.setContinueOptionsCombined(null); + this.setRedoQuestions( null); + this.setViewSummary(null); + this.setViewAnswers(null); + this.setRedoQuestionsOk(null); + this.setLearnerFinished(null); + } + + public void resetParameters() + { + this.setOptionCheckBoxSelected(null); + this.setQuestionIndex(null); + this.setOptionIndex(null); + this.setChecked(null); + this.setOptionValue(null); + } + + + /** + * @return Returns the continueOptions. + */ + public String getContinueOptions() { + return continueOptions; + } + /** + * @param continueOptions The continueOptions to set. + */ + public void setContinueOptions(String continueOptions) { + this.continueOptions = continueOptions; + } + /** + * @return Returns the checked. + */ + public String getChecked() { + return checked; + } + /** + * @param checked The checked to set. + */ + public void setChecked(String checked) { + this.checked = checked; + } + /** + * @return Returns the optionCheckBoxSelected. + */ + public String getOptionCheckBoxSelected() { + return optionCheckBoxSelected; + } + /** + * @param optionCheckBoxSelected The optionCheckBoxSelected to set. + */ + public void setOptionCheckBoxSelected(String optionCheckBoxSelected) { + this.optionCheckBoxSelected = optionCheckBoxSelected; + } + /** + * @return Returns the optionIndex. + */ + public String getOptionIndex() { + return optionIndex; + } + /** + * @param optionIndex The optionIndex to set. + */ + public void setOptionIndex(String optionIndex) { + this.optionIndex = optionIndex; + } + /** + * @return Returns the questionIndex. + */ + public String getQuestionIndex() { + return questionIndex; + } + /** + * @param questionIndex The questionIndex to set. + */ + public void setQuestionIndex(String questionIndex) { + this.questionIndex = questionIndex; + } + + /** + * @return Returns the viewSummary. + */ + public String getViewSummary() { + return viewSummary; + } + /** + * @param viewSummary The viewSummary to set. + */ + public void setViewSummary(String viewSummary) { + this.viewSummary = viewSummary; + } + /** + * @return Returns the continueOptionsCombined. + */ + public String getContinueOptionsCombined() { + return continueOptionsCombined; + } + /** + * @param continueOptionsCombined The continueOptionsCombined to set. + */ + public void setContinueOptionsCombined(String continueOptionsCombined) { + this.continueOptionsCombined = continueOptionsCombined; + } + /** + * @return Returns the redoQuestions. + */ + public String getRedoQuestions() { + return redoQuestions; + } + /** + * @param redoQuestions The redoQuestions to set. + */ + public void setRedoQuestions(String redoQuestions) { + this.redoQuestions = redoQuestions; + } + /** + * @return Returns the optionValue. + */ + public String getOptionValue() { + return optionValue; + } + /** + * @param optionValue The optionValue to set. + */ + public void setOptionValue(String optionValue) { + this.optionValue = optionValue; + } + /** + * @return Returns the viewAnswers. + */ + public String getViewAnswers() { + return viewAnswers; + } + /** + * @param viewAnswers The viewAnswers to set. + */ + public void setViewAnswers(String viewAnswers) { + this.viewAnswers = viewAnswers; + } + /** + * @return Returns the redoQuestionsOk. + */ + public String getRedoQuestionsOk() { + return redoQuestionsOk; + } + /** + * @param redoQuestionsOk The redoQuestionsOk to set. + */ + public void setRedoQuestionsOk(String redoQuestionsOk) { + this.redoQuestionsOk = redoQuestionsOk; + } + /** + * @return Returns the nextOptions. + */ + public String getNextOptions() { + return nextOptions; + } + /** + * @param nextOptions The nextOptions to set. + */ + public void setNextOptions(String nextOptions) { + this.nextOptions = nextOptions; + } + /** + * @return Returns the learnerFinished. + */ + public String getLearnerFinished() { + return learnerFinished; + } + /** + * @param learnerFinished The learnerFinished to set. + */ + public void setLearnerFinished(String learnerFinished) { + this.learnerFinished = learnerFinished; + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McLearningStarterAction.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McLearningStarterAction.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McLearningStarterAction.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,472 @@ + +package org.lamsfoundation.lams.tool.mc.web; + +import java.io.IOException; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.log4j.Logger; +import org.apache.struts.Globals; +import org.apache.struts.action.Action; +import org.apache.struts.action.ActionForm; +import org.apache.struts.action.ActionForward; +import org.apache.struts.action.ActionMapping; +import org.apache.struts.action.ActionMessage; +import org.apache.struts.action.ActionMessages; +import org.lamsfoundation.lams.tool.exception.ToolException; +import org.lamsfoundation.lams.tool.mc.McAppConstants; +import org.lamsfoundation.lams.tool.mc.McApplicationException; +import org.lamsfoundation.lams.tool.mc.McComparator; +import org.lamsfoundation.lams.tool.mc.McContent; +import org.lamsfoundation.lams.tool.mc.McQueContent; +import org.lamsfoundation.lams.tool.mc.McQueUsr; +import org.lamsfoundation.lams.tool.mc.McSession; +import org.lamsfoundation.lams.tool.mc.McUtils; +import org.lamsfoundation.lams.tool.mc.service.IMcService; +import org.lamsfoundation.lams.tool.mc.service.McServiceProxy; +import org.lamsfoundation.lams.usermanagement.dto.UserDTO; +import org.lamsfoundation.lams.web.session.SessionManager; +import org.lamsfoundation.lams.web.util.AttributeNames; + + +/** + * + * @author Ozgur Demirtas + * + * /&userId=&toolSessionId=123&mode=teacher + + * Tool Session: + * + * A tool session is the concept by which which the tool and the LAMS core manage a set of learners interacting with the tool. + * The tool session id (toolSessionId) is generated by the LAMS core and given to the tool. + * A tool session represents the use of a tool for a particulate activity for a group of learners. + * So if an activity is ungrouped, then one tool session exist for for a tool activity in a learning design. + * + * More details on the tool session id are covered under monitoring. + * When thinking about the tool content id and the tool session id, it might be helpful to think about the tool content id + * relating to the definition of an activity, whereas the tool session id relates to the runtime participation in the activity. + + * * + * Learner URL: + * The learner url display the screen(s) that the learner uses to participate in the activity. + * When the learner accessed this user, it will have a tool access mode ToolAccessMode.LEARNER. + * + * It is the responsibility of the tool to record the progress of the user. + * If the tool is a multistage tool, for example asking a series of questions, the tool must keep track of what the learner has already done. + * If the user logs out and comes back to the tool later, then the tool should resume from where the learner stopped. + * When the user is completed with tool, then the tool notifies the progress engine by calling + * org.lamsfoundation.lams.learning.service.completeToolSession(Long toolSessionId, User learner). + * + * If the tool's content DefineLater flag is set to true, then the learner should see a "Please wait for the teacher to define this part...." + * style message. + * If the tool's content RunOffline flag is set to true, then the learner should see a "This activity is not being done on the computer. + * Please see your instructor for details." + * + * ?? Would it be better to define a run offline message in the tool? We have instructions for the teacher but not the learner. ?? + * If the tool has a LockOnFinish flag, then the tool should lock learner's entries once they have completed the activity. + * If they return to the activity (e.g. via the progress bar) then the entries should be read only. + * + */ + +public class McLearningStarterAction extends Action implements McAppConstants { + static Logger logger = Logger.getLogger(McLearningStarterAction.class.getName()); + /* Since the toolSessionId is passed, we will derive toolContentId from the toolSessionId + * + * This class is used to load the default content and initialize the presentation Map for Learner mode + * + * createToolSession will not be called once the tool is deployed. + * + * It is important that ALL the session attributes created in this action gets removed by: QaUtils.cleanupSession(request) + */ + + public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException, McApplicationException { + Map mapQuestionsContent= new TreeMap(new McComparator()); + Map mapAnswers= new TreeMap(new McComparator()); + + IMcService mcService = McUtils.getToolService(request); + logger.debug("retrieving mcService from session: " + mcService); + if (mcService == null) + { + mcService = McServiceProxy.getMcService(getServlet().getServletContext()); + logger.debug("retrieving mcService from proxy: " + mcService); + request.getSession().setAttribute(TOOL_SERVICE, mcService); + } + + setupPaths(request); + McLearningForm mcLearningForm = (McLearningForm) form; + + /* + * initialize available question display modes in the session + */ + request.getSession().setAttribute(QUESTION_LISTING_MODE_SEQUENTIAL,QUESTION_LISTING_MODE_SEQUENTIAL); + request.getSession().setAttribute(QUESTION_LISTING_MODE_COMBINED, QUESTION_LISTING_MODE_COMBINED); + + /* + * mark the http session as a learning activity + */ + request.getSession().setAttribute(TARGET_MODE,TARGET_MODE_LEARNING); + + /* + * persist time zone information to session scope. + */ + McUtils.persistTimeZone(request); + ActionForward validateParameters=validateParameters(request, mapping); + logger.debug("validateParamaters: " + validateParameters); + if (validateParameters != null) + { + return validateParameters; + } + + Long toolSessionID=(Long) request.getSession().getAttribute(TOOL_SESSION_ID); + logger.debug("retrieved toolSessionID: " + toolSessionID); + /* + * 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. + */ + + if (!McUtils.existsSession(toolSessionID, request)) + { + logger.debug("tool session does not exist" + toolSessionID); + /* + *for testing only, remove this line in development + */ + Long currentToolContentId= new Long(1234); + logger.debug("simulating container behaviour: calling createToolSession with toolSessionId : " + + toolSessionID + " and toolContentId: " + currentToolContentId); + try + { + mcService.createToolSession(toolSessionID, currentToolContentId); + logger.debug("simulated container behaviour."); + } + catch(ToolException e) + { + logger.debug("we should never come here."); + } + + } + + /* + * 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 + */ + + McSession mcSession=mcService.retrieveMcSession(toolSessionID); + logger.debug("retrieving mcSession: " + mcSession); + + /* + * find out what content this tool session is referring to + * get the content for this tool session (many to one mapping) + */ + + /* + * Each passed tool session id points to a particular content. Many to one mapping. + */ + McContent mcContent=mcSession.getMcContent(); + logger.debug("using mcContent: " + mcContent); + request.getSession().setAttribute(TOOL_CONTENT_ID, mcContent.getMcContentId()); + logger.debug("using TOOL_CONTENT_ID: " + mcContent.getMcContentId()); + + request.getSession().setAttribute(TOOL_CONTENT_UID, mcContent.getUid()); + logger.debug("using TOOL_CONTENT_UID: " + mcContent.getUid()); + + /* + * The content we retrieved above must have been created before in Authoring time. + * And the passed tool session id already refers to it. + */ + setupAttributes(request, mcContent); + + + /* + * fetch question content from content + */ + Iterator contentIterator=mcContent.getMcQueContents().iterator(); + while (contentIterator.hasNext()) + { + McQueContent mcQueContent=(McQueContent)contentIterator.next(); + if (mcQueContent != null) + { + int displayOrder=mcQueContent.getDisplayOrder().intValue(); + if (displayOrder != 0) + { + /* add the question to the questions Map in the displayOrder*/ + mapQuestionsContent.put(new Integer(displayOrder).toString(),mcQueContent.getQuestion()); + } + + /* prepare the first question's candidate answers for presentation*/ + if (displayOrder == 1) + { + logger.debug("first question... "); + Long uid=mcQueContent.getUid(); + logger.debug("uid : " + uid); + List listMcOptions=mcService.findMcOptionsContentByQueId(uid); + logger.debug("listMcOptions : " + listMcOptions); + Map mapOptionsContent=McUtils.generateOptionsMap(listMcOptions); + request.getSession().setAttribute(MAP_OPTIONS_CONTENT, mapOptionsContent); + logger.debug("updated Options Map: " + request.getSession().getAttribute(MAP_OPTIONS_CONTENT)); + } + } + } + + request.getSession().setAttribute(MAP_QUESTION_CONTENT_LEARNER, mapQuestionsContent); + logger.debug("MAP_QUESTION_CONTENT_LEARNER: " + request.getSession().getAttribute(MAP_QUESTION_CONTENT_LEARNER)); + logger.debug("mcContent has : " + mapQuestionsContent.size() + " entries."); + request.getSession().setAttribute(TOTAL_QUESTION_COUNT, new Long(mapQuestionsContent.size()).toString()); + + request.getSession().setAttribute(CURRENT_QUESTION_INDEX, "1"); + logger.debug("CURRENT_QUESTION_INDEX: " + request.getSession().getAttribute(CURRENT_QUESTION_INDEX)); + logger.debug("final Options Map for the first question: " + request.getSession().getAttribute(MAP_OPTIONS_CONTENT)); + + /*also prepare data into mapGeneralOptionsContent for combined answers view */ + Map mapGeneralOptionsContent=AuthoringUtil.generateGeneralOptionsContentMap(request, mcContent); + logger.debug("returned mapGeneralOptionsContent: " + mapGeneralOptionsContent); + request.getSession().setAttribute(MAP_GENERAL_OPTIONS_CONTENT, mapGeneralOptionsContent); + + /* + * Verify that userId does not already exist in the db. + * If it does exist, that means, that user already responded to the content and + * his answers must be displayed read-only + * + */ + String userID=(String) request.getSession().getAttribute(USER_ID); + logger.debug("userID:" + userID); + + McQueUsr mcQueUsr=mcService.retrieveMcQueUsr(new Long(userID)); + logger.debug("mcQueUsr:" + mcQueUsr); + + if (mcQueUsr != null) + { + logger.debug("mcQueUsr is available in the db:" + mcQueUsr); + Long queUsrId=mcQueUsr.getUid(); + logger.debug("queUsrId: " + queUsrId); + + int highestAttemptOrder=LearningUtil.getHighestAttemptOrder(request, queUsrId); + logger.debug("highestAttemptOrder: " + highestAttemptOrder); + if (highestAttemptOrder == 0) + highestAttemptOrder=1; + logger.debug("highestAttemptOrder: " + highestAttemptOrder); + request.getSession().setAttribute(LEARNER_LAST_ATTEMPT_ORDER,new Integer(highestAttemptOrder).toString()); + + int learnerBestMark=LearningUtil.getHighestMark(request, queUsrId); + logger.debug("learnerBestMark: " + learnerBestMark); + request.getSession().setAttribute(LEARNER_BEST_MARK,new Integer(learnerBestMark).toString()); + } + else + { + logger.debug("mcQueUsr is not available in the db:" + mcQueUsr); + request.getSession().setAttribute(LEARNER_LAST_ATTEMPT_ORDER,new Integer(1).toString()); + request.getSession().setAttribute(LEARNER_BEST_MARK,new Integer(0).toString()); + + } + + + if (mcQueUsr != null) + { + logger.debug("the learner has already responsed to this content, just generate a read-only report. Use redo questions for this."); + return (mapping.findForward(REDO_QUESTIONS)); + } + + return (mapping.findForward(LOAD_LEARNER)); + } + + + /** + * sets up session scope attributes based on content linked to the passed tool session id + * setupAttributes(HttpServletRequest request, McContent mcContent) + * + * @param request + * @param mcContent + */ + protected void setupAttributes(HttpServletRequest request, McContent mcContent) + { + /* returns Integer: can be 0 or greater than 0, 0 is no passmark, otherwise there is a passmark. */ + logger.debug("PASSMARK: " + mcContent.getPassMark()); + if (mcContent.getPassMark() != null) + { + int passMark=mcContent.getPassMark().intValue(); + request.getSession().setAttribute(PASSMARK, mcContent.getPassMark()); + } + else + { + request.getSession().setAttribute(PASSMARK, new Integer(0)); + } + + request.getSession().setAttribute(IS_SHOW_LEARNERS_REPORT, new Boolean(mcContent.isShowReport()).toString()); + logger.debug("IS_SHOW_LEARNERS_REPORT: " + new Boolean(mcContent.isShowReport()).toString()); + + /* same as 1 page per question */ + logger.debug("IS_QUESTIONS_SEQUENCED: " + mcContent.isQuestionsSequenced()); + if (mcContent.isQuestionsSequenced()) + { + request.getSession().setAttribute(QUESTION_LISTING_MODE, QUESTION_LISTING_MODE_SEQUENTIAL); + } + else + { + request.getSession().setAttribute(QUESTION_LISTING_MODE, QUESTION_LISTING_MODE_COMBINED); + } + logger.debug("QUESTION_LISTING_MODE: " + request.getSession().getAttribute(QUESTION_LISTING_MODE)); + + logger.debug("IS_RETRIES: " + new Boolean(mcContent.isRetries()).toString()); + request.getSession().setAttribute(IS_RETRIES, new Boolean(mcContent.isRetries()).toString()); + + logger.debug("REPORT_TITLE_LEARNER: " + mcContent.getReportTitle()); + request.getSession().setAttribute(REPORT_TITLE_LEARNER,mcContent.getReportTitle()); + + request.getSession().setAttribute(END_LEARNING_MESSAGE,mcContent.getEndLearningMessage()); + logger.debug("END_LEARNING_MESSAGE: " + mcContent.getEndLearningMessage()); + + logger.debug("IS_CONTENT_IN_USE: " + mcContent.isContentInUse()); + request.getSession().setAttribute(IS_CONTENT_IN_USE, new Boolean(mcContent.isContentInUse()).toString()); + + /* + * Is the tool activity been checked as Define Later in the property inspector? + */ + logger.debug("IS_DEFINE_LATER: " + mcContent.isDefineLater()); + request.getSession().setAttribute(IS_DEFINE_LATER, new Boolean(mcContent.isDefineLater()).toString()); + + /* + * Is the tool activity been checked as Run Offline in the property inspector? + */ + logger.debug("IS_TOOL_ACTIVITY_OFFLINE: " + mcContent.isRunOffline()); + request.getSession().setAttribute(IS_TOOL_ACTIVITY_OFFLINE, new Boolean(mcContent.isRunOffline()).toString()); + + + /* the following attributes are unused for the moment. + * from here... + */ + logger.debug("ACTIVITY_TITLE: " + mcContent.getTitle()); + request.getSession().setAttribute(ACTIVITY_TITLE,mcContent.getTitle()); + + logger.debug("ACTIVITY_INSTRUCTIONS: " + mcContent.getInstructions()); + request.getSession().setAttribute(ACTIVITY_INSTRUCTIONS,mcContent.getInstructions()); + + logger.debug("IS_USERNAME_VISIBLE: " + mcContent.isUsernameVisible()); + request.getSession().setAttribute(IS_USERNAME_VISIBLE, new Boolean(mcContent.isUsernameVisible()).toString()); + + logger.debug("IS_SHOW_FEEDBACK: " + new Boolean(mcContent.isShowFeedback()).toString()); + request.getSession().setAttribute(IS_SHOW_FEEDBACK, new Boolean(mcContent.isShowFeedback()).toString()); + + Map mapGeneralCheckedOptionsContent= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_GENERAL_CHECKED_OPTIONS_CONTENT, mapGeneralCheckedOptionsContent); + + Map mapLeanerCheckedOptionsContent= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_LEARNER_CHECKED_OPTIONS_CONTENT, mapLeanerCheckedOptionsContent); + + Map mapLeanerAssessmentResults= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_LEARNER_ASSESSMENT_RESULTS, mapLeanerAssessmentResults); + + Map mapLeanerFeedbackIncorrect=AuthoringUtil.buildInCorrectFeedbackMap(request, mcContent.getMcContentId()); + request.getSession().setAttribute(MAP_LEARNER_FEEDBACK_INCORRECT, mapLeanerFeedbackIncorrect); + logger.debug("MAP_LEARNER_FEEDBACK_INCORRECT: " + mapLeanerFeedbackIncorrect); + + Map mapLeanerFeedbackCorrect=AuthoringUtil.buildCorrectFeedbackMap(request, mcContent.getMcContentId()); + request.getSession().setAttribute(MAP_LEARNER_FEEDBACK_CORRECT, mapLeanerFeedbackCorrect); + logger.debug("MAP_LEARNER_FEEDBACK_CORRECT: " + mapLeanerFeedbackCorrect); + + Map mapQuestionWeights=LearningUtil.buildWeightsMap(request, mcContent.getMcContentId()); + request.getSession().setAttribute(MAP_QUESTION_WEIGHTS, mapQuestionWeights); + logger.debug("MAP_QUESTION_WEIGHTS: " + mapQuestionWeights); + /* .. till here */ + } + + + protected ActionForward validateParameters(HttpServletRequest request, ActionMapping mapping) + { + /* + * obtain and setup the current user's data + */ + + String userID = ""; + /* get session from shared session.*/ + HttpSession ss = SessionManager.getSession(); + /* get back login user DTO*/ + UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); + if ((user == null) || (user.getUserID() == null)) + { + logger.debug("error: The tool expects userId"); + persistError(request,"error.learningUser.notAvailable"); + request.setAttribute(USER_EXCEPTION_USERID_NOTAVAILABLE, new Boolean(true)); + return (mapping.findForward(ERROR_LIST)); + }else + userID = user.getUserID().toString(); + + logger.debug("retrieved userId: " + userID); + request.getSession().setAttribute(USER_ID, userID); + + + /* + * process incoming tool session id and later derive toolContentId from it. + */ + String strToolSessionId=request.getParameter(TOOL_SESSION_ID); + long toolSessionId=0; + if ((strToolSessionId == null) || (strToolSessionId.length() == 0)) + { + persistError(request, "error.toolSessionId.required"); + request.setAttribute(USER_EXCEPTION_TOOLSESSIONID_REQUIRED, new Boolean(true)); + return (mapping.findForward(ERROR_LIST)); + } + else + { + try + { + toolSessionId=new Long(strToolSessionId).longValue(); + logger.debug("passed TOOL_SESSION_ID : " + new Long(toolSessionId)); + request.getSession().setAttribute(TOOL_SESSION_ID,new Long(toolSessionId)); + } + catch(NumberFormatException e) + { + persistError(request, "error.sessionId.numberFormatException"); + logger.debug("add error.sessionId.numberFormatException to ActionMessages."); + request.setAttribute(USER_EXCEPTION_NUMBERFORMAT, new Boolean(true)); + return (mapping.findForward(ERROR_LIST)); + } + } + return null; + } + + + /** + * sets up ROOT_PATH and PATH_TO_LAMS attributes for presentation purposes + * setupPaths(HttpServletRequest request) + * @param request + */ + protected void setupPaths(HttpServletRequest request) + { + String protocol = request.getProtocol(); + if(protocol.startsWith("HTTPS")){ + protocol = "https://"; + }else{ + protocol = "http://"; + } + String root = protocol+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/"; + String pathToLams = protocol+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/../.."; + request.getSession().setAttribute(ROOT, root); + request.getSession().setAttribute(ROOT_PATH, root); + request.getSession().setAttribute(PATH_TO_LAMS, pathToLams); + + logger.debug("setting root to: " + request.getSession().getAttribute(ROOT)); + } + + /** + * persists error messages to request scope + * @param request + * @param message + */ + public void persistError(HttpServletRequest request, String message) + { + ActionMessages errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY, new ActionMessage(message)); + logger.debug("add " + message +" to ActionMessages:"); + saveErrors(request,errors); + } +} Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McStarterAction.java =================================================================== diff -u --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McStarterAction.java (revision 0) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/mc/web/McStarterAction.java (revision 5f8c01a75dfd1323be7280810229d7ccd0ead2b7) @@ -0,0 +1,645 @@ +/** + * @author Ozgur Demirtas + * + * McStarterAction loads the default content and initializes the presentation Map. + * Initializes the tool's authoring mode + * Requests can come either from authoring envuironment or from the monitoring environment for Edit Activity screen + * + * Tool path The URL path for the tool should be /tool/$TOOL_SIG. + * + + + + + + + +*/ + +package org.lamsfoundation.lams.tool.mc.web; +import java.io.IOException; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; +import org.apache.struts.Globals; +import org.apache.struts.action.Action; +import org.apache.struts.action.ActionForm; +import org.apache.struts.action.ActionForward; +import org.apache.struts.action.ActionMapping; +import org.apache.struts.action.ActionMessage; +import org.apache.struts.action.ActionMessages; +import org.lamsfoundation.lams.tool.mc.McAppConstants; +import org.lamsfoundation.lams.tool.mc.McApplicationException; +import org.lamsfoundation.lams.tool.mc.McComparator; +import org.lamsfoundation.lams.tool.mc.McContent; +import org.lamsfoundation.lams.tool.mc.McOptsContent; +import org.lamsfoundation.lams.tool.mc.McQueContent; +import org.lamsfoundation.lams.tool.mc.McUtils; +import org.lamsfoundation.lams.tool.mc.service.IMcService; +import org.lamsfoundation.lams.tool.mc.service.McServiceProxy; + +public class McStarterAction extends Action implements McAppConstants { + /* + * CONTENT_LOCKED refers to content being in use or not: Any students answered that content? + * For future CONTENT_LOCKED ->CONTENT_IN_USE + * + * may use org.lamsfoundation.lams.web.util.AttributeNames + * check back McUtils.configureContentRepository(request); + */ + static Logger logger = Logger.getLogger(McStarterAction.class.getName()); + + public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException, McApplicationException { + IMcService mcService = McUtils.getToolService(request); + logger.debug("retrieving mcService from session: " + mcService); + if (mcService == null) + { + mcService = McServiceProxy.getMcService(getServlet().getServletContext()); + logger.debug("retrieving mcService from proxy: " + mcService); + request.getSession().setAttribute(TOOL_SERVICE, mcService); + } + + setupPaths(request); + initialiseAttributes(request); + + McAuthoringForm mcAuthoringForm = (McAuthoringForm) form; + mcAuthoringForm.resetRadioBoxes(); + + ActionForward validateParameters=populateParameters(request,mapping); + logger.debug("validateParameters: " + validateParameters); + if (validateParameters != null) + { + logger.debug("validateParameters not null : " + validateParameters); + return validateParameters; + } + else + { + /* mark the http session as an authoring activity */ + request.getSession().setAttribute(TARGET_MODE,TARGET_MODE_AUTHORING); + + /* define tab controllers for jsp */ + request.getSession().setAttribute(CHOICE_TYPE_BASIC,CHOICE_TYPE_BASIC); + request.getSession().setAttribute(CHOICE_TYPE_ADVANCED,CHOICE_TYPE_ADVANCED); + request.getSession().setAttribute(CHOICE_TYPE_INSTRUCTIONS,CHOICE_TYPE_INSTRUCTIONS); + + logger.debug("will render authoring screen"); + String strToolContentId=""; + strToolContentId=request.getParameter(TOOL_CONTENT_ID); + + /* Process incoming tool content id. + * Either exists or not exists in the db yet, a toolContentId must be passed to the tool from the container */ + long toolContentId=0; + try + { + toolContentId=new Long(strToolContentId).longValue(); + logger.debug("passed TOOL_CONTENT_ID : " + toolContentId); + request.getSession().setAttribute(TOOL_CONTENT_ID, new Long(strToolContentId)); + } + catch(NumberFormatException e) + { + persistError(request,"error.numberFormatException"); + request.setAttribute(USER_EXCEPTION_NUMBERFORMAT, new Boolean(true)); + logger.debug("forwarding to: " + LOAD_QUESTIONS); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + /* + * find out if the passed tool content id exists in the db + * present user either a first timer screen with default content data or fetch the existing content. + * + * if the toolcontentid does not exist in the db, create the default Map, + * there is no need to check if the content is in use in this case. + * It is always unlocked -> not in use since it is the default content. + */ + if (!existsContent(toolContentId, request)) + { + logger.debug("retrieving default content"); + retrieveDefaultContent(request, mcAuthoringForm); + } + else + { + logger.debug("retrieving existing content for: " + toolContentId); + retrieveExistingContent(request, mcAuthoringForm, toolContentId); + } + } + mcAuthoringForm.resetUserAction(); + return (mapping.findForward(LOAD_QUESTIONS)); + } + + public ActionForward populateParameters(HttpServletRequest request, ActionMapping mapping) + { + IMcService mcService =McUtils.getToolService(request); + /* retrieve the default content id based on tool signature */ + long contentId=0; + try + { + logger.debug("attempt retrieving tool with signature : " + MY_SIGNATURE); + contentId=mcService.getToolDefaultContentIdBySignature(MY_SIGNATURE); + logger.debug("retrieved tool default contentId: " + contentId); + if (contentId == 0) + { + logger.debug("default content id has not been setup"); + request.setAttribute(USER_EXCEPTION_DEFAULTCONTENT_NOTSETUP, new Boolean(true)); + persistError(request,"error.defaultContent.notSetup"); + return (mapping.findForward(ERROR_LIST)); + } + } + catch(Exception e) + { + logger.debug("error getting the default content id: " + e.getMessage()); + request.setAttribute(USER_EXCEPTION_DEFAULTCONTENT_NOTSETUP, new Boolean(true)); + persistError(request,"error.defaultContent.notSetup"); + return (mapping.findForward(ERROR_LIST)); + } + + /* retrieve uid of the content based on default content id determined above */ + long contentUID=0; + try + { + logger.debug("retrieve uid of the content based on default content id determined above: " + contentId); + McContent mcContent=mcService.retrieveMc(new Long(contentId)); + if (mcContent == null) + { + logger.debug("Exception occured: No default content"); + request.setAttribute(USER_EXCEPTION_DEFAULTCONTENT_NOTSETUP, new Boolean(true)); + persistError(request,"error.defaultContent.notSetup"); + return (mapping.findForward(ERROR_LIST)); + } + logger.debug("using mcContent: " + mcContent); + logger.debug("using mcContent uid: " + mcContent.getUid()); + contentUID=mcContent.getUid().longValue(); + } + catch(Exception e) + { + logger.debug("Exception occured: No default question content"); + request.setAttribute(USER_EXCEPTION_DEFAULTCONTENT_NOTSETUP, new Boolean(true)); + persistError(request,"error.defaultContent.notSetup"); + return (mapping.findForward(ERROR_LIST)); + } + + + /* retrieve uid of the default question content */ + long queContentUID=0; + try + { + logger.debug("retrieve the default question content based on default content UID: " + queContentUID); + McQueContent mcQueContent=mcService.getToolDefaultQuestionContent(contentUID); + logger.debug("using mcQueContent: " + mcQueContent); + if (mcQueContent == null) + { + logger.debug("Exception occured: No default question content"); + request.setAttribute(USER_EXCEPTION_DEFAULTQUESTIONCONTENT_NOT_AVAILABLE, new Boolean(true)); + persistError(request,"error.defaultQuestionContent.notAvailable"); + return (mapping.findForward(ERROR_LIST)); + } + logger.debug("using mcQueContent uid: " + mcQueContent.getUid()); + queContentUID=mcQueContent.getUid().longValue(); + request.getSession().setAttribute(DEFAULT_QUESTION_UID, new Long(queContentUID)); + logger.debug("DEFAULT_QUESTION_UID: " + queContentUID); + } + catch(Exception e) + { + logger.debug("Exception occured: No default question content"); + request.setAttribute(USER_EXCEPTION_DEFAULTQUESTIONCONTENT_NOT_AVAILABLE, new Boolean(true)); + persistError(request,"error.defaultQuestionContent.notAvailable"); + return (mapping.findForward(ERROR_LIST)); + } + + + /* retrieve default options content */ + try + { + logger.debug("retrieve the default options content based on default question content UID: " + queContentUID); + List list=mcService.findMcOptionsContentByQueId(new Long(queContentUID)); + logger.debug("using options list: " + list); + if (list == null) + { + logger.debug("Exception occured: No default options content"); + request.setAttribute(USER_EXCEPTION_DEFAULTOPTIONSCONTENT_NOT_AVAILABLE, new Boolean(true)); + persistError(request,"error.defaultOptionsContent.notAvailable"); + return (mapping.findForward(ERROR_LIST)); + } + + } + catch(Exception e) + { + logger.debug("Exception occured: No default options content"); + request.setAttribute(USER_EXCEPTION_DEFAULTOPTIONSCONTENT_NOT_AVAILABLE, new Boolean(true)); + persistError(request,"error.defaultOptionsContent.notAvailable"); + return (mapping.findForward(ERROR_LIST)); + } + + return null; + } + + + /** + * existsContent(long toolContentId) + * @param long toolContentId + * @return boolean + * determine whether a specific toolContentId exists in the db + */ + protected boolean existsContent(long toolContentId, HttpServletRequest request) + { + IMcService mcService =McUtils.getToolService(request); + McContent mcContent=mcService.retrieveMc(new Long(toolContentId)); + if (mcContent == null) + return false; + + return true; + } + + /** + * find out if the content is locked or not. If it is a locked content, the author can not modify it. + * The idea of content being locked is, once any one learner starts using a particular content + * that content should become unmodifiable. + * @param mcContent + * @return + */ + protected boolean isContentInUse(McContent mcContent) + { + logger.debug("is content inuse: " + mcContent.isContentInUse()); + return mcContent.isContentInUse(); + } + + + /** + * sets up ROOT_PATH and PATH_TO_LAMS attributes for presentation purposes + * setupPaths(HttpServletRequest request) + * @param request + */ + protected void setupPaths(HttpServletRequest request) + { + String protocol = request.getProtocol(); + if(protocol.startsWith("HTTPS")){ + protocol = "https://"; + }else{ + protocol = "http://"; + } + String root = protocol+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/"; + String pathToLams = protocol+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/../.."; + request.getSession().setAttribute(ROOT, root); + request.getSession().setAttribute(ROOT_PATH, root); + request.getSession().setAttribute(PATH_TO_LAMS, pathToLams); + + logger.debug("setting root to: " + request.getSession().getAttribute(ROOT)); + } + + + /** + * retrieves the contents of an existing content from the db and prepares it for presentation + * retrieveExistingContent(HttpServletRequest request, McAuthoringForm mcAuthoringForm, long toolContentId) + * + * @param request + * @param mcAuthoringForm + * @param toolContentId + */ + protected void retrieveExistingContent(HttpServletRequest request, McAuthoringForm mcAuthoringForm, long toolContentId) + { + IMcService mcService =McUtils.getToolService(request); + + logger.debug("getting existing content with id:" + toolContentId); + McContent mcContent=mcService.retrieveMc(new Long(toolContentId)); + logger.debug("existing mcContent:" + mcContent); + + request.getSession().setAttribute(RICHTEXT_TITLE,mcContent.getTitle()); + request.getSession().setAttribute(RICHTEXT_INSTRUCTIONS,mcContent.getInstructions()); + request.getSession().setAttribute(QUESTIONS_SEQUENCED,new Boolean(mcContent.isQuestionsSequenced())); + request.getSession().setAttribute(USERNAME_VISIBLE,new Boolean(mcContent.isUsernameVisible())); + request.getSession().setAttribute(CREATED_BY, new Long(mcContent.getCreatedBy())); + request.getSession().setAttribute(MONITORING_REPORT_TITLE,mcContent.getMonitoringReportTitle()); + request.getSession().setAttribute(REPORT_TITLE,mcContent.getReportTitle()); + request.getSession().setAttribute(RUN_OFFLINE, new Boolean(mcContent.isRunOffline())); + request.getSession().setAttribute(DEFINE_LATER, new Boolean(mcContent.isDefineLater())); + request.getSession().setAttribute(SYNCH_IN_MONITOR, new Boolean(mcContent.isSynchInMonitor())); + request.getSession().setAttribute(OFFLINE_INSTRUCTIONS,mcContent.getOfflineInstructions()); + request.getSession().setAttribute(ONLINE_INSTRUCTIONS,mcContent.getOnlineInstructions()); + request.getSession().setAttribute(RICHTEXT_OFFLINEINSTRUCTIONS,mcContent.getOfflineInstructions()); + request.getSession().setAttribute(RICHTEXT_ONLINEINSTRUCTIONS,mcContent.getOnlineInstructions()); + request.getSession().setAttribute(END_LEARNING_MESSAGE,mcContent.getEndLearningMessage()); + request.getSession().setAttribute(CONTENT_IN_USE, new Boolean(mcContent.isContentInUse())); + request.getSession().setAttribute(RETRIES, new Boolean(mcContent.isRetries())); + request.getSession().setAttribute(PASSMARK, mcContent.getPassMark()); //Integer + request.getSession().setAttribute(SHOW_FEEDBACK, new Boolean(mcContent.isShowFeedback())); + + McUtils.setDefaultSessionAttributes(request, mcContent, mcAuthoringForm); + logger.debug("RICHTEXT_TITLE:" + request.getSession().getAttribute(RICHTEXT_TITLE)); + + mcAuthoringForm.setPassmark((mcContent.getPassMark()).toString()); + logger.debug("PASSMARK:" + mcAuthoringForm.getPassmark()); + + logger.debug("getting name lists based on uid:" + mcContent.getUid()); + + List listUploadedOffFiles= mcService.retrieveMcUploadedOfflineFilesName(mcContent.getUid()); + logger.debug("existing listUploadedOfflineFileNames:" + listUploadedOffFiles); + request.getSession().setAttribute(LIST_UPLOADED_OFFLINE_FILENAMES,listUploadedOffFiles); + + List listUploadedOnFiles= mcService.retrieveMcUploadedOnlineFilesName(mcContent.getUid()); + logger.debug("existing listUploadedOnlineFileNames:" + listUploadedOnFiles); + request.getSession().setAttribute(LIST_UPLOADED_ONLINE_FILENAMES,listUploadedOnFiles); + + List listUploadedOffFilesUuidPlusFilename= mcService.retrieveMcUploadedOfflineFilesUuidPlusFilename(mcContent.getUid()); + logger.debug("existing listUploadedOffFilesUuidPlusFilename:" + listUploadedOffFilesUuidPlusFilename); + request.getSession().setAttribute(LIST_UPLOADED_OFFLINE_FILES,listUploadedOffFilesUuidPlusFilename); + + if (mcContent.isUsernameVisible()) + { + mcAuthoringForm.setUsernameVisible(ON); + logger.debug("setting userNameVisible to true"); + } + else + { + mcAuthoringForm.setUsernameVisible(OFF); + logger.debug("setting userNameVisible to false"); + } + + + if (mcContent.isQuestionsSequenced()) + { + mcAuthoringForm.setQuestionsSequenced(ON); + logger.debug("setting questionsSequenced to true"); + } + else + { + mcAuthoringForm.setQuestionsSequenced(OFF); + logger.debug("setting questionsSequenced to false"); + } + + if (mcContent.isSynchInMonitor()) + { + mcAuthoringForm.setSynchInMonitor(ON); + logger.debug("setting SynchInMonitor to true"); + } + else + { + mcAuthoringForm.setSynchInMonitor(OFF); + logger.debug("setting SynchInMonitor to false"); + } + + if (mcContent.isRetries()) + { + mcAuthoringForm.setRetries(ON); + logger.debug("setting retries to true"); + } + else + { + mcAuthoringForm.setRetries(OFF); + logger.debug("setting retries to false"); + } + + if (mcContent.isShowFeedback()) + { + mcAuthoringForm.setShowFeedback(ON); + logger.debug("setting showFeedback to true"); + } + else + { + mcAuthoringForm.setShowFeedback(OFF); + logger.debug("setting showFeedback to false"); + } + + if (mcContent.isShowReport()) + { + mcAuthoringForm.setSln(ON); + logger.debug("setting sln to true"); + } + else + { + mcAuthoringForm.setSln(OFF); + logger.debug("setting sln to false"); + } + + McUtils.populateUploadedFilesData(request, mcContent); + logger.debug("populated UploadedFilesData"); + Map mapWeights= AuthoringUtil.rebuildWeightsMapfromDB(request, new Long(toolContentId)); + logger.debug("mapWeights: " + mapWeights); + request.getSession().setAttribute(MAP_WEIGHTS, mapWeights); + + Map mapQuestionsContent=AuthoringUtil.rebuildQuestionMapfromDB(request, new Long(toolContentId)); + logger.debug("mapQuestionsContent:" + mapQuestionsContent); + request.getSession().setAttribute(MAP_QUESTIONS_CONTENT, mapQuestionsContent); + logger.debug("starter initialized the existing Questions Map: " + request.getSession().getAttribute(MAP_QUESTIONS_CONTENT)); + + AuthoringUtil.refreshMaps(request, toolContentId); + } + + + /** + * retrieves the contents of the default content from the db and prepares it for presentation + * retrieveDefaultContent(HttpServletRequest request, McAuthoringForm mcAuthoringForm) + * + * @param request + * @param mcAuthoringForm + */ + protected void retrieveDefaultContent(HttpServletRequest request, McAuthoringForm mcAuthoringForm) + { + IMcService mcService =McUtils.getToolService(request); + + long contentId=0; + logger.debug("getting default content"); + contentId=mcService.getToolDefaultContentIdBySignature(MY_SIGNATURE); + McContent mcContent=mcService.retrieveMc(new Long(contentId)); + logger.debug("mcContent:" + mcContent); + + /* reset all radioboxes to false*/ + mcAuthoringForm.resetRadioBoxes(); + logger.debug("all radioboxes arec reset"); + + request.getSession().setAttribute(RICHTEXT_TITLE,mcContent.getTitle()); + request.getSession().setAttribute(RICHTEXT_INSTRUCTIONS,mcContent.getInstructions()); + request.getSession().setAttribute(QUESTIONS_SEQUENCED,new Boolean(mcContent.isQuestionsSequenced())); + request.getSession().setAttribute(USERNAME_VISIBLE,new Boolean(mcContent.isUsernameVisible())); + request.getSession().setAttribute(CREATED_BY, new Long(mcContent.getCreatedBy())); + request.getSession().setAttribute(MONITORING_REPORT_TITLE,mcContent.getMonitoringReportTitle()); + request.getSession().setAttribute(REPORT_TITLE,mcContent.getReportTitle()); + request.getSession().setAttribute(RUN_OFFLINE, new Boolean(mcContent.isRunOffline())); + request.getSession().setAttribute(DEFINE_LATER, new Boolean(mcContent.isDefineLater())); + request.getSession().setAttribute(SYNCH_IN_MONITOR, new Boolean(mcContent.isSynchInMonitor())); + request.getSession().setAttribute(OFFLINE_INSTRUCTIONS,mcContent.getOfflineInstructions()); + request.getSession().setAttribute(ONLINE_INSTRUCTIONS,mcContent.getOnlineInstructions()); + request.getSession().setAttribute(RICHTEXT_OFFLINEINSTRUCTIONS,mcContent.getOfflineInstructions()); + request.getSession().setAttribute(RICHTEXT_ONLINEINSTRUCTIONS,mcContent.getOnlineInstructions()); + request.getSession().setAttribute(END_LEARNING_MESSAGE,mcContent.getEndLearningMessage()); + request.getSession().setAttribute(CONTENT_IN_USE, new Boolean(mcContent.isContentInUse())); + request.getSession().setAttribute(RETRIES, new Boolean(mcContent.isRetries())); + request.getSession().setAttribute(PASSMARK, mcContent.getPassMark()); //Integer + request.getSession().setAttribute(SHOW_FEEDBACK, new Boolean(mcContent.isShowFeedback())); + request.getSession().setAttribute(RICHTEXT_REPORT_TITLE,mcContent.getReportTitle()); + request.getSession().setAttribute(RICHTEXT_END_LEARNING_MSG,mcContent.getEndLearningMessage()); + + McUtils.setDefaultSessionAttributes(request, mcContent, mcAuthoringForm); + + logger.debug("PASSMARK:" + request.getSession().getAttribute(PASSMARK)); + + logger.debug("RICHTEXT_TITLE:" + request.getSession().getAttribute(RICHTEXT_TITLE)); + logger.debug("getting default content"); + /* + * this is a new content creation, the content must not be in use. + * relevant attribute: CONTENT_IN_USE + */ + request.getSession().setAttribute(CONTENT_IN_USE, new Boolean(false)); + logger.debug("CONTENT_IN_USE: " + request.getSession().getAttribute(CONTENT_IN_USE)); + + /* this is already done in mcAuthoringForm.resetRadioBoxes()*/ + mcAuthoringForm.setUsernameVisible(OFF); + mcAuthoringForm.setQuestionsSequenced(OFF); + mcAuthoringForm.setSynchInMonitor(OFF); + mcAuthoringForm.setRetries(OFF); + mcAuthoringForm.setShowFeedback(OFF); + mcAuthoringForm.setSln(OFF); + + /* collect options for the default question content into a Map*/ + McQueContent mcQueContent=mcService.getToolDefaultQuestionContent(mcContent.getUid().longValue()); + logger.debug("mcQueContent:" + mcQueContent); + + /* mcQueContent can not be null since here it was verified before*/ + /* display a single sample question */ + request.getSession().setAttribute(DEFAULT_QUESTION_CONTENT, mcQueContent.getQuestion()); + + Map mapQuestionsContent= new TreeMap(new McComparator()); + mapQuestionsContent.put(new Long(1).toString(), mcQueContent.getQuestion()); + request.getSession().setAttribute(MAP_QUESTIONS_CONTENT, mapQuestionsContent); + logger.debug("starter initialized the Questions Map: " + request.getSession().getAttribute(MAP_QUESTIONS_CONTENT)); + + /* hold all he options for this question*/ + List list=mcService.findMcOptionsContentByQueId(mcQueContent.getUid()); + logger.debug("options list:" + list); + + Map mapOptionsContent= new TreeMap(new McComparator()); + Iterator listIterator=list.iterator(); + Long mapIndex=new Long(1); + while (listIterator.hasNext()) + { + McOptsContent mcOptsContent=(McOptsContent)listIterator.next(); + logger.debug("option text:" + mcOptsContent.getMcQueOptionText()); + mapOptionsContent.put(mapIndex.toString(),mcOptsContent.getMcQueOptionText()); + mapIndex=new Long(mapIndex.longValue()+1); + } + request.getSession().setAttribute(MAP_OPTIONS_CONTENT, mapOptionsContent); + Map mapDefaultOptionsContent=mapOptionsContent; + request.getSession().setAttribute(MAP_DEFAULTOPTIONS_CONTENT, mapDefaultOptionsContent); + logger.debug("starter initialized the Options Map: " + request.getSession().getAttribute(MAP_OPTIONS_CONTENT)); + logger.debug("starter initialized the Default Options Map: " + request.getSession().getAttribute(MAP_DEFAULTOPTIONS_CONTENT)); + + Map mapWeights= new TreeMap(new McComparator()); + /* reset all the weights to 0*/ + long mapCounter=0; + for (long i=1; i <= MAX_QUESTION_COUNT ; i++) + { + mapCounter++; + mapWeights.put(new Long(mapCounter).toString(), new Integer(0)); + } + request.getSession().setAttribute(MAP_WEIGHTS, mapWeights); + logger.debug("MAP_WEIGHTS:" + request.getSession().getAttribute(MAP_WEIGHTS)); + } + + + /** + * initialisation + * initialiseAttributes(HttpServletRequest request) + * + * @param request + */ + protected void initialiseAttributes(HttpServletRequest request) + { + logger.debug("starting initialiseAttributes..."); + /* CURRENT_TAB == 1 defines Basic Tab + * CURRENT_TAB == 2 defines Avanced Tab + * CURRENT_TAB == 3 defines Instructions Tab + */ + request.getSession().setAttribute(CURRENT_TAB, new Long(1)); + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + + /* needs to run only once per tool*/ + /* McUtils.configureContentRepository(request, mcService); */ + + /* these two are for repository access */ + /* holds the final offline files list */ + LinkedList listUploadedOfflineFiles= new LinkedList(); + LinkedList listUploadedOnlineFiles= new LinkedList(); + + /* these two are for jsp */ + LinkedList listUploadedOfflineFileNames= new LinkedList(); + LinkedList listUploadedOnlineFileNames= new LinkedList(); + + request.getSession().setAttribute(LIST_UPLOADED_OFFLINE_FILES,listUploadedOfflineFiles); + request.getSession().setAttribute(LIST_UPLOADED_OFFLINE_FILENAMES,listUploadedOfflineFileNames); + + request.getSession().setAttribute(LIST_UPLOADED_ONLINE_FILES,listUploadedOnlineFiles); + request.getSession().setAttribute(LIST_UPLOADED_ONLINE_FILENAMES,listUploadedOnlineFileNames); + + Map mapQuestionsContent= new TreeMap(new McComparator()); + Map mapOptionsContent= new TreeMap(new McComparator()); + Map mapDefaultOptionsContent= new TreeMap(new McComparator()); + + Map mapGeneralOptionsContent= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_GENERAL_OPTIONS_CONTENT, mapGeneralOptionsContent); + + Map mapGeneralSelectedOptionsContent= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_GENERAL_SELECTED_OPTIONS_CONTENT, mapGeneralSelectedOptionsContent); + + Map mapStartupGeneralOptionsContent= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_STARTUP_GENERAL_OPTIONS_CONTENT, mapStartupGeneralOptionsContent); + + Map mapStartupGeneralSelectedOptionsContent= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_STARTUP_GENERAL_SELECTED_OPTIONS_CONTENT, mapStartupGeneralSelectedOptionsContent); + + Map mapDisabledQuestions= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_DISABLED_QUESTIONS, mapDisabledQuestions); + + Map mapWeights= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_WEIGHTS, mapWeights); + + Map mapCheckBoxStates= new TreeMap(new McComparator()); + mapCheckBoxStates.put("1" ,"INCORRECT"); + mapCheckBoxStates.put("2" ,"CORRECT"); + request.getSession().setAttribute(MAP_CHECKBOX_STATES, mapCheckBoxStates); + + Map mapSelectedOptions= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_SELECTED_OPTIONS, mapSelectedOptions); + + Map mapFeedbackIncorrect= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_FEEDBACK_INCORRECT, mapFeedbackIncorrect); + + Map mapFeedbackCorrect= new TreeMap(new McComparator()); + request.getSession().setAttribute(MAP_FEEDBACK_CORRECT, mapFeedbackCorrect); + + request.getSession().setAttribute(EDIT_OPTIONS_MODE, new Integer(0)); + logger.debug("resetting EDIT_OPTIONS_MODE to 0"); + } + + + /** + * persists error messages to request scope + * @param request + * @param message + */ + public void persistError(HttpServletRequest request, String message) + { + ActionMessages errors= new ActionMessages(); + errors.add(Globals.ERROR_KEY, new ActionMessage(message)); + logger.debug("add " + message +" to ActionMessages:"); + saveErrors(request,errors); + } +} Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/IQaContentDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/IQaQueContentDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/IQaQueUsrDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/IQaSessionDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/IQaUploadedFileDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/IQaUsrRespDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/hibernate/QaContentDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/hibernate/QaQueContentDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/hibernate/QaQueUsrDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/hibernate/QaSessionDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/hibernate/QaUploadedFileDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/dao/hibernate/QaUsrRespDAO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/service/IQaService.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/service/QaServicePOJO.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/service/QaServiceProxy.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/util/QaToolContentHandler.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/AuthoringUtil.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/LearningUtil.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/MonitoringUtil.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/QAction.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/QaAuthoringForm.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/QaEmptyForm.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/QaExportPortfolioForm.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/QaExportPortfolioStarterAction.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/QaLearningForm.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/QaLearningStarterAction.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/QaMonitoringAction.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/QaMonitoringForm.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/QaMonitoringStarterAction.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/web/QaStarterAction.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/AbstractQaTestCase.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/AllTests.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/QaContent.hbm.xml'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/QaDataAccessTestCase.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/QaQueContent.hbm.xml'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/QaQueUsr.hbm.xml'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/QaResources.properties'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/QaSession.hbm.xml'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/QaUploadedFile.hbm.xml'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/QaUsrResp.hbm.xml'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/TestQaContent.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/TestQaQueContent.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/TestQaQueUsr.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/TestQaSession.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/TestQaUsrResp.java'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/dbConnection.properties'. Fisheye: No comparison available. Pass `N' to diff? Fisheye: Tag 5f8c01a75dfd1323be7280810229d7ccd0ead2b7 refers to a dead (removed) revision in file `lams_tool_laqa/test/java/org/lamsfoundation/lams/tool/qa/testqaApplicationContext.xml'. Fisheye: No comparison available. Pass `N' to diff?