Index: lams_build/lib/lams/lams.jar =================================================================== diff -u -r1383e134b37b964b9a1070bb1b960aa6dcd05b51 -rac624414ec459fe718b3bfaf9a381e58b58398fc Binary files differ Index: lams_common/src/java/org/lamsfoundation/lams/commonContext.xml =================================================================== diff -u -r5eca912646ea4d81e3cf72fa0fe8b0567aea3c3b -rac624414ec459fe718b3bfaf9a381e58b58398fc --- lams_common/src/java/org/lamsfoundation/lams/commonContext.xml (.../commonContext.xml) (revision 5eca912646ea4d81e3cf72fa0fe8b0567aea3c3b) +++ lams_common/src/java/org/lamsfoundation/lams/commonContext.xml (.../commonContext.xml) (revision ac624414ec459fe718b3bfaf9a381e58b58398fc) @@ -14,7 +14,7 @@ - + Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java =================================================================== diff -u -r373dcc4ea6d1a07c60268ceccd9d1e69d9c35f9c -rac624414ec459fe718b3bfaf9a381e58b58398fc --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision 373dcc4ea6d1a07c60268ceccd9d1e69d9c35f9c) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision ac624414ec459fe718b3bfaf9a381e58b58398fc) @@ -23,6 +23,7 @@ package org.lamsfoundation.lams.tool.assessment.service; +import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.sql.Timestamp; import java.util.ArrayList; @@ -48,9 +49,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.tomcat.util.json.JSONArray; -import org.apache.tomcat.util.json.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.confidencelevel.ConfidenceLevel; import org.lamsfoundation.lams.confidencelevel.service.IConfidenceLevelService; import org.lamsfoundation.lams.events.IEventNotificationService; @@ -116,6 +114,10 @@ import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.util.audit.IAuditService; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Andrey Balan */ @@ -143,7 +145,7 @@ private AssessmentOutputFactory assessmentOutputFactory; // system services - + private IConfidenceLevelService confidenceLevelService; private ILamsToolService toolService; @@ -296,8 +298,8 @@ Map questionUidToConfidenceLevelMap = new HashMap(); for (ConfidenceLevel confidence : confidences) { questionUidToConfidenceLevelMap.put(confidence.getQuestionUid(), confidence.getConfidenceLevel()); - } - + } + confidenceLevelService.saveConfidenceLevels(toolSessionId, user.getUserId().intValue(), questionUidToConfidenceLevelMap); } } @@ -475,7 +477,7 @@ @Override public void setAttemptStarted(Assessment assessment, AssessmentUser assessmentUser, Long toolSessionId) { Set questions = assessment.getQuestions(); - + AssessmentResult lastResult = getLastAssessmentResult(assessment.getUid(), assessmentUser.getUserId()); if (lastResult != null) { @@ -504,7 +506,7 @@ assessmentResultDao.saveObject(lastResult); return; - // mark previous attempt as being not the latest any longer + // mark previous attempt as being not the latest any longer } else { lastResult.setLatest(null); assessmentResultDao.saveObject(lastResult); @@ -577,7 +579,8 @@ for (QuestionDTO questionDto : questionsForOnePage) { // in case single MarkHedging question needs to be stored -- search for that question - if ((singleMarkHedgingQuestionUid != null) && !questionDto.getUid().equals(singleMarkHedgingQuestionUid)) { + if ((singleMarkHedgingQuestionUid != null) + && !questionDto.getUid().equals(singleMarkHedgingQuestionUid)) { continue; } @@ -607,7 +610,7 @@ continue; } } - + // store confidence levels entered by the learner int level = questionDto.getConfidenceLevel(); questionUidToConfidenceLevelMap.put(questionDto.getUid(), level); @@ -618,7 +621,7 @@ maximumGrade += questionDto.getGrade(); } } - + // store confidence levels entered by the learner if (assessment.isEnableConfidenceLevels()) { confidenceLevelService.saveConfidenceLevels(result.getSessionId(), userId.intValue(), questionUidToConfidenceLevelMap); @@ -643,24 +646,24 @@ * @param isAutosave * in case of autosave there is no need to calculate marks * @return grade that user scored by answering that question - * @throws NoSuchMethodException - * @throws InvocationTargetException - * @throws IllegalAccessException + * @throws NoSuchMethodException + * @throws InvocationTargetException + * @throws IllegalAccessException */ - private float storeUserAnswer(AssessmentResult assessmentResult, QuestionDTO questionDto, boolean isAutosave) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + private float storeUserAnswer(AssessmentResult assessmentResult, QuestionDTO questionDto, boolean isAutosave) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Assessment assessment = assessmentResult.getAssessment(); - + AssessmentQuestionResult questionResult = null; // get questionResult from DB instance of AssessmentResult for (AssessmentQuestionResult questionResultIter : assessmentResult.getQuestionResults()) { if (questionDto.getUid().equals(questionResultIter.getAssessmentQuestion().getUid())) { questionResult = questionResultIter; } } - - //if teacher edited content in monitor (modified question) it led to removal if autosaved questionResult - if (assessment.isContentModifiedInMonitor(assessmentResult.getStartDate()) - && questionResult == null) { + + //if teacher edited content in monitor (modified question) it led to removal if autosaved questionResult + if (assessment.isContentModifiedInMonitor(assessmentResult.getStartDate()) && questionResult == null) { //update questionDto AssessmentQuestion modifiedQuestion = assessmentQuestionDao.getByUid(questionDto.getUid()); QuestionDTO updatedQuestionDto = modifiedQuestion.getQuestionDTO(); @@ -752,7 +755,8 @@ java.util.regex.Pattern.CASE_INSENSITIVE | java.util.regex.Pattern.UNICODE_CASE); } boolean isAnswerMatchedCurrentOption = (questionDto.getAnswerString() != null) - ? pattern.matcher(questionDto.getAnswerString().trim()).matches() : false; + ? pattern.matcher(questionDto.getAnswerString().trim()).matches() + : false; if (isAnswerMatchedCurrentOption) { mark = optionDto.getGrade() * maxMark; @@ -768,7 +772,8 @@ boolean isAnswerMatchedCurrentOption = false; try { float answerFloat = Float.valueOf(questionDto.getAnswerString()); - isAnswerMatchedCurrentOption = ((answerFloat >= (optionDto.getOptionFloat() - optionDto.getAcceptedError())) + isAnswerMatchedCurrentOption = ((answerFloat >= (optionDto.getOptionFloat() + - optionDto.getAcceptedError())) && (answerFloat <= (optionDto.getOptionFloat() + optionDto.getAcceptedError()))); } catch (Exception e) { } @@ -786,7 +791,8 @@ answerFloat = answerFloat / unit.getMultiplier(); isAnswerMatchedCurrentOption = ((answerFloat >= (optionDto.getOptionFloat() - optionDto.getAcceptedError())) - && (answerFloat <= (optionDto.getOptionFloat() + optionDto.getAcceptedError()))); + && (answerFloat <= (optionDto.getOptionFloat() + + optionDto.getAcceptedError()))); if (isAnswerMatchedCurrentOption) { break; } @@ -804,15 +810,16 @@ } } else if (questionDto.getType() == AssessmentConstants.QUESTION_TYPE_TRUE_FALSE) { - if ((questionDto.getAnswerBoolean() == questionDto.getCorrectAnswer()) && (questionDto.getAnswerString() != null)) { + if ((questionDto.getAnswerBoolean() == questionDto.getCorrectAnswer()) + && (questionDto.getAnswerString() != null)) { mark = maxMark; } } else if (questionDto.getType() == AssessmentConstants.QUESTION_TYPE_ORDERING) { float maxMarkForCorrectAnswer = maxMark / questionDto.getOptionDtos().size(); - TreeSet correctOptionSet = new TreeSet(new SequencableComparator()); + TreeSet correctOptionSet = new TreeSet<>(new SequencableComparator()); correctOptionSet.addAll(questionDto.getOptionDtos()); - ArrayList correctOptionList = new ArrayList(correctOptionSet); + ArrayList correctOptionList = new ArrayList<>(correctOptionSet); int i = 0; for (OptionDTO optionDto : questionDto.getOptionDtos()) { if (optionDto.getUid() == correctOptionList.get(i++).getUid()) { @@ -981,7 +988,7 @@ @Override public List getReflectList(Long contentId) { - List reflectList = new LinkedList(); + List reflectList = new LinkedList<>(); List sessionList = assessmentSessionDao.getByContentId(contentId); for (AssessmentSession session : sessionList) { @@ -1032,22 +1039,28 @@ @Override public List getSessionDtos(Long contentId, boolean includeStatistics) { - List sessionDtos = new ArrayList(); + List sessionDtos = new ArrayList<>(); List sessionList = assessmentSessionDao.getByContentId(contentId); for (AssessmentSession session : sessionList) { Long sessionId = session.getSessionId(); SessionDTO sessionDto = new SessionDTO(sessionId, session.getSessionName()); //for statistics tab - if ( includeStatistics ) { + if (includeStatistics) { int countUsers = assessmentUserDao.getCountUsersBySession(sessionId, ""); sessionDto.setNumberLearners(countUsers); Object[] markStats = assessmentUserDao.getStatsMarksBySession(sessionId); - if ( markStats != null ) { - sessionDto.setMinMark(markStats[0] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[0], (Locale)null, 2) : "0.00"); - sessionDto.setAvgMark(markStats[1] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[1], (Locale)null, 2) : "0.00"); - sessionDto.setMaxMark(markStats[2] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[2], (Locale)null, 2) : "0.00"); + if (markStats != null) { + sessionDto.setMinMark(markStats[0] != null + ? NumberUtil.formatLocalisedNumber((Float) markStats[0], (Locale) null, 2) + : "0.00"); + sessionDto.setAvgMark(markStats[1] != null + ? NumberUtil.formatLocalisedNumber((Float) markStats[1], (Locale) null, 2) + : "0.00"); + sessionDto.setMaxMark(markStats[2] != null + ? NumberUtil.formatLocalisedNumber((Float) markStats[2], (Locale) null, 2) + : "0.00"); } } @@ -1061,20 +1074,26 @@ public LeaderResultsDTO getLeaderResultsDTOForLeaders(Long contentId) { LeaderResultsDTO newDto = new LeaderResultsDTO(contentId); Object[] markStats = assessmentUserDao.getStatsMarksForLeaders(contentId); - if ( markStats != null ) { - newDto.setMinMark(markStats[0] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[0], (Locale)null, 2) : "0.00"); - newDto.setAvgMark(markStats[1] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[1], (Locale)null, 2) : "0.00"); - newDto.setMaxMark(markStats[2] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[2], (Locale)null, 2) : "0.00"); - newDto.setNumberGroupsLeaderFinished((Integer)markStats[3]); + if (markStats != null) { + newDto.setMinMark( + markStats[0] != null ? NumberUtil.formatLocalisedNumber((Float) markStats[0], (Locale) null, 2) + : "0.00"); + newDto.setAvgMark( + markStats[1] != null ? NumberUtil.formatLocalisedNumber((Float) markStats[1], (Locale) null, 2) + : "0.00"); + newDto.setMaxMark( + markStats[2] != null ? NumberUtil.formatLocalisedNumber((Float) markStats[2], (Locale) null, 2) + : "0.00"); + newDto.setNumberGroupsLeaderFinished((Integer) markStats[3]); } return newDto; } - + @Override public AssessmentResultDTO getUserMasterDetail(Long sessionId, Long userId) { AssessmentResultDTO resultDto = new AssessmentResultDTO(); resultDto.setSessionId(sessionId); - + AssessmentResult lastFinishedResult = assessmentResultDao.getLastFinishedAssessmentResultByUser(sessionId, userId); if (lastFinishedResult != null) { @@ -1083,13 +1102,13 @@ Set questionResults = lastFinishedResult.getQuestionResults(); //prepare list of the questions to display in user master detail table, filtering out questions that aren't supposed to be answered - SortedSet questionResultsToDisplay = new TreeSet( + SortedSet questionResultsToDisplay = new TreeSet<>( new AssessmentQuestionResultComparator()); //in case there is at least one random question - we need to show all questions if (assessment.hasRandomQuestion()) { questionResultsToDisplay.addAll(questionResults); - //otherwise show only questions from the question list + //otherwise show only questions from the question list } else { for (QuestionReference reference : questionReferences) { for (AssessmentQuestionResult questionResult : questionResults) { @@ -1128,7 +1147,7 @@ @Override public UserSummary getUserSummary(Long contentId, Long userId, Long sessionId) { Assessment assessment = assessmentDao.getByContentId(contentId); - + UserSummary userSummary = new UserSummary(); AssessmentUser user = assessmentUserDao.getUserByUserIDAndSessionID(userId, sessionId); userSummary.setUser(user); @@ -1143,11 +1162,11 @@ if (lastFinishedResult != null) { userSummary.setLastAttemptGrade(lastFinishedResult.getGrade()); } - + if (!results.isEmpty()) { //prepare list of the questions to display, filtering out questions that aren't supposed to be answered - Set questions = new TreeSet(); + Set questions = new TreeSet<>(); //in case there is at least one random question - we need to show all questions in a drop down select if (assessment.hasRandomQuestion()) { questions.addAll(assessment.getQuestions()); @@ -1164,19 +1183,19 @@ : null; //prepare list of UserSummaryItems - ArrayList userSummaryItems = new ArrayList(); + ArrayList userSummaryItems = new ArrayList<>(); for (AssessmentQuestion question : questions) { UserSummaryItem userSummaryItem = new UserSummaryItem(question); //find all questionResults that correspond to the current question - List questionResults = new ArrayList(); + List questionResults = new ArrayList<>(); for (AssessmentResult result : results) { for (AssessmentQuestionResult questionResult : result.getQuestionResults()) { if (question.getUid().equals(questionResult.getAssessmentQuestion().getUid())) { // for displaying purposes only (no saving occurrs) questionResult.setFinishDate(result.getFinishDate()); - + // prepare for displaying purposes confidence levels if (assessment.isEnableConfidenceLevels()) { //find according confidenceLevel @@ -1216,27 +1235,27 @@ @Override public Map getQuestionSummaryForExport(Assessment assessment) { - Map questionSummaries = new LinkedHashMap(); + Map questionSummaries = new LinkedHashMap<>(); if (assessment.getQuestions() == null) { return questionSummaries; } - SortedSet sessions = new TreeSet(new AssessmentSessionComparator()); + SortedSet sessions = new TreeSet<>(new AssessmentSessionComparator()); sessions.addAll(assessmentSessionDao.getByContentId(assessment.getContentId())); List assessmentResults = assessmentResultDao .getLastFinishedAssessmentResults(assessment.getContentId()); - Map userUidToResultMap = new HashMap(); + Map userUidToResultMap = new HashMap<>(); for (AssessmentResult assessmentResult : assessmentResults) { userUidToResultMap.put(assessmentResult.getUser().getUid(), assessmentResult); } - Map> sessionIdToUsersMap = new HashMap>(); + Map> sessionIdToUsersMap = new HashMap<>(); for (AssessmentSession session : sessions) { Long sessionId = session.getSessionId(); - List users = new ArrayList(); + List users = new ArrayList<>(); // in case of leader aware tool show only leaders' responses if (assessment.isUseSelectLeaderToolOuput()) { @@ -1256,14 +1275,14 @@ QuestionSummary questionSummary = new QuestionSummary(); questionSummary.setQuestion(question); - List> questionResults = new ArrayList>(); + List> questionResults = new ArrayList<>(); for (AssessmentSession session : sessions) { Long sessionId = session.getSessionId(); List users = sessionIdToUsersMap.get(sessionId); - ArrayList sessionQuestionResults = new ArrayList(); + ArrayList sessionQuestionResults = new ArrayList<>(); for (AssessmentUser user : users) { AssessmentResult assessmentResult = userUidToResultMap.get(user.getUid()); AssessmentQuestionResult questionResult = null; @@ -1312,12 +1331,12 @@ @Override public LinkedHashMap exportSummary(Assessment assessment, List sessionDtos, boolean showUserNames) { - LinkedHashMap dataToExport = new LinkedHashMap(); + LinkedHashMap dataToExport = new LinkedHashMap<>(); final ExcelCell[] EMPTY_ROW = new ExcelCell[0]; // -------------- First tab: Summary ---------------------------------------------------- if (showUserNames) { - ArrayList summaryTab = new ArrayList(); + ArrayList summaryTab = new ArrayList<>(); if (sessionDtos != null) { for (SessionDTO sessionDTO : sessionDtos) { @@ -1328,8 +1347,8 @@ ExcelCell[] sessionTitle = new ExcelCell[1]; sessionTitle[0] = new ExcelCell(sessionDTO.getSessionName(), true); summaryTab.add(sessionTitle); - - List userDtos = new ArrayList(); + + List userDtos = new ArrayList<>(); // in case of UseSelectLeaderToolOuput - display only one user if (assessment.isUseSelectLeaderToolOuput()) { @@ -1355,12 +1374,15 @@ userDtos = getPagedUsersBySession(sessionId, 0, countSessionUsers, "userName", "ASC", ""); } - ArrayList summaryTabLearnerList = new ArrayList(); - + ArrayList summaryTabLearnerList = new ArrayList<>(); + ExcelCell[] summaryRowTitle = new ExcelCell[3]; - summaryRowTitle[0] = new ExcelCell(getMessage("label.export.user.id"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN); - summaryRowTitle[1] = new ExcelCell(getMessage("label.monitoring.summary.user.name"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN); - summaryRowTitle[2] = new ExcelCell(getMessage("label.monitoring.summary.total"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN); + summaryRowTitle[0] = new ExcelCell(getMessage("label.export.user.id"), true, + ExcelCell.BORDER_STYLE_BOTTOM_THIN); + summaryRowTitle[1] = new ExcelCell(getMessage("label.monitoring.summary.user.name"), true, + ExcelCell.BORDER_STYLE_BOTTOM_THIN); + summaryRowTitle[2] = new ExcelCell(getMessage("label.monitoring.summary.total"), true, + ExcelCell.BORDER_STYLE_BOTTOM_THIN); summaryTabLearnerList.add(summaryRowTitle); float minGrade = -9999999; @@ -1375,18 +1397,22 @@ userResultRow[2] = new ExcelCell(grade, false); summaryTabLearnerList.add(userResultRow); - if ( grade < minGrade || minGrade == -9999999 ) + if (grade < minGrade || minGrade == -9999999) { minGrade = grade; - if ( grade > maxGrade ) + } + if (grade > maxGrade) { maxGrade = grade; + } } - if ( minGrade == -9999999) + if (minGrade == -9999999) { minGrade = 0; + } - LinkedHashMap markSummary = getMarksSummaryForSession(userDtos, minGrade, maxGrade, 10); + LinkedHashMap markSummary = getMarksSummaryForSession(userDtos, minGrade, maxGrade, + 10); // work out total marks so we can do percentages. need as float for the correct divisions int totalNumEntries = 0; - for ( Map.Entry entry : markSummary.entrySet() ) { + for (Map.Entry entry : markSummary.entrySet()) { totalNumEntries += entry.getValue(); } @@ -1398,25 +1424,29 @@ summaryTab.add(minMaxRow); minMaxRow = new ExcelCell[2]; minMaxRow[0] = new ExcelCell(getMessage("label.lowest.mark"), true); - minMaxRow[1] = new ExcelCell((double)minGrade, false); + minMaxRow[1] = new ExcelCell((double) minGrade, false); summaryTab.add(minMaxRow); minMaxRow = new ExcelCell[2]; minMaxRow[0] = new ExcelCell(getMessage("label.highest.mark"), true); - minMaxRow[1] = new ExcelCell((double)maxGrade, false); + minMaxRow[1] = new ExcelCell((double) maxGrade, false); summaryTab.add(minMaxRow); - + summaryTab.add(EMPTY_ROW); ExcelCell[] binSummaryRow = new ExcelCell[3]; - binSummaryRow[0] = new ExcelCell(getMessage("label.authoring.basic.list.header.mark"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN); - binSummaryRow[1] = new ExcelCell(getMessage("label.number.learners"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN); - binSummaryRow[2] = new ExcelCell(getMessage("label.percentage"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN); + binSummaryRow[0] = new ExcelCell(getMessage("label.authoring.basic.list.header.mark"), true, + ExcelCell.BORDER_STYLE_BOTTOM_THIN); + binSummaryRow[1] = new ExcelCell(getMessage("label.number.learners"), true, + ExcelCell.BORDER_STYLE_BOTTOM_THIN); + binSummaryRow[2] = new ExcelCell(getMessage("label.percentage"), true, + ExcelCell.BORDER_STYLE_BOTTOM_THIN); summaryTab.add(binSummaryRow); - float totalNumEntriesAsFloat = (float) totalNumEntries; - for ( Map.Entry entry : markSummary.entrySet() ) { + float totalNumEntriesAsFloat = totalNumEntries; + for (Map.Entry entry : markSummary.entrySet()) { binSummaryRow = new ExcelCell[3]; - binSummaryRow[0] = new ExcelCell(entry.getKey(),false); - binSummaryRow[1] = new ExcelCell(entry.getValue(),false); - binSummaryRow[2] = new ExcelCell(Math.round(entry.getValue() / totalNumEntriesAsFloat * 100),false); + binSummaryRow[0] = new ExcelCell(entry.getKey(), false); + binSummaryRow[1] = new ExcelCell(entry.getValue(), false); + binSummaryRow[2] = new ExcelCell(Math.round(entry.getValue() / totalNumEntriesAsFloat * 100), + false); summaryTab.add(binSummaryRow); } summaryTab.add(EMPTY_ROW); @@ -1433,7 +1463,7 @@ // ------------------------------------------------------------------ // -------------- Second tab: Question Summary ---------------------- - ArrayList questionSummaryTab = new ArrayList(); + ArrayList questionSummaryTab = new ArrayList<>(); // Create the question summary ExcelCell[] summaryTitle = new ExcelCell[1]; @@ -1473,13 +1503,13 @@ ExcelCell.BORDER_STYLE_BOTTOM_THIN); int questionNumber = 1; - + for (AssessmentQuestion question : questions) { int colsNum = showUserNames ? 10 : 9; ExcelCell[] questionTitle = new ExcelCell[1]; - questionTitle[0] = new ExcelCell(getMessage("label.monitoring.question.summary.question") + " " - + questionNumber++, true); + questionTitle[0] = new ExcelCell( + getMessage("label.monitoring.question.summary.question") + " " + questionNumber++, true); questionSummaryTab.add(questionTitle); // set up the summary table data for the top of the question area. @@ -1489,16 +1519,16 @@ || question.getType() == AssessmentConstants.QUESTION_TYPE_TRUE_FALSE; // For MC, Numeric & Short Answer Key is optionUid, Value is number of answers // For True/False Key 0 is false and Key 1 is true - Map summaryOfAnswers = new HashMap(); + Map summaryOfAnswers = new HashMap<>(); Integer summaryNACount = 0; Long trueKey = 1L; Long falseKey = 0L; if (doSummaryTable) { questionSummaryTab.add(startSummaryTable(question, summaryOfAnswers, trueKey, falseKey)); } - - ArrayList questionSummaryTabTemp = new ArrayList(); + ArrayList questionSummaryTabTemp = new ArrayList<>(); + //add question title row if (question.getType() == AssessmentConstants.QUESTION_TYPE_MARK_HEDGING) { count = 0; @@ -1579,9 +1609,10 @@ } else { userResultRow[count++] = new ExcelCell( AssessmentEscapeUtils.printResponsesForExcelExport(questionResult), false); - - if ( doSummaryTable ) { - summaryNACount = updateSummaryCounts(question, questionResult, summaryOfAnswers, summaryNACount); + + if (doSummaryTable) { + summaryNACount = updateSummaryCounts(question, questionResult, summaryOfAnswers, + summaryNACount); } } @@ -1609,10 +1640,11 @@ } if (doSummaryTable) { - questionSummaryTab.add(outputSummaryTable(question, summaryOfAnswers, summaryNACount, trueKey, falseKey)); + questionSummaryTab + .add(outputSummaryTable(question, summaryOfAnswers, summaryNACount, trueKey, falseKey)); questionSummaryTab.add(EMPTY_ROW); } - + // Calculating the averages ExcelCell[] averageRow; @@ -1648,7 +1680,7 @@ questionSummaryTab.addAll(questionSummaryTabTemp); questionSummaryTab.add(averageRow); questionSummaryTab.add(EMPTY_ROW); - + } } @@ -1658,24 +1690,29 @@ // ------------------------------------------------------------------ // -------------- Third tab: User Summary --------------------------- - ArrayList userSummaryTab = new ArrayList(); + ArrayList userSummaryTab = new ArrayList<>(); // Create the question summary ExcelCell[] userSummaryTitle = new ExcelCell[1]; userSummaryTitle[0] = new ExcelCell(getMessage("label.export.user.summary"), true); userSummaryTab.add(userSummaryTitle); ExcelCell[] summaryRowTitle = new ExcelCell[5]; - summaryRowTitle[0] = new ExcelCell(getMessage("label.monitoring.question.summary.question"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN); - summaryRowTitle[1] = new ExcelCell(getMessage("label.authoring.basic.list.header.type"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN); - summaryRowTitle[2] = new ExcelCell(getMessage("label.authoring.basic.penalty.factor"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN); - summaryRowTitle[3] = new ExcelCell(getMessage("label.monitoring.question.summary.default.mark"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN); - summaryRowTitle[4] = new ExcelCell(getMessage("label.monitoring.question.summary.average.mark"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN); + summaryRowTitle[0] = new ExcelCell(getMessage("label.monitoring.question.summary.question"), true, + ExcelCell.BORDER_STYLE_BOTTOM_THIN); + summaryRowTitle[1] = new ExcelCell(getMessage("label.authoring.basic.list.header.type"), true, + ExcelCell.BORDER_STYLE_BOTTOM_THIN); + summaryRowTitle[2] = new ExcelCell(getMessage("label.authoring.basic.penalty.factor"), true, + ExcelCell.BORDER_STYLE_BOTTOM_THIN); + summaryRowTitle[3] = new ExcelCell(getMessage("label.monitoring.question.summary.default.mark"), true, + ExcelCell.BORDER_STYLE_BOTTOM_THIN); + summaryRowTitle[4] = new ExcelCell(getMessage("label.monitoring.question.summary.average.mark"), true, + ExcelCell.BORDER_STYLE_BOTTOM_THIN); userSummaryTab.add(summaryRowTitle); Float totalGradesPossible = new Float(0); Float totalAverage = new Float(0); if (assessment.getQuestionReferences() != null) { - Set questionReferences = new TreeSet(new SequencableComparator()); + Set questionReferences = new TreeSet<>(new SequencableComparator()); questionReferences.addAll(assessment.getQuestionReferences()); int randomQuestionsCount = 1; @@ -1731,7 +1768,7 @@ if (sessionDtos != null) { List assessmentResults = assessmentResultDao .getLastFinishedAssessmentResults(assessment.getContentId()); - Map userUidToResultMap = new HashMap(); + Map userUidToResultMap = new HashMap<>(); for (AssessmentResult assessmentResult : assessmentResults) { userUidToResultMap.put(assessmentResult.getUser().getUid(), assessmentResult); } @@ -1843,30 +1880,26 @@ summaryTable = new ExcelCell[question.getOptions().size() + 1]; for (AssessmentQuestionOption option : question.getOptions()) { summaryOfAnswers.put(option.getUid(), 0); - StringBuilder bldr = new StringBuilder(getMessage("label.authoring.basic.option.answer")) - .append(" ") - .append(i + 1) - .append(" - "); - if ( question.getType() == AssessmentConstants.QUESTION_TYPE_NUMERICAL ) { - bldr.append(option.getOptionFloat()) - .append(" +- ") - .append(option.getAcceptedError()); + StringBuilder bldr = new StringBuilder(getMessage("label.authoring.basic.option.answer")).append(" ") + .append(i + 1).append(" - "); + if (question.getType() == AssessmentConstants.QUESTION_TYPE_NUMERICAL) { + bldr.append(option.getOptionFloat()).append(" +- ").append(option.getAcceptedError()); } else { bldr.append(option.getOptionString().replaceAll("\\<.*?\\>", "")); } summaryTable[i] = new ExcelCell(bldr.toString(), false); i++; } - if ( question.getType() == AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE ) { - summaryTable[i++] = new ExcelCell(getMessage("label.not.answered"), false); + if (question.getType() == AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE) { + summaryTable[i++] = new ExcelCell(getMessage("label.not.answered"), false); } else { - summaryTable[i++] = new ExcelCell(getMessage("label.other"), false); + summaryTable[i++] = new ExcelCell(getMessage("label.other"), false); } } else { summaryTable = new ExcelCell[3]; summaryTable[0] = new ExcelCell(getMessage("label.authoring.true.false.true"), false); summaryTable[1] = new ExcelCell(getMessage("label.authoring.true.false.false"), false); - summaryTable[2] = new ExcelCell(getMessage("label.not.answered"), false); + summaryTable[2] = new ExcelCell(getMessage("label.not.answered"), false); summaryOfAnswers.put(trueKey, 0); summaryOfAnswers.put(falseKey, 0); } @@ -1883,11 +1916,10 @@ if (optionAnswer.getAnswerBoolean()) { Integer currentCount = summaryOfAnswers.get(optionAnswer.getOptionUid()); if (currentCount == null) { - log.error("Assessment Export: Unable to count answer in summary, refers to an unexpected option. QuestionResult " - + questionResult.getUid() - + " OptionUid " - + optionAnswer.getOptionUid() - + " question " + question.getUid()); + log.error( + "Assessment Export: Unable to count answer in summary, refers to an unexpected option. QuestionResult " + + questionResult.getUid() + " OptionUid " + optionAnswer.getOptionUid() + + " question " + question.getUid()); } else { summaryOfAnswers.put(optionAnswer.getOptionUid(), currentCount + 1); foundOption = true; @@ -1904,12 +1936,10 @@ if (submittedUid != null) { Integer currentCount = summaryOfAnswers.get(submittedUid); if (currentCount == null) { - log.error("Assessment Export: Unable to count answer in summary, refers to an unexpected option. QuestionResult " - + questionResult.getUid() - + " submittedOptionUid " - + submittedUid - + " question " - + question.getUid()); + log.error( + "Assessment Export: Unable to count answer in summary, refers to an unexpected option. QuestionResult " + + questionResult.getUid() + " submittedOptionUid " + submittedUid + " question " + + question.getUid()); } else { summaryOfAnswers.put(submittedUid, currentCount + 1); } @@ -1930,39 +1960,38 @@ private String valueAsPercentage(Integer value, int total) { Double percentage = (double) value / total * 100; - return NumberUtil.formatLocalisedNumber(percentage, (Locale)null, 2) + "%"; - } - + return NumberUtil.formatLocalisedNumber(percentage, (Locale) null, 2) + "%"; + } + private ExcelCell[] outputSummaryTable(AssessmentQuestion question, Map summaryOfAnswers, Integer summaryNACount, Long trueKey, Long falseKey) { - ExcelCell[] summaryTable = new ExcelCell[summaryOfAnswers.size()+1]; + ExcelCell[] summaryTable = new ExcelCell[summaryOfAnswers.size() + 1]; int total = summaryNACount; - for ( int value : summaryOfAnswers.values() ) { - total += value; + for (int value : summaryOfAnswers.values()) { + total += value; } int i = 0; if (question.getType() == AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE || question.getType() == AssessmentConstants.QUESTION_TYPE_SHORT_ANSWER - || question.getType() == AssessmentConstants.QUESTION_TYPE_NUMERICAL ) { - for (AssessmentQuestionOption option : question.getOptions()) { - summaryTable[i] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(option.getUid()), total), false); - if ( option.getGrade() > 0 ) { - summaryTable[i].setColor(IndexedColors.GREEN); + || question.getType() == AssessmentConstants.QUESTION_TYPE_NUMERICAL) { + for (AssessmentQuestionOption option : question.getOptions()) { + summaryTable[i] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(option.getUid()), total), false); + if (option.getGrade() > 0) { + summaryTable[i].setColor(IndexedColors.GREEN); + } + i++; } - i++; - } - summaryTable[i++] = new ExcelCell(valueAsPercentage(summaryNACount, total), false); + summaryTable[i++] = new ExcelCell(valueAsPercentage(summaryNACount, total), false); } else { - summaryTable = new ExcelCell[3]; - summaryTable[0] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(trueKey), total), false); - summaryTable[1] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(falseKey), total), false); - summaryTable[2] = new ExcelCell(valueAsPercentage(summaryNACount,total), false); - summaryTable[question.getCorrectAnswer() ? 0 : 1].setColor(IndexedColors.GREEN); + summaryTable = new ExcelCell[3]; + summaryTable[0] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(trueKey), total), false); + summaryTable[1] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(falseKey), total), false); + summaryTable[2] = new ExcelCell(valueAsPercentage(summaryNACount, total), false); + summaryTable[question.getCorrectAnswer() ? 0 : 1].setColor(IndexedColors.GREEN); } return summaryTable; } - /** * Used only for excell export (for getUserSummaryData() method). */ @@ -2003,11 +2032,11 @@ // When changing a mark for user and isUseSelectLeaderToolOuput is true, the mark should be propagated to all // students within the group - List users = new ArrayList(); + List users = new ArrayList<>(); if (assessment.isUseSelectLeaderToolOuput()) { users = getUsersBySession(toolSessionId); } else { - users = new ArrayList(); + users = new ArrayList<>(); AssessmentUser user = assessmentResult.getUser(); users.add(user); } @@ -2051,7 +2080,7 @@ List deletedReferences) { // create list of modified questions - List modifiedQuestions = new ArrayList(); + List modifiedQuestions = new ArrayList<>(); for (AssessmentQuestion oldQuestion : oldQuestions) { for (AssessmentQuestion newQuestion : newQuestions) { if (oldQuestion.getUid().equals(newQuestion.getUid())) { @@ -2097,7 +2126,7 @@ // create list of modified references // modifiedReferences holds pairs newReference -> oldReference.getDefaultGrade() - Map modifiedReferences = new HashMap(); + Map modifiedReferences = new HashMap<>(); for (QuestionReference oldReference : oldReferences) { for (QuestionReference newReference : newReferences) { if (oldReference.getUid().equals(newReference.getUid()) @@ -2108,7 +2137,7 @@ } // create list of added references - List addedReferences = new ArrayList(); + List addedReferences = new ArrayList<>(); for (QuestionReference newReference : newReferences) { boolean isNewReferenceMetInOldReferences = false; @@ -2136,7 +2165,7 @@ user.getUserId()); AssessmentResult lastFinishedAssessmentResult = (assessmentResults.isEmpty()) ? null : assessmentResults.get(assessmentResults.size() - 1); - + //add autosave assessmentResult as well AssessmentResult lastAssessmentResult = getLastAssessmentResult(assessment.getUid(), user.getUserId()); if (lastAssessmentResult != null && lastAssessmentResult.getFinishDate() == null) { @@ -2217,7 +2246,7 @@ } // find all question answers from random question reference - ArrayList nonRandomQuestionAnswers = new ArrayList(); + ArrayList nonRandomQuestionAnswers = new ArrayList<>(); for (AssessmentQuestionResult questionAnswer : questionAnswers) { for (QuestionReference reference : newReferences) { if (!reference.isRandomQuestion() && questionAnswer.getAssessmentQuestion().getUid() @@ -2325,7 +2354,7 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void auditLogStartEditingActivityInMonitor(long toolContentID) { toolService.auditLogStartEditingActivityInMonitor(toolContentID); @@ -2361,7 +2390,6 @@ public List getConfidenceLevelsByQuestionAndSession(Long questionUid, Long toolSessionId) { return confidenceLevelService.getConfidenceLevelsByQuestionAndSession(questionUid, toolSessionId); } - @Override public List getMarksArray(Long sessionId) { return assessmentUserDao.getRawUserMarksBySession(sessionId); @@ -2372,66 +2400,70 @@ return assessmentUserDao.getRawLeaderMarksByToolContentId(toolContentId); } - private LinkedHashMap getMarksSummaryForSession(List userDtos, float minGrade, float maxGrade, Integer numBuckets) { + private LinkedHashMap getMarksSummaryForSession(List userDtos, float minGrade, + float maxGrade, Integer numBuckets) { - LinkedHashMap summary = new LinkedHashMap(); - TreeMap inProgress = new TreeMap(); - - if ( numBuckets == null ) + LinkedHashMap summary = new LinkedHashMap<>(); + TreeMap inProgress = new TreeMap<>(); + + if (numBuckets == null) { numBuckets = 10; - + } + int bucketSize = 1; - int intMinGrade = (int)Math.floor(minGrade); + int intMinGrade = (int) Math.floor(minGrade); float gradeDifference = maxGrade - minGrade; - if ( gradeDifference <= 10 ) { - for ( int i= intMinGrade; i <= (int)Math.ceil(maxGrade); i++ ) { + if (gradeDifference <= 10) { + for (int i = intMinGrade; i <= (int) Math.ceil(maxGrade); i++) { inProgress.put(i, 0); } } else { int intGradeDifference = (int) Math.ceil(gradeDifference); - bucketSize = (int) Math.ceil(intGradeDifference / numBuckets); - for ( int i=intMinGrade; i <= maxGrade; i = i+bucketSize ) { + bucketSize = (int) Math.ceil(intGradeDifference / numBuckets); + for (int i = intMinGrade; i <= maxGrade; i = i + bucketSize) { inProgress.put(i, 0); } } - + for (AssessmentUserDTO userDto : userDtos) { float grade = userDto.getGrade(); int bucketStart = intMinGrade; - int bucketStop = bucketStart+bucketSize; + int bucketStop = bucketStart + bucketSize; boolean looking = true; - while ( bucketStart <= maxGrade && looking ) { - if ( grade >= bucketStart && grade < bucketStop ) { + while (bucketStart <= maxGrade && looking) { + if (grade >= bucketStart && grade < bucketStop) { inProgress.put(bucketStart, inProgress.get(bucketStart) + 1); looking = false; } else { bucketStart = bucketStop; - bucketStop = bucketStart+bucketSize; + bucketStop = bucketStart + bucketSize; } } } - - for ( Map.Entry entry : inProgress.entrySet() ) { + + for (Map.Entry entry : inProgress.entrySet()) { String key; - if ( bucketSize == 1 ) + if (bucketSize == 1) { key = entry.getKey().toString(); - else { - if ( maxGrade >= entry.getKey() && maxGrade <= entry.getKey()+bucketSize-1) { - if ( (int)maxGrade == entry.getKey() ) - key = NumberUtil.formatLocalisedNumber(maxGrade, (Locale)null, 2); - else + } else { + if (maxGrade >= entry.getKey() && maxGrade <= entry.getKey() + bucketSize - 1) { + if ((int) maxGrade == entry.getKey()) { + key = NumberUtil.formatLocalisedNumber(maxGrade, (Locale) null, 2); + } else { key = new StringBuilder().append(entry.getKey()).append(" - ") - .append(NumberUtil.formatLocalisedNumber(maxGrade, (Locale)null, 2)).toString(); + .append(NumberUtil.formatLocalisedNumber(maxGrade, (Locale) null, 2)).toString(); + } } else { - key = new StringBuilder().append(entry.getKey()).append(" - ").append(entry.getKey()+bucketSize-.01).toString(); + key = new StringBuilder().append(entry.getKey()).append(" - ") + .append(entry.getKey() + bucketSize - .01).toString(); } } summary.put(key, entry.getValue()); } - + return summary; } - + // ***************************************************************************** // private methods // ***************************************************************************** @@ -2466,7 +2498,7 @@ public void setAuditService(IAuditService auditService) { this.auditService = auditService; } - + public void setConfidenceLevelService(IConfidenceLevelService confidenceLevelService) { this.confidenceLevelService = confidenceLevelService; } @@ -2868,116 +2900,126 @@ Date startDate = null; Date finishDate = null; for (AssessmentResult result : results) { - if (startDate == null || (result.getStartDate() != null && result.getStartDate().before(startDate))) + if (startDate == null || (result.getStartDate() != null && result.getStartDate().before(startDate))) { startDate = result.getStartDate(); - if (finishDate == null || (result.getFinishDate() != null && result.getFinishDate().after(finishDate))) + } + if (finishDate == null || (result.getFinishDate() != null && result.getFinishDate().after(finishDate))) { finishDate = result.getFinishDate(); + } } - if (learner.isSessionFinished()) + if (learner.isSessionFinished()) { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_COMPLETED, startDate, finishDate); - else + } else { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_ATTEMPTED, startDate, null); + } } // ****************** REST methods ************************* /** * Rest call to create a new Assessment content. Required fields in toolContentJSON: "title", "instructions", * "questions", "firstName", "lastName", "lastName", "questions" and "references". * - * The questions entry should be a JSONArray containing JSON objects, which in turn must contain "questionTitle", + * The questions entry should be a ArrayNode containing JSON objects, which in turn must contain "questionTitle", * "questionText", "displayOrder" (Integer), "type" (Integer). If the type is Multiple Choice, Numerical or Matching - * Pairs then a JSONArray "answers" is required. + * Pairs then a ArrayNode "answers" is required. * - * The answers entry should be JSONArray containing JSON objects, which in turn must contain "answerText" or + * The answers entry should be ArrayNode containing JSON objects, which in turn must contain "answerText" or * "answerFloat", "displayOrder" (Integer), "grade" (Integer). * - * The references entry should be a JSONArray containing JSON objects, which in turn must contain "displayOrder" + * The references entry should be a ArrayNode containing JSON objects, which in turn must contain "displayOrder" * (Integer), "questionDisplayOrder" (Integer - to match to the question). It may also have "defaultGrade" (Integer) * and "randomQuestion" (Boolean) + * + * @throws IOException */ @SuppressWarnings("unchecked") @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) + throws IOException { Assessment assessment = new Assessment(); assessment.setContentId(toolContentID); - assessment.setTitle(toolContentJSON.getString(RestTags.TITLE)); - assessment.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + assessment.setTitle(toolContentJSON.get(RestTags.TITLE).asText()); + assessment.setInstructions(toolContentJSON.get(RestTags.INSTRUCTIONS).asText()); assessment.setCreated(new Date()); - assessment.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - assessment.setReflectInstructions(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, (String) null)); - assessment.setAllowGradesAfterAttempt(JsonUtil.opt(toolContentJSON, "allowGradesAfterAttempt", Boolean.FALSE)); - assessment.setAllowHistoryResponses(JsonUtil.opt(toolContentJSON, "allowHistoryResponses", Boolean.FALSE)); + assessment.setReflectOnActivity( + JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + assessment.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + assessment.setAllowGradesAfterAttempt( + JsonUtil.optBoolean(toolContentJSON, "allowGradesAfterAttempt", Boolean.FALSE)); + assessment + .setAllowHistoryResponses(JsonUtil.optBoolean(toolContentJSON, "allowHistoryResponses", Boolean.FALSE)); assessment.setAllowOverallFeedbackAfterQuestion( - JsonUtil.opt(toolContentJSON, "allowOverallFeedbackAfterQuestion", Boolean.FALSE)); - assessment.setAllowQuestionFeedback(JsonUtil.opt(toolContentJSON, "allowQuestionFeedback", Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, "allowOverallFeedbackAfterQuestion", Boolean.FALSE)); + assessment + .setAllowQuestionFeedback(JsonUtil.optBoolean(toolContentJSON, "allowQuestionFeedback", Boolean.FALSE)); assessment.setAllowRightAnswersAfterQuestion( - JsonUtil.opt(toolContentJSON, "allowRightAnswersAfterQuestion", Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, "allowRightAnswersAfterQuestion", Boolean.FALSE)); assessment.setAllowWrongAnswersAfterQuestion( - JsonUtil.opt(toolContentJSON, "allowWrongAnswersAfterQuestion", Boolean.FALSE)); - assessment.setAttemptsAllowed(JsonUtil.opt(toolContentJSON, "attemptsAllows", 1)); + JsonUtil.optBoolean(toolContentJSON, "allowWrongAnswersAfterQuestion", Boolean.FALSE)); + assessment.setAttemptsAllowed(JsonUtil.optInt(toolContentJSON, "attemptsAllows", 1)); assessment.setDefineLater(false); - assessment.setDisplaySummary(JsonUtil.opt(toolContentJSON, "displaySummary", Boolean.FALSE)); + assessment.setDisplaySummary(JsonUtil.optBoolean(toolContentJSON, "displaySummary", Boolean.FALSE)); assessment.setNotifyTeachersOnAttemptCompletion( - JsonUtil.opt(toolContentJSON, "notifyTeachersOnAttemptCompletion", Boolean.FALSE)); - assessment.setNumbered(JsonUtil.opt(toolContentJSON, "numbered", Boolean.TRUE)); - assessment.setPassingMark(JsonUtil.opt(toolContentJSON, "passingMark", 0)); - assessment.setQuestionsPerPage(JsonUtil.opt(toolContentJSON, "questionsPerPage", 0)); - assessment.setReflectInstructions(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, "")); - assessment.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - assessment.setShuffled(JsonUtil.opt(toolContentJSON, "shuffled", Boolean.FALSE)); - assessment.setTimeLimit(JsonUtil.opt(toolContentJSON, "timeLimit", 0)); + JsonUtil.optBoolean(toolContentJSON, "notifyTeachersOnAttemptCompletion", Boolean.FALSE)); + assessment.setNumbered(JsonUtil.optBoolean(toolContentJSON, "numbered", Boolean.TRUE)); + assessment.setPassingMark(JsonUtil.optInt(toolContentJSON, "passingMark", 0)); + assessment.setQuestionsPerPage(JsonUtil.optInt(toolContentJSON, "questionsPerPage", 0)); + assessment.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, "")); + assessment.setReflectOnActivity( + JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + assessment.setShuffled(JsonUtil.optBoolean(toolContentJSON, "shuffled", Boolean.FALSE)); + assessment.setTimeLimit(JsonUtil.optInt(toolContentJSON, "timeLimit", 0)); assessment.setUseSelectLeaderToolOuput( - JsonUtil.opt(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); // submission deadline set in monitoring if (toolContentJSON.has("overallFeedback")) { - throw new JSONException( + throw new IOException( "Assessment Tool does not support Overall Feedback for REST Authoring. " + toolContentJSON); } AssessmentUser assessmentUser = getUserByIDAndContent(userID.longValue(), toolContentID); if (assessmentUser == null) { assessmentUser = new AssessmentUser(); - assessmentUser.setFirstName(toolContentJSON.getString("firstName")); - assessmentUser.setLastName(toolContentJSON.getString("lastName")); - assessmentUser.setLoginName(toolContentJSON.getString("loginName")); + assessmentUser.setFirstName(toolContentJSON.get("firstName").asText()); + assessmentUser.setLastName(toolContentJSON.get("lastName").asText()); + assessmentUser.setLoginName(toolContentJSON.get("loginName").asText()); assessmentUser.setAssessment(assessment); } assessment.setCreatedBy(assessmentUser); // **************************** Set the question bank ********************* - JSONArray questions = toolContentJSON.getJSONArray("questions"); + ArrayNode questions = JsonUtil.optArray(toolContentJSON, "questions"); Set newQuestionSet = assessment.getQuestions(); // the Assessment constructor will set up the collection - for (int i = 0; i < questions.length(); i++) { - JSONObject questionJSONData = (JSONObject) questions.get(i); + for (JsonNode questionJSONData : questions) { AssessmentQuestion question = new AssessmentQuestion(); - short type = (short) questionJSONData.getInt("type"); + short type = JsonUtil.optInt(questionJSONData, "type").shortValue(); question.setType(type); - question.setTitle(questionJSONData.getString(RestTags.QUESTION_TITLE)); - question.setQuestion(questionJSONData.getString(RestTags.QUESTION_TEXT)); - question.setSequenceId(questionJSONData.getInt(RestTags.DISPLAY_ORDER)); + question.setTitle(questionJSONData.get(RestTags.QUESTION_TITLE).asText()); + question.setQuestion(questionJSONData.get(RestTags.QUESTION_TEXT).asText()); + question.setSequenceId(JsonUtil.optInt(questionJSONData, RestTags.DISPLAY_ORDER)); - question.setAllowRichEditor(JsonUtil.opt(questionJSONData, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE)); - question.setAnswerRequired(JsonUtil.opt(questionJSONData, "answerRequired", Boolean.FALSE)); - question.setCaseSensitive(JsonUtil.opt(questionJSONData, "caseSensitive", Boolean.FALSE)); - question.setCorrectAnswer(JsonUtil.opt(questionJSONData, "correctAnswer", Boolean.FALSE)); - question.setDefaultGrade(JsonUtil.opt(questionJSONData, "defaultGrade", 1)); - question.setFeedback(JsonUtil.opt(questionJSONData, "feedback", (String) null)); - question.setFeedbackOnCorrect(JsonUtil.opt(questionJSONData, "feedbackOnCorrect", (String) null)); - question.setFeedbackOnIncorrect(JsonUtil.opt(questionJSONData, "feedbackOnIncorrect", (String) null)); - question.setFeedbackOnPartiallyCorrect( - JsonUtil.opt(questionJSONData, "feedbackOnPartiallyCorrect", (String) null)); - question.setGeneralFeedback(JsonUtil.opt(questionJSONData, "generalFeedback", "")); - question.setMaxWordsLimit(JsonUtil.opt(questionJSONData, "maxWordsLimit", 0)); - question.setMinWordsLimit(JsonUtil.opt(questionJSONData, "minWordsLimit", 0)); - question.setMultipleAnswersAllowed(JsonUtil.opt(questionJSONData, "multipleAnswersAllowed", Boolean.FALSE)); + question.setAllowRichEditor( + JsonUtil.optBoolean(questionJSONData, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE)); + question.setAnswerRequired(JsonUtil.optBoolean(questionJSONData, "answerRequired", Boolean.FALSE)); + question.setCaseSensitive(JsonUtil.optBoolean(questionJSONData, "caseSensitive", Boolean.FALSE)); + question.setCorrectAnswer(JsonUtil.optBoolean(questionJSONData, "correctAnswer", Boolean.FALSE)); + question.setDefaultGrade(JsonUtil.optInt(questionJSONData, "defaultGrade", 1)); + question.setFeedback(JsonUtil.optString(questionJSONData, "feedback")); + question.setFeedbackOnCorrect(JsonUtil.optString(questionJSONData, "feedbackOnCorrect")); + question.setFeedbackOnIncorrect(JsonUtil.optString(questionJSONData, "feedbackOnIncorrect")); + question.setFeedbackOnPartiallyCorrect(JsonUtil.optString(questionJSONData, "feedbackOnPartiallyCorrect")); + question.setGeneralFeedback(JsonUtil.optString(questionJSONData, "generalFeedback", "")); + question.setMaxWordsLimit(JsonUtil.optInt(questionJSONData, "maxWordsLimit", 0)); + question.setMinWordsLimit(JsonUtil.optInt(questionJSONData, "minWordsLimit", 0)); + question.setMultipleAnswersAllowed( + JsonUtil.optBoolean(questionJSONData, "multipleAnswersAllowed", Boolean.FALSE)); question.setIncorrectAnswerNullifiesMark( - JsonUtil.opt(questionJSONData, "incorrectAnswerNullifiesMark", Boolean.FALSE)); - question.setPenaltyFactor(Float.parseFloat(JsonUtil.opt(questionJSONData, "penaltyFactor", "0.0"))); + JsonUtil.optBoolean(questionJSONData, "incorrectAnswerNullifiesMark", Boolean.FALSE)); + question.setPenaltyFactor(JsonUtil.optDouble(questionJSONData, "penaltyFactor", 0.0).floatValue()); // question.setUnits(units); Needed for numerical type question if ((type == AssessmentConstants.QUESTION_TYPE_MATCHING_PAIRS) @@ -2986,22 +3028,21 @@ || (type == AssessmentConstants.QUESTION_TYPE_MARK_HEDGING)) { if (!questionJSONData.has(RestTags.ANSWERS)) { - throw new JSONException("REST Authoring is missing answers for a question of type " + type - + ". Data:" + toolContentJSON); + throw new IOException("REST Authoring is missing answers for a question of type " + type + ". Data:" + + toolContentJSON); } - Set optionList = new LinkedHashSet(); - JSONArray optionsData = questionJSONData.getJSONArray(RestTags.ANSWERS); - for (int j = 0; j < optionsData.length(); j++) { - JSONObject answerData = (JSONObject) optionsData.get(j); + Set optionList = new LinkedHashSet<>(); + ArrayNode optionsData = JsonUtil.optArray(questionJSONData, RestTags.ANSWERS); + for (JsonNode answerData : optionsData) { AssessmentQuestionOption option = new AssessmentQuestionOption(); - option.setSequenceId(answerData.getInt(RestTags.DISPLAY_ORDER)); - option.setGrade(Float.parseFloat(answerData.getString("grade"))); - option.setCorrect(Boolean.parseBoolean(JsonUtil.opt(answerData, "correct", "false"))); - option.setAcceptedError(Float.parseFloat(JsonUtil.opt(answerData, "acceptedError", "0.0"))); - option.setFeedback(JsonUtil.opt(answerData, "feedback", (String) null)); - option.setOptionString(JsonUtil.opt(answerData, RestTags.ANSWER_TEXT, (String) null)); - option.setOptionFloat(Float.parseFloat(JsonUtil.opt(answerData, "answerFloat", "0.0"))); + option.setSequenceId(JsonUtil.optInt(answerData, RestTags.DISPLAY_ORDER)); + option.setGrade(answerData.get("grade").floatValue()); + option.setCorrect(JsonUtil.optBoolean(answerData, "correct", false)); + option.setAcceptedError(JsonUtil.optDouble(answerData, "acceptedError", 0.0).floatValue()); + option.setFeedback(JsonUtil.optString(answerData, "feedback")); + option.setOptionString(JsonUtil.optString(answerData, RestTags.ANSWER_TEXT)); + option.setOptionFloat(JsonUtil.optDouble(answerData, "answerFloat", 0.0).floatValue()); // option.setQuestion(question); can't find the use for this field yet! optionList.add(option); } @@ -3013,23 +3054,23 @@ } // **************************** Now set up the references to the questions in the bank ********************* - JSONArray references = toolContentJSON.getJSONArray("references"); + ArrayNode references = JsonUtil.optArray(toolContentJSON, "references"); Set newReferenceSet = assessment.getQuestionReferences(); // the Assessment constructor will set up the - // collection - for (int i = 0; i < references.length(); i++) { - JSONObject referenceJSONData = (JSONObject) references.get(i); + + ;// collection + for (JsonNode referenceJSONData : references) { QuestionReference reference = new QuestionReference(); reference.setType((short) 0); - reference.setDefaultGrade(JsonUtil.opt(referenceJSONData, "defaultGrade", 1)); - reference.setSequenceId(referenceJSONData.getInt(RestTags.DISPLAY_ORDER)); + reference.setDefaultGrade(JsonUtil.optInt(referenceJSONData, "defaultGrade", 1)); + reference.setSequenceId(JsonUtil.optInt(referenceJSONData, RestTags.DISPLAY_ORDER)); AssessmentQuestion matchingQuestion = matchQuestion(newQuestionSet, - referenceJSONData.getInt("questionDisplayOrder")); + JsonUtil.optInt(referenceJSONData, "questionDisplayOrder")); if (matchingQuestion == null) { - throw new JSONException("Unable to find matching question for displayOrder " + throw new IOException("Unable to find matching question for displayOrder " + referenceJSONData.get("questionDisplayOrder") + ". Data:" + toolContentJSON); } reference.setQuestion(matchingQuestion); - reference.setRandomQuestion(JsonUtil.opt(referenceJSONData, "randomQuestion", Boolean.FALSE)); + reference.setRandomQuestion(JsonUtil.optBoolean(referenceJSONData, "randomQuestion", Boolean.FALSE)); reference.setTitle(null); newReferenceSet.add(reference); } @@ -3051,10 +3092,10 @@ } // TODO Implement REST support for all types and then remove checkType method - void checkType(short type) throws JSONException { + void checkType(short type) throws IOException { if ((type != AssessmentConstants.QUESTION_TYPE_ESSAY) && (type != AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE)) { - throw new JSONException( + throw new IOException( "Assessment Tool does not support REST Authoring for anything but Essay Type and Multiple Choice. Found type " + type); } Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/LearningAction.java =================================================================== diff -u -r373dcc4ea6d1a07c60268ceccd9d1e69d9c35f9c -rac624414ec459fe718b3bfaf9a381e58b58398fc --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/LearningAction.java (.../LearningAction.java) (revision 373dcc4ea6d1a07c60268ceccd9d1e69d9c35f9c) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/LearningAction.java (.../LearningAction.java) (revision ac624414ec459fe718b3bfaf9a381e58b58398fc) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.assessment.web.action; import java.io.IOException; @@ -54,8 +53,6 @@ import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionRedirect; -import org.apache.tomcat.util.json.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.confidencelevel.ConfidenceLevel; import org.lamsfoundation.lams.learning.web.bean.ActivityPositionDTO; import org.lamsfoundation.lams.learning.web.util.LearningWebUtil; @@ -89,6 +86,9 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Andrey Balan */ @@ -99,7 +99,7 @@ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, IllegalAccessException, - InstantiationException, InvocationTargetException, NoSuchMethodException, JSONException { + InstantiationException, InvocationTargetException, NoSuchMethodException { String param = mapping.getParameter(); if (param.equals("start")) { @@ -138,7 +138,7 @@ if (param.equals("getSecondsLeft")) { return getSecondsLeft(mapping, form, request, response); } - + // ================ Reflection ======================= if (param.equals("newReflection")) { return newReflection(mapping, form, request, response); @@ -162,7 +162,7 @@ InvocationTargetException, NoSuchMethodException { // initialize Session Map - SessionMap sessionMap = new SessionMap(); + SessionMap sessionMap = new SessionMap<>(); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); // save toolContentID into HTTPSession @@ -202,22 +202,25 @@ return mapping.findForward(AssessmentConstants.WAIT_FOR_LEADER); } - + // forwards to the waitForLeader pages boolean isNonLeader = !user.getUserId().equals(groupLeader.getUserId()); if (assessment.getTimeLimit() != 0 && isNonLeader && !user.isSessionFinished()) { - AssessmentResult lastLeaderResult = service.getLastAssessmentResult(assessment.getUid(), groupLeader.getUserId()); + AssessmentResult lastLeaderResult = service.getLastAssessmentResult(assessment.getUid(), + groupLeader.getUserId()); //show waitForLeaderLaunchTimeLimit page if the leader hasn't started activity or hasn't pressed OK button to launch time limit if (lastLeaderResult == null || lastLeaderResult.getTimeLimitLaunchedDate() == null) { - request.setAttribute(AssessmentConstants.PARAM_WAITING_MESSAGE_KEY, "label.waiting.for.leader.launch.time.limit"); + request.setAttribute(AssessmentConstants.PARAM_WAITING_MESSAGE_KEY, + "label.waiting.for.leader.launch.time.limit"); return mapping.findForward(AssessmentConstants.WAIT_FOR_LEADER_TIME_LIMIT); - } - + } + //if the time is up and leader hasn't submitted response - show waitForLeaderFinish page boolean isTimeLimitExceeded = service.checkTimeLimitExceeded(assessment, groupLeader); if (isTimeLimitExceeded && !groupLeader.isSessionFinished()) { - request.setAttribute(AssessmentConstants.PARAM_WAITING_MESSAGE_KEY, "label.waiting.for.leader.finish"); + request.setAttribute(AssessmentConstants.PARAM_WAITING_MESSAGE_KEY, + "label.waiting.for.leader.finish"); return mapping.findForward(AssessmentConstants.WAIT_FOR_LEADER_TIME_LIMIT); } } @@ -235,10 +238,10 @@ boolean isUserLeader = service.isUserGroupLeader(user, new Long(toolSessionId)); sessionMap.put(AssessmentConstants.ATTR_IS_USER_LEADER, isUserLeader); - Set questionReferences = new TreeSet(new SequencableComparator()); + Set questionReferences = new TreeSet<>(new SequencableComparator()); questionReferences.addAll(assessment.getQuestionReferences()); - HashMap questionToReferenceMap = new HashMap(); - ArrayList takenQuestion = new ArrayList(); + HashMap questionToReferenceMap = new HashMap<>(); + ArrayList takenQuestion = new ArrayList<>(); //add non-random questions for (QuestionReference questionReference : questionReferences) { @@ -293,7 +296,7 @@ sessionMap.put(AssessmentConstants.ATTR_REFLECTION_ON, assessment.isReflectOnActivity()); sessionMap.put(AssessmentConstants.ATTR_REFLECTION_INSTRUCTION, assessment.getReflectInstructions()); sessionMap.put(AssessmentConstants.ATTR_REFLECTION_ENTRY, entryText); - + //time limit boolean isTimeLimitEnabled = hasEditRight && !showResults && assessment.getTimeLimit() != 0; long secondsLeft = isTimeLimitEnabled ? service.getSecondsLeft(assessment, user) : 0; @@ -329,10 +332,10 @@ } //sort questions - LinkedList questionDtos = new LinkedList(); + LinkedList questionDtos = new LinkedList<>(); for (QuestionReference questionReference : questionReferences) { AssessmentQuestion question = questionToReferenceMap.get(questionReference.getUid()); - + QuestionDTO questionDto = question.getQuestionDTO(); questionDto.setGrade(questionReference.getDefaultGrade()); @@ -341,33 +344,32 @@ // shuffling if (assessment.isShuffled()) { - ArrayList shuffledList = new ArrayList(questionDtos); + ArrayList shuffledList = new ArrayList<>(questionDtos); Collections.shuffle(shuffledList); - questionDtos = new LinkedList(shuffledList); + questionDtos = new LinkedList<>(shuffledList); } - for (QuestionDTO questionDto : questionDtos) { + for (QuestionDTO questionDto : questionDtos) { if (questionDto.isShuffle() || (questionDto.getType() == AssessmentConstants.QUESTION_TYPE_ORDERING)) { - ArrayList shuffledList = new ArrayList(questionDto.getOptionDtos()); + ArrayList shuffledList = new ArrayList<>(questionDto.getOptionDtos()); Collections.shuffle(shuffledList); - questionDto.setOptionDtos(new LinkedHashSet(shuffledList)); + questionDto.setOptionDtos(new LinkedHashSet<>(shuffledList)); } if (questionDto.getType() == AssessmentConstants.QUESTION_TYPE_MATCHING_PAIRS) { //sort answer options alphanumerically (as per LDEV-4326) - ArrayList optionsSortedByOptionString = new ArrayList( - questionDto.getOptionDtos()); + ArrayList optionsSortedByOptionString = new ArrayList<>(questionDto.getOptionDtos()); optionsSortedByOptionString.sort(new Comparator() { @Override public int compare(OptionDTO o1, OptionDTO o2) { String optionString1 = o1.getOptionString() != null ? o1.getOptionString() : ""; String optionString2 = o2.getOptionString() != null ? o2.getOptionString() : ""; - + return AlphanumComparator.compareAlphnumerically(optionString1, optionString2); } }); - questionDto.setMatchingPairOptions(new LinkedHashSet(optionsSortedByOptionString)); + questionDto.setMatchingPairOptions(new LinkedHashSet<>(optionsSortedByOptionString)); } } - + // populate user entered confidence levels if (assessment.isEnableConfidenceLevels()) { List confidenceLevels = service.getConfidenceLevelsByUser(user.getUserId().intValue(), @@ -385,17 +387,18 @@ } //paging - List> pagedQuestionDtos = new ArrayList>(); + List> pagedQuestionDtos = new ArrayList<>(); int maxQuestionsPerPage = ((assessment.getQuestionsPerPage() != 0) && hasEditRight) - ? assessment.getQuestionsPerPage() : questionDtos.size(); - LinkedHashSet questionsForOnePage = new LinkedHashSet(); + ? assessment.getQuestionsPerPage() + : questionDtos.size(); + LinkedHashSet questionsForOnePage = new LinkedHashSet<>(); pagedQuestionDtos.add(questionsForOnePage); int count = 0; for (QuestionDTO questionDto : questionDtos) { questionsForOnePage.add(questionDto); count++; if ((questionsForOnePage.size() == maxQuestionsPerPage) && (count != questionDtos.size())) { - questionsForOnePage = new LinkedHashSet(); + questionsForOnePage = new LinkedHashSet<>(); pagedQuestionDtos.add(questionsForOnePage); } } @@ -407,7 +410,7 @@ // loadupLastAttempt for display purpose loadupLastAttempt(sessionMap); - + if (showResults) { // display results page @@ -423,12 +426,12 @@ return mapping.findForward(AssessmentConstants.LEARNING); } } - + /** * Checks Leader Progress */ private ActionForward checkLeaderProgress(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { IAssessmentService service = getAssessmentService(); Long toolSessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); @@ -440,32 +443,36 @@ boolean isTimeLimitExceeded = service.checkTimeLimitExceeded(session.getAssessment(), leader); boolean isLeaderResponseFinalized = leader.isSessionFinished(); - JSONObject JSONObject = new JSONObject(); - JSONObject.put("isPageRefreshRequested", isLeaderResponseFinalized || isTimeLimitExceeded); + ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); + ObjectNode.put("isPageRefreshRequested", isLeaderResponseFinalized || isTimeLimitExceeded); response.setContentType("application/x-json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); return null; } /** * Shows next page. It's available only to leaders as non-leaders see all questions on one page. - * @throws NoSuchMethodException - * @throws InvocationTargetException - * @throws IllegalAccessException + * + * @throws NoSuchMethodException + * @throws InvocationTargetException + * @throws IllegalAccessException */ private ActionForward nextPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws ServletException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { + HttpServletResponse response) + throws ServletException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { return nextPage(mapping, request, false, -1); } - + /** * Auxiliary method to be called by nextPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, - * HttpServletResponse response) or submitAll. + * HttpServletResponse response) or submitAll. * * @param mapping * @param request - * @param isAnswersValidationFailed submitAll() method may set it as true in case some of the pages miss required answers - * @param pageNumberWithUnasweredQuestions page number with questions required to be answered + * @param isAnswersValidationFailed + * submitAll() method may set it as true in case some of the pages miss required answers + * @param pageNumberWithUnasweredQuestions + * page number with questions required to be answered * @return */ private ActionForward nextPage(ActionMapping mapping, HttpServletRequest request, boolean isAnswersValidationFailed, @@ -501,7 +508,7 @@ if (showResults) { request.setAttribute(AssessmentConstants.ATTR_SESSION_MAP_ID, sessionMapID); return mapping.findForward(AssessmentConstants.SHOW_RESULTS); - + } else { //get user answers from request and store them into sessionMap storeUserAnswersIntoSessionMap(request, oldPageNumber); @@ -510,7 +517,7 @@ long secondsLeft = service.getSecondsLeft(assessment, user); sessionMap.put(AssessmentConstants.ATTR_SECONDS_LEFT, secondsLeft); - + // use redirect to prevent form resubmission ActionRedirect redirect = new ActionRedirect(mapping.findForwardConfig(AssessmentConstants.LEARNING)); redirect.addParameter(AssessmentConstants.ATTR_SESSION_MAP_ID, sessionMapID); @@ -523,13 +530,14 @@ * Ajax call to get the remaining seconds. Needed when the page is reloaded in the browser to check with the server * what the current values should be! Otherwise the learner can keep hitting reload after a page change or submit * all (when questions are spread across pages) and increase their time! + * * @return - * @throws JSONException - * @throws IOException + * @throws JSONException + * @throws IOException */ private ActionForward getSecondsLeft(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) - throws ServletException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, JSONException, IOException { + HttpServletResponse response) throws ServletException, IllegalAccessException, InvocationTargetException, + NoSuchMethodException, IOException { IAssessmentService service = getAssessmentService(); String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID); @@ -538,21 +546,23 @@ Assessment assessment = (Assessment) sessionMap.get(AssessmentConstants.ATTR_ASSESSMENT); AssessmentUser user = (AssessmentUser) sessionMap.get(AssessmentConstants.ATTR_USER); long secondsLeft = service.getSecondsLeft(assessment, user); - JSONObject JSONObject = new JSONObject(); - JSONObject.put(AssessmentConstants.ATTR_SECONDS_LEFT, secondsLeft); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.put(AssessmentConstants.ATTR_SECONDS_LEFT, secondsLeft); response.setContentType("application/x-json;charset=utf-8"); - response.getWriter().print(JSONObject); - return null; + response.getWriter().print(responseJSON); + return null; } /** * Handling submittion of MarkHedging type of Questions (in case of leader aware tool). - * @throws NoSuchMethodException - * @throws InvocationTargetException - * @throws IllegalAccessException + * + * @throws NoSuchMethodException + * @throws InvocationTargetException + * @throws IllegalAccessException */ private ActionForward submitSingleMarkHedgingQuestion(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) throws ServletException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { + HttpServletRequest request, HttpServletResponse response) + throws ServletException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { IAssessmentService service = getAssessmentService(); String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession() @@ -569,7 +579,8 @@ // store results from sessionMap into DB Long singleMarkHedgingQuestionUid = WebUtil.readLongParam(request, "singleMarkHedgingQuestionUid"); - boolean isResultsStored = service.storeUserAnswers(assessment, userId, pagedQuestionDtos, singleMarkHedgingQuestionUid, false); + boolean isResultsStored = service.storeUserAnswers(assessment, userId, pagedQuestionDtos, + singleMarkHedgingQuestionUid, false); // result was not stored in case user was prohibited from submitting (or autosubmitting) answers (e.g. when // using 2 browsers). Then show last stored results if (!isResultsStored) { @@ -602,12 +613,14 @@ /** * Display same entire authoring page content from HttpSession variable. - * @throws NoSuchMethodException - * @throws InvocationTargetException - * @throws IllegalAccessException + * + * @throws NoSuchMethodException + * @throws InvocationTargetException + * @throws IllegalAccessException */ private ActionForward submitAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws ServletException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { + HttpServletResponse response) + throws ServletException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession() .getAttribute(sessionMapID); @@ -639,7 +652,7 @@ // populate info for displaying results page showResults(mapping, sessionMap); - + //use redirect to prevent form resubmission ActionRedirect redirect = new ActionRedirect(mapping.findForwardConfig(AssessmentConstants.SHOW_RESULTS)); redirect.addParameter(AssessmentConstants.ATTR_SESSION_MAP_ID, sessionMapID); @@ -662,20 +675,20 @@ AssessmentUser assessmentUser = (AssessmentUser) sessionMap.get(AssessmentConstants.ATTR_USER); Long userId = assessmentUser.getUserId(); service.unsetSessionFinished(toolSessionId, userId); - + Date lastAttemptStartingDate = service.getLastAssessmentResult(assessment.getUid(), userId).getStartDate(); - + // set attempt started: create a new one + mark previous as not being the latest any longer service.setAttemptStarted(assessment, assessmentUser, toolSessionId); - + // in case of content was modified in monitor - redirect to start.do in order to refresh info from the DB if (assessment.isContentModifiedInMonitor(lastAttemptStartingDate)) { ActionRedirect redirect = new ActionRedirect(mapping.findForwardConfig("learningStartMethod")); redirect.addParameter(AttributeNames.PARAM_MODE, mode.toString()); redirect.addParameter(AssessmentConstants.PARAM_TOOL_SESSION_ID, toolSessionId); return redirect; - - //otherwise use data from SessionMap + + //otherwise use data from SessionMap } else { sessionMap.put(AssessmentConstants.ATTR_SHOW_RESULTS, false); @@ -760,7 +773,7 @@ int optionIndex = NumberUtils.stringToInt(request.getParameter(AssessmentConstants.PARAM_OPTION_INDEX), -1); if (optionIndex != -1) { - List rList = new ArrayList(optionDtoList); + List rList = new ArrayList<>(optionDtoList); // get current and the target item, and switch their sequnece OptionDTO option = rList.remove(optionIndex); @@ -771,7 +784,7 @@ } // put back list - optionDtoList = new LinkedHashSet(rList); + optionDtoList = new LinkedHashSet<>(rList); questionDto.setOptionDtos(optionDtoList); } @@ -782,12 +795,14 @@ /** * auto saves responses - * @throws NoSuchMethodException - * @throws InvocationTargetException - * @throws IllegalAccessException + * + * @throws NoSuchMethodException + * @throws InvocationTargetException + * @throws IllegalAccessException */ private ActionForward autoSaveAnswers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + HttpServletResponse response) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { IAssessmentService service = getAssessmentService(); String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession() @@ -801,7 +816,7 @@ return null; } - + /** * Stores date when user has started activity with time limit */ @@ -811,11 +826,11 @@ String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession() .getAttribute(sessionMapID); - + Long assessmentUid = ((Assessment) sessionMap.get(AssessmentConstants.ATTR_ASSESSMENT)).getUid(); Long userId = ((AssessmentUser) sessionMap.get(AssessmentConstants.ATTR_USER)).getUserId(); sessionMap.put(AssessmentConstants.ATTR_IS_TIME_LIMIT_NOT_LAUNCHED, false); - + service.launchTimeLimit(assessmentUid, userId); return null; @@ -890,7 +905,8 @@ * Get back user answers from request and store it into sessionMap. * * @param request - * @param pageNumber number of the page to process + * @param pageNumber + * number of the page to process */ private void storeUserAnswersIntoSessionMap(HttpServletRequest request, int pageNumber) { String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID); @@ -1016,7 +1032,8 @@ int questionType = questionDto.getType(); //enforce all hedging marks question type to be answered as well - if (questionDto.isAnswerRequired() || (questionType == AssessmentConstants.QUESTION_TYPE_MARK_HEDGING)) { + if (questionDto.isAnswerRequired() + || (questionType == AssessmentConstants.QUESTION_TYPE_MARK_HEDGING)) { boolean isAnswered = false; @@ -1066,13 +1083,14 @@ if ((questionDto.getType() == AssessmentConstants.QUESTION_TYPE_ESSAY) && (questionDto.getMinWordsLimit() > 0)) { - if ( questionDto.getAnswerString() == null ) { + if (questionDto.getAnswerString() == null) { isAllQuestionsReachedMinWordsLimit = false; break; - + } else { - boolean isMinWordsLimitReached = ValidationUtil.isMinWordsLimitReached(questionDto.getAnswerString(), - questionDto.getMinWordsLimit(), questionDto.isAllowRichEditor()); + boolean isMinWordsLimitReached = ValidationUtil.isMinWordsLimitReached( + questionDto.getAnswerString(), questionDto.getMinWordsLimit(), + questionDto.isAllowRichEditor()); // check min words limit is reached if (!isMinWordsLimitReached) { isAllQuestionsReachedMinWordsLimit = false; @@ -1101,7 +1119,7 @@ Assessment assessment = (Assessment) sessionMap.get(AssessmentConstants.ATTR_ASSESSMENT); Long userId = ((AssessmentUser) sessionMap.get(AssessmentConstants.ATTR_USER)).getUserId(); IAssessmentService service = getAssessmentService(); - + int dbResultCount = service.getAssessmentResultCount(assessment.getUid(), userId); if (dbResultCount > 0) { @@ -1221,7 +1239,7 @@ questionDto.setPenalty(questionResult.getPenalty()); for (OptionDTO optionDto : questionDto.getOptionDtos()) { - + for (AssessmentOptionAnswer optionAnswer : questionResult.getOptionAnswers()) { if (optionDto.getUid().equals(optionAnswer.getOptionUid())) { optionDto.setAnswerBoolean(optionAnswer.getAnswerBoolean()); @@ -1233,7 +1251,7 @@ //sort ordering type of question in order to show how learner has sorted them if (questionDto.getType() == AssessmentConstants.QUESTION_TYPE_ORDERING) { - + //don't sort ordering type of questions that haven't been submitted to not break their shuffled order boolean isOptionAnswersNeverSubmitted = true; for (OptionDTO optionDto : questionDto.getOptionDtos()) { @@ -1243,7 +1261,7 @@ } if (!isOptionAnswersNeverSubmitted) { - TreeSet orderedSet = new TreeSet(new AnswerIntComparator()); + TreeSet orderedSet = new TreeSet<>(new AnswerIntComparator()); orderedSet.addAll(questionDto.getOptionDtos()); questionDto.setOptionDtos(orderedSet); } @@ -1269,20 +1287,22 @@ /** * Store user answers in DB in last unfinished attempt and notify teachers about it. - * @throws NoSuchMethodException - * @throws InvocationTargetException - * @throws IllegalAccessException + * + * @throws NoSuchMethodException + * @throws InvocationTargetException + * @throws IllegalAccessException */ - private boolean storeUserAnswersIntoDatabase(SessionMap sessionMap, boolean isAutosave) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { - + private boolean storeUserAnswersIntoDatabase(SessionMap sessionMap, boolean isAutosave) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + List> pagedQuestionDtos = (List>) sessionMap .get(AssessmentConstants.ATTR_PAGED_QUESTION_DTOS); IAssessmentService service = getAssessmentService(); Long toolSessionId = (Long) sessionMap.get(AssessmentConstants.ATTR_TOOL_SESSION_ID); Long userId = ((AssessmentUser) sessionMap.get(AssessmentConstants.ATTR_USER)).getUserId(); ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE); Assessment assessment = service.getAssessmentBySessionId(toolSessionId); - + boolean isResultsStored = service.storeUserAnswers(assessment, userId, pagedQuestionDtos, null, isAutosave); // notify teachers @@ -1322,8 +1342,8 @@ private AssessmentUser getSpecifiedUser(IAssessmentService service, Long sessionId, Integer userId) { AssessmentUser assessmentUser = service.getUserByIDAndSession(new Long(userId.intValue()), sessionId); if (assessmentUser == null) { - LearningAction.log - .error("Unable to find specified user for assessment activity. Screens are likely to fail. SessionId=" + LearningAction.log.error( + "Unable to find specified user for assessment activity. Screens are likely to fail. SessionId=" + sessionId + " UserId=" + userId); } return assessmentUser; Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/MonitoringAction.java =================================================================== diff -u -r373dcc4ea6d1a07c60268ceccd9d1e69d9c35f9c -rac624414ec459fe718b3bfaf9a381e58b58398fc --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision 373dcc4ea6d1a07c60268ceccd9d1e69d9c35f9c) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision ac624414ec459fe718b3bfaf9a381e58b58398fc) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.assessment.web.action; import java.io.IOException; @@ -47,9 +46,6 @@ import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; -import org.apache.tomcat.util.json.JSONArray; -import org.apache.tomcat.util.json.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.confidencelevel.ConfidenceLevel; import org.lamsfoundation.lams.gradebook.util.GradebookConstants; import org.lamsfoundation.lams.tool.assessment.AssessmentConstants; @@ -73,21 +69,26 @@ import org.lamsfoundation.lams.util.DateUtil; import org.lamsfoundation.lams.util.ExcelCell; import org.lamsfoundation.lams.util.ExcelUtil; +import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.web.session.SessionManager; import org.lamsfoundation.lams.web.util.AttributeNames; import org.lamsfoundation.lams.web.util.SessionMap; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + public class MonitoringAction extends Action { public static Logger log = Logger.getLogger(MonitoringAction.class); private IAssessmentService service; @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException { + HttpServletResponse response) throws IOException, ServletException { request.setAttribute("initialTabId", WebUtil.readLongParam(request, AttributeNames.PARAM_CURRENT_TAB, true)); String param = mapping.getParameter(); @@ -127,7 +128,7 @@ if (param.equals("statistic")) { return statistic(mapping, form, request, response); } - + return mapping.findForward(AssessmentConstants.ERROR); } @@ -136,7 +137,7 @@ initAssessmentService(); // initialize Session Map - SessionMap sessionMap = new SessionMap(); + SessionMap sessionMap = new SessionMap<>(); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); request.setAttribute(AssessmentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); @@ -154,7 +155,8 @@ Date tzSubmissionDeadline = DateUtil.convertToTimeZoneFromDefault(teacherTimeZone, submissionDeadline); request.setAttribute(AssessmentConstants.ATTR_SUBMISSION_DEADLINE, tzSubmissionDeadline.getTime()); // use the unconverted time, as convertToStringForJSON() does the timezone conversion if needed - request.setAttribute(AssessmentConstants.ATTR_SUBMISSION_DEADLINE_DATESTRING, DateUtil.convertToStringForJSON(submissionDeadline, request.getLocale())); + request.setAttribute(AssessmentConstants.ATTR_SUBMISSION_DEADLINE_DATESTRING, + DateUtil.convertToStringForJSON(submissionDeadline, request.getLocale())); } @@ -166,7 +168,7 @@ } //prepare list of the questions to display in question drop down menu, filtering out questions that aren't supposed to be answered - Set questionList = new TreeSet(); + Set questionList = new TreeSet<>(); //in case there is at least one random question - we need to show all questions in a drop down select if (assessment.hasRandomQuestion()) { questionList.addAll(assessment.getQuestions()); @@ -179,7 +181,7 @@ } //prepare toolOutputDefinitions and activityEvaluation - List toolOutputDefinitions = new ArrayList(); + List toolOutputDefinitions = new ArrayList<>(); toolOutputDefinitions.add(AssessmentConstants.OUTPUT_NAME_LEARNER_TOTAL_SCORE); toolOutputDefinitions.add(AssessmentConstants.OUTPUT_NAME_BEST_SCORE); toolOutputDefinitions.add(AssessmentConstants.OUTPUT_NAME_FIRST_SCORE); @@ -199,7 +201,7 @@ WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID)); return mapping.findForward(AssessmentConstants.SUCCESS); } - + private ActionForward userMasterDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { initAssessmentService(); @@ -271,7 +273,7 @@ * @param request * @param response * @return - * @throws IOException + * @throws IOException */ private ActionForward setSubmissionDeadline(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -312,7 +314,7 @@ * @throws IOException */ private ActionForward setActivityEvaluation(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { initAssessmentService(); String sessionMapID = request.getParameter(AssessmentConstants.ATTR_SESSION_MAP_ID); @@ -323,11 +325,11 @@ String activityEvaluation = WebUtil.readStrParam(request, AssessmentConstants.ATTR_ACTIVITY_EVALUATION); service.setActivityEvaluation(contentID, activityEvaluation); - // update the session ready for stats tab to be reloaded otherwise flicking between tabs + // update the session ready for stats tab to be reloaded otherwise flicking between tabs // causes the old value to be redisplayed sessionMap.put(AssessmentConstants.ATTR_ACTIVITY_EVALUATION, activityEvaluation); - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); responseJSON.put("success", "true"); response.setContentType("application/json;charset=utf-8"); response.getWriter().print(new String(responseJSON.toString())); @@ -338,7 +340,7 @@ * Refreshes user list. */ public ActionForward getUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse res) throws IOException, ServletException, JSONException { + HttpServletResponse res) throws IOException, ServletException { initAssessmentService(); String sessionMapID = request.getParameter(AssessmentConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession() @@ -357,7 +359,7 @@ } String searchString = WebUtil.readStrParam(request, "userName", true); - List userDtos = new ArrayList(); + List userDtos = new ArrayList<>(); int countSessionUsers = 0; //in case of UseSelectLeaderToolOuput - display only one user if (assessment.isUseSelectLeaderToolOuput()) { @@ -390,31 +392,31 @@ Math.ceil(new Integer(countSessionUsers).doubleValue() / new Integer(rowLimit).doubleValue())) .intValue(); - JSONArray rows = new JSONArray(); + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); int i = 1; for (AssessmentUserDTO userDto : userDtos) { - JSONArray userData = new JSONArray(); - userData.put(userDto.getUserId()); - userData.put(sessionId); + ArrayNode userData = JsonNodeFactory.instance.arrayNode(); + userData.add(userDto.getUserId()); + userData.add(sessionId); String fullName = StringEscapeUtils.escapeHtml(userDto.getFirstName() + " " + userDto.getLastName()); - userData.put(fullName); - userData.put(userDto.getGrade()); + userData.add(fullName); + userData.add(userDto.getGrade()); if (userDto.getPortraitId() != null ) - userData.put(userDto.getPortraitId()); + userData.add(userDto.getPortraitId()); - JSONObject userRow = new JSONObject(); + ObjectNode userRow = JsonNodeFactory.instance.objectNode(); userRow.put("id", i++); - userRow.put("cell", userData); + userRow.set("cell", userData); - rows.put(userRow); + rows.add(userRow); } - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); responseJSON.put("total", totalPages); responseJSON.put("page", page); responseJSON.put("records", countSessionUsers); - responseJSON.put("rows", rows); + responseJSON.set("rows", rows); res.setContentType("application/json;charset=utf-8"); res.getWriter().print(new String(responseJSON.toString())); @@ -425,7 +427,7 @@ * Refreshes user list. */ public ActionForward getUsersByQuestion(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse res) throws IOException, ServletException, JSONException { + HttpServletResponse res) throws IOException, ServletException { initAssessmentService(); String sessionMapID = request.getParameter(AssessmentConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession() @@ -445,7 +447,7 @@ } String searchString = WebUtil.readStrParam(request, "userName", true); - List userDtos = new ArrayList(); + List userDtos = new ArrayList<>(); int countSessionUsers = 0; //in case of UseSelectLeaderToolOuput - display only one user if (assessment.isUseSelectLeaderToolOuput()) { @@ -485,26 +487,26 @@ int totalPages = new Double( Math.ceil(new Integer(countSessionUsers).doubleValue() / new Integer(rowLimit).doubleValue())) .intValue(); - + List confidenceLevels = assessment.isEnableConfidenceLevels() ? service.getConfidenceLevelsByQuestionAndSession(questionUid, sessionId) : null; - JSONArray rows = new JSONArray(); + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); int i = 1; for (AssessmentUserDTO userDto : userDtos) { Long questionResultUid = userDto.getQuestionResultUid(); String fullName = StringEscapeUtils.escapeHtml(userDto.getFirstName() + " " + userDto.getLastName()); - JSONArray userData = new JSONArray(); + ArrayNode userData = JsonNodeFactory.instance.arrayNode(); if (questionResultUid != null) { AssessmentQuestionResult questionResult = service.getAssessmentQuestionResultByUid(questionResultUid); - userData.put(questionResultUid); - userData.put(questionResult.getMaxMark()); - userData.put(fullName); - userData.put(AssessmentEscapeUtils.printResponsesForJqgrid(questionResult)); + userData.add(questionResultUid); + userData.add(questionResult.getMaxMark()); + userData.add(fullName); + userData.add(AssessmentEscapeUtils.printResponsesForJqgrid(questionResult)); // prepare for displaying purposes confidence levels if (assessment.isEnableConfidenceLevels()) { @@ -516,45 +518,45 @@ break; } } - userData.put(confidence); + userData.add(confidence); } - userData.put(questionResult.getMark()); - + userData.add(questionResult.getMark()); + } else { - userData.put(""); - userData.put(""); - userData.put(fullName); - userData.put("-"); + userData.add(""); + userData.add(""); + userData.add(fullName); + userData.add("-"); if (assessment.isEnableConfidenceLevels()) { - userData.put(-1); + userData.add(-1); } - userData.put("-"); + userData.add("-"); } - JSONObject userRow = new JSONObject(); + ObjectNode userRow = JsonNodeFactory.instance.objectNode(); userRow.put("id", i++); - userRow.put("cell", userData); + userRow.set("cell", userData); - rows.put(userRow); + rows.add(userRow); } - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); responseJSON.put("total", totalPages); responseJSON.put("page", page); responseJSON.put("records", countSessionUsers); - responseJSON.put("rows", rows); + responseJSON.set("rows", rows); res.setContentType("application/json;charset=utf-8"); res.getWriter().print(new String(responseJSON.toString())); return null; } - /** + /** * Get the mark summary with data arranged in bands. Can be displayed graphically or in a table. */ private ActionForward getMarkChartData(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse res) throws IOException, ServletException, JSONException { + HttpServletResponse res) throws IOException, ServletException { initAssessmentService(); @@ -566,22 +568,23 @@ Long contentId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_CONTENT_ID); Assessment assessment = service.getAssessmentByContentId(contentId); List results = null; - - if ( assessment != null ) { - if ( assessment.isUseSelectLeaderToolOuput() ) { + + if (assessment != null) { + if (assessment.isUseSelectLeaderToolOuput()) { results = service.getMarksArrayForLeaders(contentId); } else { Long sessionId = WebUtil.readLongParam(request, AssessmentConstants.ATTR_TOOL_SESSION_ID); results = service.getMarksArray(sessionId); } } - - JSONObject responseJSON = new JSONObject(); - if ( results != null ) - responseJSON.put("data", results); - else - responseJSON.put("data", new Float[0]); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + if (results != null) { + responseJSON.set("data", JsonUtil.readArray(results)); + } else { + responseJSON.set("data", JsonUtil.readArray(new Float[0])); + } + res.setContentType("application/json;charset=utf-8"); res.getWriter().write(responseJSON.toString()); return null; @@ -650,7 +653,7 @@ return null; } - + private ActionForward statistic(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { @@ -662,8 +665,8 @@ Long contentId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); Assessment assessment = service.getAssessmentByContentId(contentId); - if ( assessment != null ) { - if ( assessment.isUseSelectLeaderToolOuput() ) { + if (assessment != null) { + if (assessment.isUseSelectLeaderToolOuput()) { LeaderResultsDTO leaderDto = service.getLeaderResultsDTOForLeaders(contentId); sessionMap.put("leaderDto", leaderDto); } else { @@ -674,7 +677,6 @@ return mapping.findForward(AssessmentConstants.SUCCESS); } - // ************************************************************************************* // Private method // *************************************************************************************