Index: lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/OrgPasswordChangeAction.java =================================================================== diff -u -r9d983eac609d45a939706e34834cfed8c7249810 -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/OrgPasswordChangeAction.java (.../OrgPasswordChangeAction.java) (revision 9d983eac609d45a939706e34834cfed8c7249810) +++ lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/OrgPasswordChangeAction.java (.../OrgPasswordChangeAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -43,9 +43,6 @@ import org.apache.struts.action.ActionMapping; import org.apache.struts.action.DynaActionForm; import org.apache.struts.actions.DispatchAction; -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.admin.AdminConstants; import org.lamsfoundation.lams.admin.service.AdminServiceProxy; import org.lamsfoundation.lams.events.IEventNotificationService; @@ -56,12 +53,17 @@ import org.lamsfoundation.lams.usermanagement.dto.UserDTO; import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; import org.lamsfoundation.lams.util.HashUtil; +import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.util.ValidationUtil; import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.web.session.SessionManager; import org.lamsfoundation.lams.web.util.AttributeNames; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + public class OrgPasswordChangeAction extends DispatchAction { private static Logger log = Logger.getLogger(OrgPasswordChangeAction.class); @@ -91,7 +93,7 @@ } public ActionForward getGridUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { Integer organisationID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); String role = WebUtil.readStrParam(request, AttributeNames.PARAM_ROLE); @@ -130,35 +132,35 @@ } } - JSONObject resultJSON = new JSONObject(); + ObjectNode resultJSON = JsonNodeFactory.instance.objectNode(); resultJSON.put(AdminConstants.ELEMENT_PAGE, page); resultJSON.put(AdminConstants.ELEMENT_TOTAL, totalPages); resultJSON.put(AdminConstants.ELEMENT_RECORDS, totalUsers); - JSONArray rowsJSON = new JSONArray(); + ArrayNode rowsJSON = JsonNodeFactory.instance.arrayNode(); // build rows for grid for (UserDTO user : users) { - JSONObject rowJSON = new JSONObject(); + ObjectNode rowJSON = JsonNodeFactory.instance.objectNode(); rowJSON.put(AdminConstants.ELEMENT_ID, user.getUserID()); - JSONArray cellJSON = new JSONArray(); - cellJSON.put(user.getFirstName() + " " + user.getLastName()); - cellJSON.put(user.getLogin()); - cellJSON.put(user.getEmail()); + ArrayNode cellJSON = JsonNodeFactory.instance.arrayNode(); + cellJSON.add(user.getFirstName() + " " + user.getLastName()); + cellJSON.add(user.getLogin()); + cellJSON.add(user.getEmail()); - rowJSON.put(AdminConstants.ELEMENT_CELL, cellJSON); - rowsJSON.put(rowJSON); + rowJSON.set(AdminConstants.ELEMENT_CELL, cellJSON); + rowsJSON.add(rowJSON); } - resultJSON.put(AdminConstants.ELEMENT_ROWS, rowsJSON); + resultJSON.set(AdminConstants.ELEMENT_ROWS, rowsJSON); response.setContentType("application/json;charset=utf-8"); response.getWriter().print(resultJSON.toString()); return null; } public ActionForward changePassword(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { UserDTO userDTO = getUserDTO(); Integer currentUserId = userDTO.getUserID(); // security check @@ -180,9 +182,9 @@ // get data needed for each group if (isStaffChange) { String staffString = (String) passForm.get("excludedStaff"); - JSONArray excludedStaff = StringUtils.isBlank(staffString) ? null : new JSONArray(staffString); + ArrayNode excludedStaff = StringUtils.isBlank(staffString) ? null : JsonUtil.readArray(staffString); staffString = (String) passForm.get("includedStaff"); - JSONArray includedStaff = StringUtils.isBlank(staffString) ? null : new JSONArray(staffString); + ArrayNode includedStaff = StringUtils.isBlank(staffString) ? null : JsonUtil.readArray(staffString); String staffPass = (String) passForm.get("staffPass"); Collection users = getUsersByRole(organisationID, true); @@ -193,9 +195,11 @@ } if (isLearnerChange) { String learnersString = (String) passForm.get("excludedLearners"); - JSONArray excludedLearners = StringUtils.isBlank(learnersString) ? null : new JSONArray(learnersString); + ArrayNode excludedLearners = StringUtils.isBlank(learnersString) ? null + : JsonUtil.readArray(learnersString); learnersString = (String) passForm.get("includedLearners"); - JSONArray includedLearners = StringUtils.isBlank(learnersString) ? null : new JSONArray(learnersString); + ArrayNode includedLearners = StringUtils.isBlank(learnersString) ? null + : JsonUtil.readArray(learnersString); String learnerPass = (String) passForm.get("learnerPass"); Collection users = getUsersByRole(organisationID, false); @@ -218,8 +222,8 @@ messageService.getMessage("admin.org.password.change.email.body", new String[] { password }), false); } - private Set changePassword(String password, Collection users, JSONArray includedUsers, - JSONArray excludedUsers, boolean force) throws JSONException { + private Set changePassword(String password, Collection users, ArrayNode includedUsers, + ArrayNode excludedUsers, boolean force) { if (!ValidationUtil.isPasswordValueValid(password, password)) { // this should have been picked up by JS validator on the page! throw new InvalidParameterException("Password does not pass validation"); @@ -236,8 +240,8 @@ if (includedUsers == null) { boolean excluded = false; // skip excluded (unchecked on the page) users - for (int index = 0; index < excludedUsers.length(); index++) { - Integer excludedUserID = excludedUsers.getInt(index); + for (int index = 0; index < excludedUsers.size(); index++) { + Integer excludedUserID = excludedUsers.get(index).asInt(); if (user.getUserId().equals(excludedUserID)) { excluded = true; break; @@ -248,8 +252,8 @@ } } else { boolean included = false; - for (int index = 0; index < includedUsers.length(); index++) { - Integer includedUserID = includedUsers.getInt(index); + for (int index = 0; index < includedUsers.size(); index++) { + Integer includedUserID = includedUsers.get(index).asInt(); if (user.getUserId().equals(includedUserID)) { included = true; break; Index: lams_build/lib/lams/lams.jar =================================================================== diff -u -r79a5b84a312572845e14580f38b7193bdb9ae076 -r920d578377db9f50585f754c68a25e72da1d2c2f Binary files differ Index: lams_central/src/java/org/lamsfoundation/lams/authoring/ObjectExtractor.java =================================================================== diff -u -r146c434b9071ee5a83366cc892327193aa8b18b9 -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_central/src/java/org/lamsfoundation/lams/authoring/ObjectExtractor.java (.../ObjectExtractor.java) (revision 146c434b9071ee5a83366cc892327193aa8b18b9) +++ lams_central/src/java/org/lamsfoundation/lams/authoring/ObjectExtractor.java (.../ObjectExtractor.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -34,9 +34,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; -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.dao.IBaseDAO; import org.lamsfoundation.lams.learningdesign.Activity; import org.lamsfoundation.lams.learningdesign.ActivityEvaluation; @@ -97,6 +94,10 @@ import org.lamsfoundation.lams.util.FileUtil; import org.lamsfoundation.lams.util.JsonUtil; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Manpreet Minhas * @author Mailing Truong @@ -314,16 +315,16 @@ } @Override - public LearningDesign extractSaveLearningDesign(JSONObject ldJSON, LearningDesign existingLearningDesign, - WorkspaceFolder workspaceFolder, User user) throws ObjectExtractorException, ParseException, JSONException { + public LearningDesign extractSaveLearningDesign(ObjectNode ldJSON, LearningDesign existingLearningDesign, + WorkspaceFolder workspaceFolder, User user) throws ObjectExtractorException, ParseException { // if the learningDesign already exists, update it, otherwise create a // new one. learningDesign = existingLearningDesign != null ? existingLearningDesign : new LearningDesign(); // Check the copy type. Can only update it if it is COPY_TYPE_NONE (ie // authoring copy) - Integer copyTypeID = (Integer) JsonUtil.opt(ldJSON, AuthoringJsonTags.COPY_TYPE); + Integer copyTypeID = JsonUtil.optInt(ldJSON, AuthoringJsonTags.COPY_TYPE); if (copyTypeID == null) { copyTypeID = LearningDesign.COPY_TYPE_NONE; } @@ -339,15 +340,15 @@ learningDesign.setWorkspaceFolder(workspaceFolder); learningDesign.setUser(user); - String contentFolderID = (String) JsonUtil.opt(ldJSON, AuthoringJsonTags.CONTENT_FOLDER_ID); + String contentFolderID = JsonUtil.optString(ldJSON, AuthoringJsonTags.CONTENT_FOLDER_ID); if (contentFolderID == null) { contentFolderID = FileUtil.generateUniqueContentFolderID(); ldJSON.put(AuthoringJsonTags.CONTENT_FOLDER_ID, contentFolderID); } learningDesign.setContentFolderID(contentFolderID); if (existingLearningDesign == null) { - Integer originalUserID = (Integer) JsonUtil.opt(ldJSON, AuthoringJsonTags.ORIGINAL_USER_ID); + Integer originalUserID = JsonUtil.optInt(ldJSON, AuthoringJsonTags.ORIGINAL_USER_ID); if (originalUserID == null) { learningDesign.setOriginalUser(user); } else { @@ -375,24 +376,24 @@ initialiseToolSessionMap(learningDesign); // get the core learning design stuff - default to invalid - learningDesign.setValidDesign(JsonUtil.opt(ldJSON, AuthoringJsonTags.VALID_DESIGN, false)); - learningDesign.setLearningDesignUIID((Integer) JsonUtil.opt(ldJSON, AuthoringJsonTags.LEARNING_DESIGN_UIID)); - learningDesign.setDescription((String) JsonUtil.opt(ldJSON, AuthoringJsonTags.DESCRIPTION)); - learningDesign.setTitle((String) JsonUtil.opt(ldJSON, AuthoringJsonTags.TITLE)); - learningDesign.setMaxID((Integer) JsonUtil.opt(ldJSON, AuthoringJsonTags.MAX_ID)); - learningDesign.setReadOnly((Boolean) JsonUtil.opt(ldJSON, AuthoringJsonTags.READ_ONLY)); + learningDesign.setValidDesign(JsonUtil.optBoolean(ldJSON, AuthoringJsonTags.VALID_DESIGN, false)); + learningDesign.setLearningDesignUIID(JsonUtil.optInt(ldJSON, AuthoringJsonTags.LEARNING_DESIGN_UIID)); + learningDesign.setDescription(JsonUtil.optString(ldJSON, AuthoringJsonTags.DESCRIPTION)); + learningDesign.setTitle(JsonUtil.optString(ldJSON, AuthoringJsonTags.TITLE)); + learningDesign.setMaxID(JsonUtil.optInt(ldJSON, AuthoringJsonTags.MAX_ID)); + learningDesign.setReadOnly(JsonUtil.optBoolean(ldJSON, AuthoringJsonTags.READ_ONLY)); learningDesign.setDateReadOnly( - DateUtil.convertFromString((String) JsonUtil.opt(ldJSON, AuthoringJsonTags.DATE_READ_ONLY))); - learningDesign.setHelpText((String) JsonUtil.opt(ldJSON, AuthoringJsonTags.HELP_TEXT)); - String version = (String) JsonUtil.opt(ldJSON, AuthoringJsonTags.VERSION); + DateUtil.convertFromString(JsonUtil.optString(ldJSON, AuthoringJsonTags.DATE_READ_ONLY))); + learningDesign.setHelpText(JsonUtil.optString(ldJSON, AuthoringJsonTags.HELP_TEXT)); + String version = JsonUtil.optString(ldJSON, AuthoringJsonTags.VERSION); if (version == null) { version = Configuration.get(ConfigurationKeys.SERVER_VERSION_NUMBER); } - learningDesign.setDesignType((String) JsonUtil.opt(ldJSON, AuthoringJsonTags.DESIGN_TYPE)); + learningDesign.setDesignType(JsonUtil.optString(ldJSON, AuthoringJsonTags.DESIGN_TYPE)); learningDesign.setVersion(version); learningDesign.setDuration(JsonUtil.optLong(ldJSON, AuthoringJsonTags.DURATION)); - mode = (Integer) JsonUtil.opt(ldJSON, AuthoringJsonTags.SAVE_MODE); + mode = JsonUtil.optInt(ldJSON, AuthoringJsonTags.SAVE_MODE); // Set creation date and modification date based on the server timezone, // not the client. @@ -406,7 +407,7 @@ License license = licenseDAO.getLicenseByID(licenseID); learningDesign.setLicense(license); } - learningDesign.setLicenseText((String) JsonUtil.opt(ldJSON, AuthoringJsonTags.LICENSE_TEXT)); + learningDesign.setLicenseText(JsonUtil.optString(ldJSON, AuthoringJsonTags.LICENSE_TEXT)); Long originalLearningDesignID = JsonUtil.optLong(ldJSON, AuthoringJsonTags.ORIGINAL_DESIGN_ID); if (originalLearningDesignID != null) { @@ -417,13 +418,12 @@ learningDesignDAO.insertOrUpdate(learningDesign); // now process the "parts" of the learning design - parseGroupings((JSONArray) JsonUtil.opt(ldJSON, AuthoringJsonTags.GROUPINGS)); - parseActivities((JSONArray) JsonUtil.opt(ldJSON, AuthoringJsonTags.ACTIVITIES)); - parseActivitiesToMatchUpParentandInputActivities( - (JSONArray) JsonUtil.opt(ldJSON, AuthoringJsonTags.ACTIVITIES)); - parseTransitions((JSONArray) JsonUtil.opt(ldJSON, AuthoringJsonTags.TRANSITIONS)); - parseBranchMappings((JSONArray) JsonUtil.opt(ldJSON, AuthoringJsonTags.BRANCH_MAPPINGS)); - parseAnnotations((JSONArray) JsonUtil.opt(ldJSON, AuthoringJsonTags.ANNOTATIONS)); + parseGroupings(JsonUtil.optArray(ldJSON, AuthoringJsonTags.GROUPINGS)); + parseActivities(JsonUtil.optArray(ldJSON, AuthoringJsonTags.ACTIVITIES)); + parseActivitiesToMatchUpParentandInputActivities(JsonUtil.optArray(ldJSON, AuthoringJsonTags.ACTIVITIES)); + parseTransitions(JsonUtil.optArray(ldJSON, AuthoringJsonTags.TRANSITIONS)); + parseBranchMappings(JsonUtil.optArray(ldJSON, AuthoringJsonTags.BRANCH_MAPPINGS)); + parseAnnotations(JsonUtil.optArray(ldJSON, AuthoringJsonTags.ANNOTATIONS)); progressDefaultChildActivities(); @@ -586,25 +586,24 @@ } } - private void parseGroupings(JSONArray groupingsList) throws JSONException { + private void parseGroupings(ArrayNode groupingsList) { // iterate through the list of groupings objects // each object should contain information groupingUUID, groupingID, // groupingTypeID if (groupingsList != null) { - for (int groupingIndex = 0; groupingIndex < groupingsList.length(); groupingIndex++) { - JSONObject groupingDetails = groupingsList.getJSONObject(groupingIndex); + for (JsonNode groupingDetails : groupingsList) { if (groupingDetails != null) { - Grouping grouping = extractGroupingObject(groupingDetails); + Grouping grouping = extractGroupingObject((ObjectNode) groupingDetails); groupingDAO.insertOrUpdate(grouping); groupings.put(grouping.getGroupingUIID(), grouping); } } } } - public Grouping extractGroupingObject(JSONObject groupingDetails) throws JSONException { - Integer groupingUIID = (Integer) JsonUtil.opt(groupingDetails, "groupingUIID"); - Integer groupingTypeID = (Integer) JsonUtil.opt(groupingDetails, "groupingTypeID"); + public Grouping extractGroupingObject(ObjectNode groupingDetails) { + Integer groupingUIID = JsonUtil.optInt(groupingDetails, "groupingUIID"); + Integer groupingTypeID = JsonUtil.optInt(groupingDetails, "groupingTypeID"); Grouping grouping = groupings.get(groupingUIID); // check that the grouping type is still okay - if it is we keep the @@ -637,15 +636,14 @@ createLessonClass((LessonClass) grouping, groupingDetails); } - grouping.setMaxNumberOfGroups((Integer) JsonUtil.opt(groupingDetails, "maxNumberOfGroups")); + grouping.setMaxNumberOfGroups(JsonUtil.optInt(groupingDetails, "maxNumberOfGroups")); Set groupsToDelete = new HashSet<>(grouping.getGroups()); - JSONArray groupsList = (JSONArray) JsonUtil.opt(groupingDetails, "groups"); + ArrayNode groupsList = JsonUtil.optArray(groupingDetails, "groups"); if (groupsList != null) { - for (int groupIndex = 0; groupIndex < groupsList.length(); groupIndex++) { - JSONObject groupDetails = groupsList.getJSONObject(groupIndex); - Group group = extractGroupObject(groupDetails, grouping); + for (JsonNode groupDetails : groupsList) { + Group group = extractGroupObject((ObjectNode) groupDetails, grouping); groups.put(group.getGroupUIID(), group); groupsToDelete.remove(group); } @@ -669,10 +667,10 @@ return grouping; } - private Group extractGroupObject(JSONObject groupDetails, Grouping grouping) throws JSONException { + private Group extractGroupObject(ObjectNode groupDetails, Grouping grouping) { Group group = null; - Integer groupUIID = (Integer) JsonUtil.opt(groupDetails, AuthoringJsonTags.GROUP_UIID); + Integer groupUIID = JsonUtil.optInt(groupDetails, AuthoringJsonTags.GROUP_UIID); Long groupID = JsonUtil.optLong(groupDetails, AuthoringJsonTags.GROUP_ID); // Does it exist already? If the group was created at runtime, there @@ -704,23 +702,23 @@ grouping.getGroups().add(group); } - group.setGroupName((String) JsonUtil.opt(groupDetails, AuthoringJsonTags.GROUP_NAME)); + group.setGroupName(JsonUtil.optString(groupDetails, AuthoringJsonTags.GROUP_NAME)); group.setGrouping(grouping); group.setGroupUIID(groupUIID); - group.setOrderId(JsonUtil.opt(groupDetails, AuthoringJsonTags.ORDER_ID, 0)); + group.setOrderId(JsonUtil.optInt(groupDetails, AuthoringJsonTags.ORDER_ID, 0)); return group; } - private void createRandomGrouping(RandomGrouping randomGrouping, JSONObject groupingDetails) throws JSONException { + private void createRandomGrouping(RandomGrouping randomGrouping, ObjectNode groupingDetails) { // the two settings are mutually exclusive. Authoring takes care of this, // but we'll code it here too just to make sure. - Integer numLearnersPerGroup = (Integer) JsonUtil.opt(groupingDetails, AuthoringJsonTags.LEARNERS_PER_GROUP); + Integer numLearnersPerGroup = JsonUtil.optInt(groupingDetails, AuthoringJsonTags.LEARNERS_PER_GROUP); if ((numLearnersPerGroup != null) && (numLearnersPerGroup.intValue() > 0)) { randomGrouping.setLearnersPerGroup(numLearnersPerGroup); randomGrouping.setNumberOfGroups(null); } else { - Integer numGroups = (Integer) JsonUtil.opt(groupingDetails, AuthoringJsonTags.NUMBER_OF_GROUPS); + Integer numGroups = JsonUtil.optInt(groupingDetails, AuthoringJsonTags.NUMBER_OF_GROUPS); if ((numGroups != null) && (numGroups.intValue() > 0)) { randomGrouping.setNumberOfGroups(numGroups); } else { @@ -730,21 +728,19 @@ } } - private void createChosenGrouping(ChosenGrouping chosenGrouping, JSONObject groupingDetails) { + private void createChosenGrouping(ChosenGrouping chosenGrouping, ObjectNode groupingDetails) { // no extra properties as yet } - private void parseActivities(JSONArray activitiesList) throws ObjectExtractorException, JSONException { - + private void parseActivities(ArrayNode activitiesList) throws ObjectExtractorException { if (activitiesList != null) { - for (int activityIndex = 0; activityIndex < activitiesList.length(); activityIndex++) { - JSONObject activityDetails = activitiesList.getJSONObject(activityIndex); - Activity activity = extractActivityObject(activityDetails); + for (JsonNode activityDetails : activitiesList) { + Activity activity = extractActivityObject((ObjectNode) activityDetails); activityDAO.insertOrUpdate(activity); // if its a tool activity, extract evaluation details if (activity.isToolActivity()) { - extractEvaluationObject(activityDetails, (ToolActivity) activity); + extractEvaluationObject((ObjectNode) activityDetails, (ToolActivity) activity); } newActivityMap.put(activity.getActivityUIID(), activity); @@ -767,9 +763,9 @@ learningDesignDAO.insertOrUpdate(learningDesign); } - private void extractEvaluationObject(JSONObject activityDetails, ToolActivity toolActivity) - throws ObjectExtractorException, JSONException { - String toolOutputDefinition = (String) JsonUtil.opt(activityDetails, AuthoringJsonTags.TOOL_OUTPUT_DEFINITION); + private void extractEvaluationObject(ObjectNode activityDetails, ToolActivity toolActivity) + throws ObjectExtractorException { + String toolOutputDefinition = JsonUtil.optString(activityDetails, AuthoringJsonTags.TOOL_OUTPUT_DEFINITION); if (StringUtils.isNotBlank(toolOutputDefinition)) { ActivityEvaluation evaluation = toolActivity.getEvaluation(); if (evaluation == null) { @@ -778,7 +774,7 @@ } evaluation.setToolOutputDefinition(toolOutputDefinition); - String weight = (String) JsonUtil.opt(activityDetails, AuthoringJsonTags.TOOL_OUTPUT_WEIGHT); + String weight = JsonUtil.optString(activityDetails, AuthoringJsonTags.TOOL_OUTPUT_WEIGHT); if (StringUtils.isBlank(weight)) { evaluation.setWeight(null); } else { @@ -792,13 +788,12 @@ activityDAO.update(toolActivity); } - private void parseCompetences(JSONArray competenceList) throws ObjectExtractorException, JSONException { + private void parseCompetences(ArrayNode competenceList) throws ObjectExtractorException { Set existingCompetences = learningDesign.getCompetences(); if (competenceList != null) { - for (int competenceIndex = 0; competenceIndex < competenceList.length(); competenceIndex++) { - JSONObject competeneJSON = competenceList.getJSONObject(competenceIndex); - String title = competeneJSON.getString(AuthoringJsonTags.TITLE); - String description = competeneJSON.getString(AuthoringJsonTags.DESCRIPTION); + for (JsonNode competenceJSON : competenceList) { + String title = JsonUtil.optString(competenceJSON, AuthoringJsonTags.TITLE); + String description = JsonUtil.optString(competenceJSON, AuthoringJsonTags.DESCRIPTION); if (getComptenceFromSet(existingCompetences, title) != null) { Competence updateCompetence = getComptenceFromSet(existingCompetences, title); @@ -817,12 +812,12 @@ // that dont exist in the new list. Set removeCompetences = new HashSet<>(); if (existingCompetences != null) { - if ((competenceList != null) && (competenceList.length() > 0)) { + if ((competenceList != null) && (competenceList.size() > 0)) { for (Competence existingCompetence : existingCompetences) { boolean remove = true; - for (int competenceIndex = 0; competenceIndex < competenceList.length(); competenceIndex++) { - if (existingCompetence.getTitle().equals( - competenceList.getJSONObject(competenceIndex).getString(AuthoringJsonTags.TITLE))) { + for (JsonNode competenceJSON : competenceList) { + if (existingCompetence.getTitle() + .equals(JsonUtil.optString(competenceJSON, AuthoringJsonTags.TITLE))) { remove = false; break; } @@ -841,7 +836,7 @@ } } - private void parseAnnotations(JSONArray annotationList) throws ObjectExtractorException, JSONException { + private void parseAnnotations(ArrayNode annotationList) throws ObjectExtractorException { if (annotationList == null) { return; } @@ -853,14 +848,13 @@ } Set updatedAnnotations = new HashSet<>(); - for (int annotationIndex = 0; annotationIndex < annotationList.length(); annotationIndex++) { - JSONObject annotationJSON = annotationList.getJSONObject(annotationIndex); + for (JsonNode annotationJSON : annotationList) { boolean found = false; LearningDesignAnnotation annotation = null; for (LearningDesignAnnotation existingAnnotation : existingAnnotations) { if (existingAnnotation.getAnnotationUIID() - .equals(annotationJSON.getInt(AuthoringJsonTags.ANNOTATION_UIID))) { + .equals(JsonUtil.optInt(annotationJSON, AuthoringJsonTags.ANNOTATION_UIID))) { annotation = existingAnnotation; found = true; break; @@ -871,14 +865,14 @@ annotation = new LearningDesignAnnotation(); } annotation.setLearningDesignId(learningDesign.getLearningDesignId()); - annotation.setAnnotationUIID(annotationJSON.getInt(AuthoringJsonTags.ANNOTATION_UIID)); - annotation.setTitle((String) JsonUtil.opt(annotationJSON, AuthoringJsonTags.TITLE)); - annotation.setXcoord((Integer) JsonUtil.opt(annotationJSON, AuthoringJsonTags.XCOORD)); - annotation.setYcoord((Integer) JsonUtil.opt(annotationJSON, AuthoringJsonTags.YCOORD)); - annotation.setEndXcoord((Integer) JsonUtil.opt(annotationJSON, AuthoringJsonTags.END_XCOORD)); - annotation.setEndYcoord((Integer) JsonUtil.opt(annotationJSON, AuthoringJsonTags.END_YCOORD)); - annotation.setColor((String) JsonUtil.opt(annotationJSON, AuthoringJsonTags.COLOR)); - String size = (String) JsonUtil.opt(annotationJSON, AuthoringJsonTags.SIZE); + annotation.setAnnotationUIID(JsonUtil.optInt(annotationJSON, AuthoringJsonTags.ANNOTATION_UIID)); + annotation.setTitle(JsonUtil.optString(annotationJSON, AuthoringJsonTags.TITLE)); + annotation.setXcoord(JsonUtil.optInt(annotationJSON, AuthoringJsonTags.XCOORD)); + annotation.setYcoord(JsonUtil.optInt(annotationJSON, AuthoringJsonTags.YCOORD)); + annotation.setEndXcoord(JsonUtil.optInt(annotationJSON, AuthoringJsonTags.END_XCOORD)); + annotation.setEndYcoord(JsonUtil.optInt(annotationJSON, AuthoringJsonTags.END_YCOORD)); + annotation.setColor(JsonUtil.optString(annotationJSON, AuthoringJsonTags.COLOR)); + String size = JsonUtil.optString(annotationJSON, AuthoringJsonTags.SIZE); if (size != null) { annotation.setSize(Short.valueOf(size)); } @@ -908,17 +902,15 @@ return null; } - private void parseActivitiesToMatchUpParentandInputActivities(JSONArray activitiesList) - throws ObjectExtractorException, JSONException { + private void parseActivitiesToMatchUpParentandInputActivities(ArrayNode activitiesList) + throws ObjectExtractorException { if (activitiesList != null) { - for (int activityIndex = 0; activityIndex < activitiesList.length(); activityIndex++) { - JSONObject activityDetails = activitiesList.getJSONObject(activityIndex); - - Integer activityUUID = activityDetails.getInt(AuthoringJsonTags.ACTIVITY_UIID); + for (JsonNode activityDetails : activitiesList) { + Integer activityUUID = JsonUtil.optInt(activityDetails, AuthoringJsonTags.ACTIVITY_UIID); Activity existingActivity = newActivityMap.get(activityUUID); // match up activity to parent based on UIID - Integer parentUIID = (Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.PARENT_UIID); + Integer parentUIID = JsonUtil.optInt(activityDetails, AuthoringJsonTags.PARENT_UIID); if (parentUIID != null) { Activity parentActivity = newActivityMap.get(parentUIID); @@ -944,7 +936,7 @@ // match up activity to input activities based on UIID. At // present there will be only one input activity existingActivity.getInputActivities().clear(); - Integer inputActivityUIID = (Integer) JsonUtil.opt(activityDetails, + Integer inputActivityUIID = JsonUtil.optInt(activityDetails, AuthoringJsonTags.INPUT_TOOL_ACTIVITY_UIID); if (inputActivityUIID != null) { Activity inputActivity = newActivityMap.get(inputActivityUIID); @@ -961,14 +953,13 @@ } } - private void parseTransitions(JSONArray transitionsList) throws JSONException { + private void parseTransitions(ArrayNode transitionsList) { HashMap newMap = new HashMap<>(); if (transitionsList != null) { - for (int transitionIndex = 0; transitionIndex < transitionsList.length(); transitionIndex++) { - JSONObject transitionDetails = transitionsList.getJSONObject(transitionIndex); - Transition transition = extractTransitionObject(transitionDetails); + for (JsonNode transitionDetails : transitionsList) { + Transition transition = extractTransitionObject((ObjectNode) transitionDetails); // Check if transition actually exists. extractTransitionObject // returns null // if neither the to/from activity exists. @@ -1003,11 +994,11 @@ } - public Activity extractActivityObject(JSONObject activityDetails) throws ObjectExtractorException, JSONException { + public Activity extractActivityObject(ObjectNode activityDetails) throws ObjectExtractorException { // it is assumed that the activityUUID will always be sent by Authoring - Integer activityUIID = (Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.ACTIVITY_UIID); - Integer activityTypeID = (Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.ACTIVITY_TYPE_ID); + Integer activityUIID = JsonUtil.optInt(activityDetails, AuthoringJsonTags.ACTIVITY_UIID); + Integer activityTypeID = JsonUtil.optInt(activityDetails, AuthoringJsonTags.ACTIVITY_TYPE_ID); Activity activity = null; // get the activity with the particular activity uuid, if null, then new @@ -1026,13 +1017,13 @@ activity.setActivityTypeId(activityTypeID); activity.setActivityUIID(activityUIID); - activity.setDescription((String) JsonUtil.opt(activityDetails, AuthoringJsonTags.DESCRIPTION)); - activity.setTitle((String) JsonUtil.opt(activityDetails, AuthoringJsonTags.ACTIVITY_TITLE)); + activity.setDescription(JsonUtil.optString(activityDetails, AuthoringJsonTags.DESCRIPTION)); + activity.setTitle(JsonUtil.optString(activityDetails, AuthoringJsonTags.ACTIVITY_TITLE)); - activity.setXcoord(getCoord(activityDetails, AuthoringJsonTags.XCOORD)); - activity.setYcoord(getCoord(activityDetails, AuthoringJsonTags.YCOORD)); + activity.setXcoord(JsonUtil.optInt(activityDetails, AuthoringJsonTags.XCOORD, ObjectExtractor.DEFAULT_COORD)); + activity.setYcoord(JsonUtil.optInt(activityDetails, AuthoringJsonTags.YCOORD, ObjectExtractor.DEFAULT_COORD)); - Integer groupingUIID = (Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.GROUPING_UIID); + Integer groupingUIID = JsonUtil.optInt(activityDetails, AuthoringJsonTags.GROUPING_UIID); if (groupingUIID == null) { clearGrouping(activity); @@ -1048,7 +1039,7 @@ } - activity.setOrderId((Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.ORDER_ID)); + activity.setOrderId(JsonUtil.optInt(activityDetails, AuthoringJsonTags.ORDER_ID)); activity.setLearningDesign(learningDesign); @@ -1064,22 +1055,15 @@ activity.setCreateDateTime(modificationDate); } - activity.setActivityCategoryID((Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.ACTIVITY_CATEGORY_ID)); - activity.setLibraryActivityUiImage((String) JsonUtil.opt(activityDetails, AuthoringJsonTags.LIBRARY_IMAGE)); - activity.setGroupingSupportType( - (Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.GROUPING_SUPPORT_TYPE)); - activity.setStopAfterActivity(JsonUtil.opt(activityDetails, AuthoringJsonTags.STOP_AFTER_ACTIVITY, false)); + activity.setActivityCategoryID(JsonUtil.optInt(activityDetails, AuthoringJsonTags.ACTIVITY_CATEGORY_ID)); + activity.setLibraryActivityUiImage(JsonUtil.optString(activityDetails, AuthoringJsonTags.LIBRARY_IMAGE)); + activity.setGroupingSupportType(JsonUtil.optInt(activityDetails, AuthoringJsonTags.GROUPING_SUPPORT_TYPE)); + activity.setStopAfterActivity( + JsonUtil.optBoolean(activityDetails, AuthoringJsonTags.STOP_AFTER_ACTIVITY, false)); return activity; } - private Integer getCoord(JSONObject details, String tag) throws JSONException { - // the coordinate can be Integer or Double in JSON, need to be ready for any - Number number = (Number) JsonUtil.opt(details, tag); - Integer coord = number == null ? null : number.intValue(); - return (coord == null) || (coord >= 0) ? coord : ObjectExtractor.DEFAULT_COORD; - } - private void clearGrouping(Activity activity) { activity.setGrouping(null); activity.setGroupingUIID(null); @@ -1092,8 +1076,7 @@ activity.setApplyGrouping(true); } - private void processActivityType(Activity activity, JSONObject activityDetails) - throws ObjectExtractorException, JSONException { + private void processActivityType(Activity activity, ObjectNode activityDetails) throws ObjectExtractorException { if (activity.isGroupingActivity()) { buildGroupingActivity((GroupingActivity) activity, activityDetails); } else if (activity.isToolActivity()) { @@ -1105,17 +1088,16 @@ } } - private void buildComplexActivity(ComplexActivity activity, JSONObject activityDetails) - throws ObjectExtractorException, JSONException { + private void buildComplexActivity(ComplexActivity activity, ObjectNode activityDetails) + throws ObjectExtractorException { // clear all the children - will be built up again by // parseActivitiesToMatchUpParentActivityByParentUIID // we don't use all-delete-orphan on the activities relationship so we // can do this clear. activity.getActivities().clear(); activity.setDefaultActivity(null); - Integer defaultActivityMapUIID = (Integer) JsonUtil.opt(activityDetails, - AuthoringJsonTags.DEFAULT_ACTIVITY_UIID); + Integer defaultActivityMapUIID = JsonUtil.optInt(activityDetails, AuthoringJsonTags.DEFAULT_ACTIVITY_UIID); if (defaultActivityMapUIID != null) { defaultActivityMap.put(defaultActivityMapUIID, activity); } @@ -1134,17 +1116,16 @@ } } - private void buildFloatingActivity(FloatingActivity floatingActivity, JSONObject activityDetails) - throws ObjectExtractorException, JSONException { - floatingActivity - .setMaxNumberOfActivities((Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.MAX_ACTIVITIES)); + private void buildFloatingActivity(FloatingActivity floatingActivity, ObjectNode activityDetails) + throws ObjectExtractorException { + floatingActivity.setMaxNumberOfActivities(JsonUtil.optInt(activityDetails, AuthoringJsonTags.MAX_ACTIVITIES)); SystemTool systemTool = getSystemTool(SystemTool.FLOATING_ACTIVITIES); floatingActivity.setSystemTool(systemTool); } - private void buildBranchingActivity(BranchingActivity branchingActivity, JSONObject activityDetails) - throws ObjectExtractorException, JSONException { + private void buildBranchingActivity(BranchingActivity branchingActivity, ObjectNode activityDetails) + throws ObjectExtractorException { if (branchingActivity.isChosenBranchingActivity()) { branchingActivity.setSystemTool(getSystemTool(SystemTool.TEACHER_CHOSEN_BRANCHING)); } else if (branchingActivity.isGroupBranchingActivity()) { @@ -1153,18 +1134,22 @@ branchingActivity.setSystemTool(getSystemTool(SystemTool.TOOL_BASED_BRANCHING)); } - branchingActivity.setStartXcoord(getCoord(activityDetails, AuthoringJsonTags.START_XCOORD)); - branchingActivity.setStartYcoord(getCoord(activityDetails, AuthoringJsonTags.START_YCOORD)); - branchingActivity.setEndXcoord(getCoord(activityDetails, AuthoringJsonTags.END_XCOORD)); - branchingActivity.setEndYcoord(getCoord(activityDetails, AuthoringJsonTags.END_YCOORD)); + branchingActivity.setStartXcoord( + JsonUtil.optInt(activityDetails, AuthoringJsonTags.START_XCOORD, ObjectExtractor.DEFAULT_COORD)); + branchingActivity.setStartYcoord( + JsonUtil.optInt(activityDetails, AuthoringJsonTags.START_YCOORD, ObjectExtractor.DEFAULT_COORD)); + branchingActivity.setEndXcoord( + JsonUtil.optInt(activityDetails, AuthoringJsonTags.END_XCOORD, ObjectExtractor.DEFAULT_COORD)); + branchingActivity.setEndYcoord( + JsonUtil.optInt(activityDetails, AuthoringJsonTags.END_YCOORD, ObjectExtractor.DEFAULT_COORD)); } - private void buildGroupingActivity(GroupingActivity groupingActivity, JSONObject activityDetails) - throws ObjectExtractorException, JSONException { + private void buildGroupingActivity(GroupingActivity groupingActivity, ObjectNode activityDetails) + throws ObjectExtractorException { /** * read the createGroupingUUID, get the Grouping Object, and set CreateGrouping to that object */ - Integer createGroupingUIID = (Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.CREATE_GROUPING_UIID); + Integer createGroupingUIID = JsonUtil.optInt(activityDetails, AuthoringJsonTags.CREATE_GROUPING_UIID); Grouping grouping = groupings.get(createGroupingUIID); if (grouping != null) { groupingActivity.setCreateGrouping(grouping); @@ -1175,22 +1160,24 @@ groupingActivity.setSystemTool(systemTool); } - private void buildOptionsActivity(OptionsActivity optionsActivity, JSONObject activityDetails) - throws JSONException { - optionsActivity.setMaxNumberOfOptions((Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.MAX_OPTIONS)); - optionsActivity.setMinNumberOfOptions((Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.MIN_OPTIONS)); + private void buildOptionsActivity(OptionsActivity optionsActivity, ObjectNode activityDetails) { + optionsActivity.setMaxNumberOfOptions(JsonUtil.optInt(activityDetails, AuthoringJsonTags.MAX_OPTIONS)); + optionsActivity.setMinNumberOfOptions(JsonUtil.optInt(activityDetails, AuthoringJsonTags.MIN_OPTIONS)); optionsActivity - .setOptionsInstructions((String) JsonUtil.opt(activityDetails, AuthoringJsonTags.OPTIONS_INSTRUCTIONS)); + .setOptionsInstructions(JsonUtil.optString(activityDetails, AuthoringJsonTags.OPTIONS_INSTRUCTIONS)); } private void buildOptionsWithSequencesActivity(OptionsWithSequencesActivity optionsActivity, - JSONObject activityDetails) throws JSONException { + ObjectNode activityDetails) { buildOptionsActivity(optionsActivity, activityDetails); - - optionsActivity.setStartXcoord(getCoord(activityDetails, AuthoringJsonTags.START_XCOORD)); - optionsActivity.setStartYcoord(getCoord(activityDetails, AuthoringJsonTags.START_YCOORD)); - optionsActivity.setEndXcoord(getCoord(activityDetails, AuthoringJsonTags.END_XCOORD)); - optionsActivity.setEndYcoord(getCoord(activityDetails, AuthoringJsonTags.END_YCOORD)); + optionsActivity.setStartXcoord( + JsonUtil.optInt(activityDetails, AuthoringJsonTags.START_XCOORD, ObjectExtractor.DEFAULT_COORD)); + optionsActivity.setStartYcoord( + JsonUtil.optInt(activityDetails, AuthoringJsonTags.START_YCOORD, ObjectExtractor.DEFAULT_COORD)); + optionsActivity.setEndXcoord( + JsonUtil.optInt(activityDetails, AuthoringJsonTags.END_XCOORD, ObjectExtractor.DEFAULT_COORD)); + optionsActivity.setEndYcoord( + JsonUtil.optInt(activityDetails, AuthoringJsonTags.END_YCOORD, ObjectExtractor.DEFAULT_COORD)); } private void buildParallelActivity(ParallelActivity activity) { @@ -1200,7 +1187,7 @@ activity.setSystemTool(getSystemTool(SystemTool.SEQUENCE)); } - private void buildToolActivity(ToolActivity toolActivity, JSONObject activityDetails) throws JSONException { + private void buildToolActivity(ToolActivity toolActivity, ObjectNode activityDetails) { Tool tool = toolDAO.getToolByID(JsonUtil.optLong(activityDetails, AuthoringJsonTags.TOOL_ID)); toolActivity.setTool(tool); @@ -1217,7 +1204,7 @@ toolActivity.setToolContentId(toolContentId); } - private void buildGateActivity(Object activity, JSONObject activityDetails) throws JSONException { + private void buildGateActivity(Object activity, ObjectNode activityDetails) { if (activity instanceof SynchGateActivity) { buildSynchGateActivity((SynchGateActivity) activity); } else if (activity instanceof PermissionGateActivity) { @@ -1230,9 +1217,7 @@ buildScheduleGateActivity((ScheduleGateActivity) activity, activityDetails); } GateActivity gateActivity = (GateActivity) activity; - gateActivity.setGateActivityLevelId( - (Integer) JsonUtil.opt(activityDetails, AuthoringJsonTags.GATE_ACTIVITY_LEVEL_ID)); - + gateActivity.setGateActivityLevelId(JsonUtil.optInt(activityDetails, AuthoringJsonTags.GATE_ACTIVITY_LEVEL_ID)); } private void buildSynchGateActivity(SynchGateActivity activity) { @@ -1247,17 +1232,16 @@ activity.setSystemTool(getSystemTool(SystemTool.SYSTEM_GATE)); } - private void buildScheduleGateActivity(ScheduleGateActivity activity, JSONObject activityDetails) - throws JSONException { + private void buildScheduleGateActivity(ScheduleGateActivity activity, ObjectNode activityDetails) { activity.setGateStartTimeOffset(JsonUtil.optLong(activityDetails, AuthoringJsonTags.GATE_START_OFFSET)); activity.setGateEndTimeOffset(JsonUtil.optLong(activityDetails, AuthoringJsonTags.GATE_END_OFFSET)); activity.setGateActivityCompletionBased( - (Boolean) JsonUtil.opt(activityDetails, AuthoringJsonTags.GATE_ACTIVITY_COMPLETION_BASED)); + JsonUtil.optBoolean(activityDetails, AuthoringJsonTags.GATE_ACTIVITY_COMPLETION_BASED)); SystemTool systemTool = getSystemTool(SystemTool.SCHEDULE_GATE); activity.setSystemTool(systemTool); } - private void createLessonClass(LessonClass lessonClass, JSONObject groupingDetails) throws JSONException { + private void createLessonClass(LessonClass lessonClass, ObjectNode groupingDetails) { Long groupId = JsonUtil.optLong(groupingDetails, AuthoringJsonTags.STAFF_GROUP_ID); if (groupId != null) { Group group = groupDAO.getGroupById(groupId); @@ -1267,13 +1251,12 @@ } } - private Transition extractTransitionObject(JSONObject transitionDetails) throws JSONException { + private Transition extractTransitionObject(ObjectNode transitionDetails) { + Integer transitionUUID = JsonUtil.optInt(transitionDetails, AuthoringJsonTags.TRANSITION_UIID); + Integer toUIID = JsonUtil.optInt(transitionDetails, AuthoringJsonTags.TO_ACTIVITY_UIID); + Integer fromUIID = JsonUtil.optInt(transitionDetails, AuthoringJsonTags.FROM_ACTIVITY_UIID); + Integer transitionType = JsonUtil.optInt(transitionDetails, AuthoringJsonTags.TRANSITION_TYPE); - Integer transitionUUID = transitionDetails.getInt(AuthoringJsonTags.TRANSITION_UIID); - Integer toUIID = transitionDetails.getInt(AuthoringJsonTags.TO_ACTIVITY_UIID); - Integer fromUIID = transitionDetails.getInt(AuthoringJsonTags.FROM_ACTIVITY_UIID); - Integer transitionType = transitionDetails.getInt(AuthoringJsonTags.TRANSITION_TYPE); - Transition transition = null; Transition existingTransition = findTransition(transitionUUID, toUIID, fromUIID, transitionType); @@ -1319,8 +1302,8 @@ transition.setFromUIID(null); } - transition.setDescription((String) JsonUtil.opt(transitionDetails, AuthoringJsonTags.DESCRIPTION)); - transition.setTitle((String) JsonUtil.opt(transitionDetails, AuthoringJsonTags.TITLE)); + transition.setDescription(JsonUtil.optString(transitionDetails, AuthoringJsonTags.DESCRIPTION)); + transition.setTitle(JsonUtil.optString(transitionDetails, AuthoringJsonTags.TITLE)); // Set creation date based on the server timezone, not the client. if (transition.getCreateDateTime() == null) { @@ -1390,10 +1373,10 @@ return mode; } - private void parseBranchMappings(JSONArray branchMappingsList) throws JSONException, ObjectExtractorException { + private void parseBranchMappings(ArrayNode branchMappingsList) throws ObjectExtractorException { if (branchMappingsList != null) { - for (int branchMappingIndex = 0; branchMappingIndex < branchMappingsList.length(); branchMappingIndex++) { - extractBranchActivityEntry(branchMappingsList.getJSONObject(branchMappingIndex)); + for (JsonNode branchMappingJSON : branchMappingsList) { + extractBranchActivityEntry((ObjectNode) branchMappingJSON); } } @@ -1421,20 +1404,19 @@ } } - private BranchActivityEntry extractBranchActivityEntry(JSONObject details) - throws JSONException, ObjectExtractorException { + private BranchActivityEntry extractBranchActivityEntry(ObjectNode details) throws ObjectExtractorException { Long entryId = JsonUtil.optLong(details, AuthoringJsonTags.BRANCH_ACTIVITY_ENTRY_ID); - Integer entryUIID = details.getInt(AuthoringJsonTags.BRANCH_ACTIVITY_ENTRY_UIID); + Integer entryUIID = JsonUtil.optInt(details, AuthoringJsonTags.BRANCH_ACTIVITY_ENTRY_UIID); - Integer sequenceActivityUIID = (Integer) JsonUtil.opt(details, AuthoringJsonTags.BRANCH_SEQUENCE_ACTIVITY_UIID); - Boolean gateOpenWhenConditionMet = (Boolean) JsonUtil.opt(details, + Integer sequenceActivityUIID = JsonUtil.optInt(details, AuthoringJsonTags.BRANCH_SEQUENCE_ACTIVITY_UIID); + Boolean gateOpenWhenConditionMet = JsonUtil.optBoolean(details, AuthoringJsonTags.BRANCH_GATE_OPENS_WHEN_CONDITION_MET); Integer branchingActivityUIID = null; if (gateOpenWhenConditionMet != null) { - branchingActivityUIID = details.getInt(AuthoringJsonTags.BRANCH_GATE_ACTIVITY_UIID); + branchingActivityUIID = JsonUtil.optInt(details, AuthoringJsonTags.BRANCH_GATE_ACTIVITY_UIID); } else { - branchingActivityUIID = details.getInt(AuthoringJsonTags.BRANCH_ACTIVITY_UIID); + branchingActivityUIID = JsonUtil.optInt(details, AuthoringJsonTags.BRANCH_ACTIVITY_UIID); } Activity branchingActivity = newActivityMap.get(branchingActivityUIID); @@ -1505,9 +1487,10 @@ // (which is used for doing deletions later). oldbranchActivityEntryList.remove(entry); - BranchCondition condition = extractCondition(details.optJSONObject(AuthoringJsonTags.BRANCH_CONDITION), entry); + BranchCondition condition = extractCondition(JsonUtil.optObject(details, AuthoringJsonTags.BRANCH_CONDITION), + entry); - Integer groupUIID = (Integer) JsonUtil.opt(details, AuthoringJsonTags.GROUP_UIID); + Integer groupUIID = JsonUtil.optInt(details, AuthoringJsonTags.GROUP_UIID); Group group = null; if (groupUIID != null) { group = groups.get(groupUIID); @@ -1572,8 +1555,7 @@ return entry; } - private BranchCondition extractCondition(JSONObject conditionDetails, BranchActivityEntry entry) - throws JSONException { + private BranchCondition extractCondition(ObjectNode conditionDetails, BranchActivityEntry entry) { BranchCondition condition = null; @@ -1591,13 +1573,14 @@ // automatically via the cascade } - Integer conditionUIID = conditionDetails.getInt(AuthoringJsonTags.CONDITION_UIID); - String conditionType = conditionDetails.getString(AuthoringJsonTags.CONDITION_TYPE); + Integer conditionUIID = JsonUtil.optInt(conditionDetails, AuthoringJsonTags.CONDITION_UIID); + String conditionType = JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_TYPE); if (BranchCondition.OUTPUT_TYPE_COMPLEX.equals(conditionType) || BranchCondition.OUTPUT_TYPE_STRING.equals(conditionType)) { // This is different than "conditionID" !!! - Long newConditionID = condition == null ? conditionDetails.getLong(AuthoringJsonTags.CONDITION_ID) + Long newConditionID = condition == null + ? JsonUtil.optLong(conditionDetails, AuthoringJsonTags.CONDITION_ID) : condition.getConditionId(); // we need to get the proper subclass, since the one provided by branch entry is not valid BranchCondition originalCondition = branchActivityEntryDAO.getConditionByID(newConditionID); @@ -1613,24 +1596,24 @@ } } else if (condition == null) { condition = new BranchCondition(null, conditionUIID, - conditionDetails.getInt(AuthoringJsonTags.ORDER_ID), - conditionDetails.getString(AuthoringJsonTags.CONDITION_NAME), - conditionDetails.getString(AuthoringJsonTags.CONDITION_DISPLAY_NAME), - conditionDetails.getString(AuthoringJsonTags.CONDITION_TYPE), - (String) JsonUtil.opt(conditionDetails, AuthoringJsonTags.CONDITION_START_VALUE), - (String) JsonUtil.opt(conditionDetails, AuthoringJsonTags.CONDITION_END_VALUE), - (String) JsonUtil.opt(conditionDetails, AuthoringJsonTags.CONDITION_EXACT_MATCH_VALUE)); + JsonUtil.optInt(conditionDetails, AuthoringJsonTags.ORDER_ID), + JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_NAME), + JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_DISPLAY_NAME), + JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_TYPE), + JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_START_VALUE), + JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_END_VALUE), + JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_EXACT_MATCH_VALUE)); } else { condition.setConditionUIID(conditionUIID); - condition.setDisplayName(conditionDetails.getString(AuthoringJsonTags.CONDITION_DISPLAY_NAME)); - condition.setEndValue((String) JsonUtil.opt(conditionDetails, AuthoringJsonTags.CONDITION_END_VALUE)); + condition + .setDisplayName(JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_DISPLAY_NAME)); + condition.setEndValue(JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_END_VALUE)); condition.setExactMatchValue( - (String) JsonUtil.opt(conditionDetails, AuthoringJsonTags.CONDITION_EXACT_MATCH_VALUE)); - condition.setName(conditionDetails.getString(AuthoringJsonTags.CONDITION_NAME)); - condition.setOrderId(conditionDetails.getInt(AuthoringJsonTags.ORDER_ID)); - condition.setStartValue( - (String) JsonUtil.opt(conditionDetails, AuthoringJsonTags.CONDITION_START_VALUE)); - condition.setType(conditionDetails.getString(AuthoringJsonTags.CONDITION_TYPE)); + JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_EXACT_MATCH_VALUE)); + condition.setName(JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_NAME)); + condition.setOrderId(JsonUtil.optInt(conditionDetails, AuthoringJsonTags.ORDER_ID)); + condition.setStartValue(JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_START_VALUE)); + condition.setType(JsonUtil.optString(conditionDetails, AuthoringJsonTags.CONDITION_TYPE)); } } return condition; @@ -1649,16 +1632,15 @@ return tool; } - private void createLearnerChoiceGrouping(LearnerChoiceGrouping learnerChoiceGrouping, JSONObject groupingDetails) - throws JSONException { - Integer numLearnersPerGroup = (Integer) JsonUtil.opt(groupingDetails, AuthoringJsonTags.LEARNERS_PER_GROUP); + private void createLearnerChoiceGrouping(LearnerChoiceGrouping learnerChoiceGrouping, ObjectNode groupingDetails) { + Integer numLearnersPerGroup = JsonUtil.optInt(groupingDetails, AuthoringJsonTags.LEARNERS_PER_GROUP); if ((numLearnersPerGroup != null) && (numLearnersPerGroup.intValue() > 0)) { learnerChoiceGrouping.setLearnersPerGroup(numLearnersPerGroup); learnerChoiceGrouping.setNumberOfGroups(null); learnerChoiceGrouping.setEqualNumberOfLearnersPerGroup(null); } else { - Integer numGroups = (Integer) JsonUtil.opt(groupingDetails, AuthoringJsonTags.NUMBER_OF_GROUPS); + Integer numGroups = JsonUtil.optInt(groupingDetails, AuthoringJsonTags.NUMBER_OF_GROUPS); if ((numGroups != null) && (numGroups.intValue() > 0)) { learnerChoiceGrouping.setNumberOfGroups(numGroups); @@ -1667,14 +1649,14 @@ } learnerChoiceGrouping.setLearnersPerGroup(null); - Boolean equalNumberOfLearnersPerGroup = (Boolean) JsonUtil.opt(groupingDetails, + Boolean equalNumberOfLearnersPerGroup = JsonUtil.optBoolean(groupingDetails, AuthoringJsonTags.EQUAL_NUMBER_OF_LEARNERS_PER_GROUP); if (equalNumberOfLearnersPerGroup != null) { learnerChoiceGrouping.setEqualNumberOfLearnersPerGroup(equalNumberOfLearnersPerGroup); } } learnerChoiceGrouping.setViewStudentsBeforeSelection( - (Boolean) JsonUtil.opt(groupingDetails, AuthoringJsonTags.VIEW_STUDENTS_BEFORE_SELECTION)); + JsonUtil.optBoolean(groupingDetails, AuthoringJsonTags.VIEW_STUDENTS_BEFORE_SELECTION)); } private void buildConditionGateActivity(ConditionGateActivity activity) { Index: lams_central/src/java/org/lamsfoundation/lams/authoring/service/AuthoringService.java =================================================================== diff -u -r4b865d9e5cdcaa1a21b113764194305d9a7480dd -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_central/src/java/org/lamsfoundation/lams/authoring/service/AuthoringService.java (.../AuthoringService.java) (revision 4b865d9e5cdcaa1a21b113764194305d9a7480dd) +++ lams_central/src/java/org/lamsfoundation/lams/authoring/service/AuthoringService.java (.../AuthoringService.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -44,8 +44,6 @@ import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; -import org.apache.tomcat.util.json.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.authoring.IObjectExtractor; import org.lamsfoundation.lams.authoring.ObjectExtractorException; import org.lamsfoundation.lams.dao.IBaseDAO; @@ -109,6 +107,7 @@ import org.lamsfoundation.lams.usermanagement.exception.WorkspaceFolderException; import org.lamsfoundation.lams.util.Configuration; import org.lamsfoundation.lams.util.ConfigurationKeys; +import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.web.session.SessionManager; @@ -117,6 +116,8 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Manpreet Minhas */ @@ -516,7 +517,6 @@ } // only the user who is editing the design may unlock it if (design.getEditOverrideUser().equals(user)) { - design.setEditOverrideLock(false); design.setEditOverrideUser(null); @@ -1480,8 +1480,8 @@ } @Override - public LearningDesign saveLearningDesignDetails(JSONObject ldJSON) - throws UserException, JSONException, WorkspaceFolderException, ObjectExtractorException, ParseException { + public LearningDesign saveLearningDesignDetails(ObjectNode ldJSON) + throws UserException, WorkspaceFolderException, ObjectExtractorException, ParseException { User user = null; Integer userID = AuthoringService.getUserId(); if (userID != null) { @@ -1491,15 +1491,15 @@ throw new UserException("UserID missing or user not found."); } - Integer workspaceFolderID = ldJSON.getInt("workspaceFolderID"); + Integer workspaceFolderID = JsonUtil.optInt(ldJSON, "workspaceFolderID"); WorkspaceFolder workspaceFolder = null; boolean authorised = false; if (workspaceFolderID != null) { workspaceFolder = (WorkspaceFolder) baseDAO.find(WorkspaceFolder.class, workspaceFolderID); authorised = workspaceManagementService.isUserAuthorizedToModifyFolderContents(workspaceFolderID, userID); } - Long learningDesignId = ldJSON.optLong(AttributeNames.PARAM_LEARNINGDESIGN_ID); + Long learningDesignId = JsonUtil.optLong(ldJSON, AttributeNames.PARAM_LEARNINGDESIGN_ID); LearningDesign existingLearningDesign = learningDesignId == null ? null : learningDesignDAO.getLearningDesignById(learningDesignId); if (!authorised && (existingLearningDesign != null) @@ -1518,8 +1518,7 @@ if (extractor.getMode().intValue() == 1) { // adding the customCSV to the call if it is present - String customCSV = ldJSON.optString("customCSV"); - + String customCSV = JsonUtil.optString(ldJSON, "customCSV"); copyLearningDesignToolContent(design, design, design.getCopyTypeID(), customCSV); } Index: lams_central/src/java/org/lamsfoundation/lams/comments/web/CommentAction.java =================================================================== diff -u -r500ae45f4243aa718eac7436bc903b4f137a3aa7 -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_central/src/java/org/lamsfoundation/lams/comments/web/CommentAction.java (.../CommentAction.java) (revision 500ae45f4243aa718eac7436bc903b4f137a3aa7) +++ lams_central/src/java/org/lamsfoundation/lams/comments/web/CommentAction.java (.../CommentAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -36,8 +36,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.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.comments.Comment; import org.lamsfoundation.lams.comments.CommentConstants; import org.lamsfoundation.lams.comments.CommentLike; @@ -58,6 +56,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 Fiona Malikoff */ @@ -160,7 +161,7 @@ sortBy = (Integer) sessionMap.get(CommentConstants.ATTR_SORT_BY); } else { - sessionMap = new SessionMap(); + sessionMap = new SessionMap<>(); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); externalId = WebUtil.readLongParam(request, CommentConstants.ATTR_EXTERNAL_ID); @@ -181,7 +182,7 @@ sessionMap.put(CommentConstants.ATTR_EXTERNAL_ID, externalId); sessionMap.put(CommentConstants.ATTR_EXTERNAL_TYPE, externalType); - if ( externalSecondaryId != null ) { + if (externalSecondaryId != null) { sessionMap.put(CommentConstants.ATTR_EXTERNAL_SECONDARY_ID, externalSecondaryId); } sessionMap.put(CommentConstants.ATTR_EXTERNAL_SIG, externalSignature); @@ -200,7 +201,8 @@ throwException("Unknown comment type ", user.getLogin(), externalId, externalType, externalSignature); } - Comment rootComment = getCommentService().createOrGetRoot(externalId, externalSecondaryId, externalType, externalSignature, user); + Comment rootComment = getCommentService().createOrGetRoot(externalId, externalSecondaryId, externalType, + externalSignature, user); sessionMap.put(CommentConstants.ATTR_ROOT_COMMENT_UID, rootComment.getUid()); return viewTopicImpl(mapping, form, request, response, sessionMap, pageSize, sortBy, true); } @@ -377,7 +379,7 @@ * Create a new comment (not a reply) */ private ActionForward newComment(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws InterruptedException, JSONException, IOException, ServletException { + HttpServletResponse response) throws InterruptedException, IOException, ServletException { SessionMap sessionMap = getSessionMap(request); Long externalId = (Long) sessionMap.get(CommentConstants.ATTR_EXTERNAL_ID); @@ -390,21 +392,22 @@ commentText = commentText.trim(); } - Boolean commentAnonymous = WebUtil.readBooleanParam(request, CommentConstants.ATTR_COMMENT_ANONYMOUS_NEW, false); + Boolean commentAnonymous = WebUtil.readBooleanParam(request, CommentConstants.ATTR_COMMENT_ANONYMOUS_NEW, + false); - JSONObject JSONObject; + ObjectNode responseJSON; if (!validateText(commentText)) { - JSONObject = getFailedValidationJSON(); - + responseJSON = getFailedValidationJSON(); } else { commentService = getCommentService(); User user = getCurrentUser(request); ToolAccessMode mode = WebUtil.getToolAccessMode((String) sessionMap.get(AttributeNames.ATTR_MODE)); - boolean isMonitor = ToolAccessMode.TEACHER.equals(mode) && monitorInToolSession(externalId, user, sessionMap); - if (!isMonitor && !learnerInToolSession(externalId, user) ) { + boolean isMonitor = ToolAccessMode.TEACHER.equals(mode) + && monitorInToolSession(externalId, user, sessionMap); + if (!isMonitor && !learnerInToolSession(externalId, user)) { throwException("New comment: User does not have the rights to access the comments. ", user.getLogin(), externalId, externalType, externalSignature); } @@ -414,14 +417,15 @@ // save message into database Comment newComment = commentService.createReply(rootSeq, commentText, user, isMonitor, commentAnonymous); - JSONObject = new JSONObject(); - JSONObject.put(CommentConstants.ATTR_COMMENT_ID, newComment.getUid()); - JSONObject.put(CommentConstants.ATTR_THREAD_ID, newComment.getThreadComment().getUid()); - JSONObject.put(CommentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); - JSONObject.put(CommentConstants.ATTR_PARENT_COMMENT_ID, newComment.getParent().getUid()); + responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.put(CommentConstants.ATTR_COMMENT_ID, newComment.getUid()); + responseJSON.put(CommentConstants.ATTR_THREAD_ID, newComment.getThreadComment().getUid()); + responseJSON.put(CommentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); + responseJSON.put(CommentConstants.ATTR_PARENT_COMMENT_ID, newComment.getParent().getUid()); + } response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(responseJSON); return null; } @@ -448,7 +452,7 @@ * Create a reply to a parent topic. */ private ActionForward replyTopicInline(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws InterruptedException, JSONException, IOException, ServletException { + HttpServletResponse response) throws InterruptedException, IOException, ServletException { SessionMap sessionMap = getSessionMap(request); Long externalId = (Long) sessionMap.get(CommentConstants.ATTR_EXTERNAL_ID); @@ -462,36 +466,38 @@ commentText = commentText.trim(); } - Boolean commentAnonymous = WebUtil.readBooleanParam(request, CommentConstants.ATTR_COMMENT_ANONYMOUS_REPLY, false); + Boolean commentAnonymous = WebUtil.readBooleanParam(request, CommentConstants.ATTR_COMMENT_ANONYMOUS_REPLY, + false); - JSONObject JSONObject; + ObjectNode responseJSON; if (!validateText(commentText)) { - JSONObject = getFailedValidationJSON(); - + responseJSON = getFailedValidationJSON(); } else { User user = getCurrentUser(request); ToolAccessMode mode = WebUtil.getToolAccessMode((String) sessionMap.get(AttributeNames.ATTR_MODE)); - boolean isMonitor = ToolAccessMode.TEACHER.equals(mode) && monitorInToolSession(externalId, user, sessionMap); - if (!isMonitor && !learnerInToolSession(externalId, user) ) { + boolean isMonitor = ToolAccessMode.TEACHER.equals(mode) + && monitorInToolSession(externalId, user, sessionMap); + if (!isMonitor && !learnerInToolSession(externalId, user)) { throwException("New comment: User does not have the rights to access the comments. ", user.getLogin(), externalId, externalType, externalSignature); } // save message into database - Comment newComment = commentService.createReply(parentId, commentText.trim(), user, isMonitor, commentAnonymous); + Comment newComment = commentService.createReply(parentId, commentText.trim(), user, isMonitor, + commentAnonymous); - JSONObject = new JSONObject(); - JSONObject.put(CommentConstants.ATTR_COMMENT_ID, newComment.getUid()); - JSONObject.put(CommentConstants.ATTR_THREAD_ID, newComment.getThreadComment().getUid()); - JSONObject.put(CommentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); - JSONObject.put(CommentConstants.ATTR_PARENT_COMMENT_ID, newComment.getParent().getUid()); + responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.put(CommentConstants.ATTR_COMMENT_ID, newComment.getUid()); + responseJSON.put(CommentConstants.ATTR_THREAD_ID, newComment.getThreadComment().getUid()); + responseJSON.put(CommentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); + responseJSON.put(CommentConstants.ATTR_PARENT_COMMENT_ID, newComment.getParent().getUid()); } response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(responseJSON); return null; } @@ -500,11 +506,11 @@ && commentText.length() < CommentConstants.MAX_BODY_LENGTH; } - private JSONObject getFailedValidationJSON() throws JSONException { + private ObjectNode getFailedValidationJSON() { MessageService msgService = getCommentService().getMessageService(); - JSONObject JSONObject = new JSONObject(); - JSONObject.put(CommentConstants.ATTR_ERR_MESSAGE, msgService.getMessage(CommentConstants.KEY_BODY_VALIDATION)); - return JSONObject; + ObjectNode resultJSON = JsonNodeFactory.instance.objectNode(); + resultJSON.put(CommentConstants.ATTR_ERR_MESSAGE, msgService.getMessage(CommentConstants.KEY_BODY_VALIDATION)); + return resultJSON; } /** @@ -537,7 +543,7 @@ * @throws ServletException */ public ActionForward updateTopicInline(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException, ServletException { + HttpServletResponse response) throws IOException, ServletException { commentService = getCommentService(); SessionMap sessionMap = getSessionMap(request); @@ -553,13 +559,15 @@ } // Don't update anonymous if it is monitoring - boolean isMonitoring = ToolAccessMode.TEACHER.equals(WebUtil.getToolAccessMode((String) sessionMap.get(AttributeNames.ATTR_MODE))); - Boolean commentAnonymous = isMonitoring ? null : WebUtil.readBooleanParam(request, CommentConstants.ATTR_COMMENT_ANONYMOUS_EDIT, false); + boolean isMonitoring = ToolAccessMode.TEACHER + .equals(WebUtil.getToolAccessMode((String) sessionMap.get(AttributeNames.ATTR_MODE))); + Boolean commentAnonymous = isMonitoring ? null + : WebUtil.readBooleanParam(request, CommentConstants.ATTR_COMMENT_ANONYMOUS_EDIT, false); - JSONObject JSONObject; + ObjectNode ObjectNode; if (!validateText(commentText)) { - JSONObject = getFailedValidationJSON(); + ObjectNode = getFailedValidationJSON(); } else { @@ -573,27 +581,27 @@ user.getLogin(), externalId, externalType, externalSignature); } - Comment updatedComment = commentService.updateComment(commentId, commentText, user, commentAnonymous, isMonitoring); + Comment updatedComment = commentService.updateComment(commentId, commentText, user, commentAnonymous, + isMonitoring); - JSONObject = new JSONObject(); - JSONObject.put(CommentConstants.ATTR_COMMENT_ID, commentId); - JSONObject.put(CommentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); - JSONObject.put(CommentConstants.ATTR_THREAD_ID, updatedComment.getThreadComment().getUid()); - JSONObject.put(CommentConstants.ATTR_PARENT_COMMENT_ID, updatedComment.getParent().getUid()); + ObjectNode = JsonNodeFactory.instance.objectNode(); + ObjectNode.put(CommentConstants.ATTR_COMMENT_ID, commentId); + ObjectNode.put(CommentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); + ObjectNode.put(CommentConstants.ATTR_THREAD_ID, updatedComment.getThreadComment().getUid()); + ObjectNode.put(CommentConstants.ATTR_PARENT_COMMENT_ID, updatedComment.getParent().getUid()); } response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); return null; } /** * Update the likes/dislikes */ private ActionForward updateLikeCount(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response, boolean isLike) - throws InterruptedException, JSONException, IOException, ServletException { + HttpServletResponse response, boolean isLike) throws InterruptedException, IOException, ServletException { SessionMap sessionMap = getSessionMap(request); Long messageUid = WebUtil.readLongParam(request, CommentConstants.ATTR_COMMENT_ID); @@ -611,20 +619,19 @@ boolean added = commentService.addLike(messageUid, user, isLike ? CommentLike.LIKE : CommentLike.DISLIKE); - JSONObject JSONObject = new JSONObject(); - JSONObject.put(CommentConstants.ATTR_COMMENT_ID, messageUid); - JSONObject.put(CommentConstants.ATTR_STATUS, added); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.put(CommentConstants.ATTR_COMMENT_ID, messageUid); + responseJSON.put(CommentConstants.ATTR_STATUS, added); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(responseJSON); return null; } /** * Update hide flag */ private ActionForward hideComment(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response, boolean isLike) - throws InterruptedException, JSONException, IOException, ServletException { + HttpServletResponse response, boolean isLike) throws InterruptedException, IOException, ServletException { SessionMap sessionMap = getSessionMap(request); Long commentId = WebUtil.readLongParam(request, CommentConstants.ATTR_COMMENT_ID); @@ -642,14 +649,14 @@ Comment updatedComment = commentService.hideComment(commentId, user, status); - JSONObject JSONObject = new JSONObject(); - JSONObject.put(CommentConstants.ATTR_COMMENT_ID, updatedComment.getUid()); - JSONObject.put(CommentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); - JSONObject.put(CommentConstants.ATTR_THREAD_ID, updatedComment.getThreadComment().getUid()); - JSONObject.put(CommentConstants.ATTR_PARENT_COMMENT_ID, updatedComment.getParent().getUid()); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.put(CommentConstants.ATTR_COMMENT_ID, updatedComment.getUid()); + responseJSON.put(CommentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); + responseJSON.put(CommentConstants.ATTR_THREAD_ID, updatedComment.getThreadComment().getUid()); + responseJSON.put(CommentConstants.ATTR_PARENT_COMMENT_ID, updatedComment.getParent().getUid()); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(responseJSON); return null; } @@ -659,7 +666,7 @@ * @throws ServletException */ public ActionForward makeSticky(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException, ServletException { + HttpServletResponse response) throws IOException, ServletException { commentService = getCommentService(); SessionMap sessionMap = getSessionMap(request); @@ -683,14 +690,14 @@ Comment updatedComment = commentService.updateSticky(commentId, sticky); - JSONObject JSONObject = new JSONObject(); - JSONObject.put(CommentConstants.ATTR_COMMENT_ID, commentId); - JSONObject.put(CommentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); - JSONObject.put(CommentConstants.ATTR_THREAD_ID, updatedComment.getThreadComment().getUid()); - JSONObject.put(CommentConstants.ATTR_PARENT_COMMENT_ID, updatedComment.getParent().getUid()); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.put(CommentConstants.ATTR_COMMENT_ID, commentId); + responseJSON.put(CommentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); + responseJSON.put(CommentConstants.ATTR_THREAD_ID, updatedComment.getThreadComment().getUid()); + responseJSON.put(CommentConstants.ATTR_PARENT_COMMENT_ID, updatedComment.getParent().getUid()); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(responseJSON); return null; } Index: lams_central/src/java/org/lamsfoundation/lams/web/IndexAction.java =================================================================== diff -u -r3617b812ba50ea59fd9991680ee73e5ee41357cf -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_central/src/java/org/lamsfoundation/lams/web/IndexAction.java (.../IndexAction.java) (revision 3617b812ba50ea59fd9991680ee73e5ee41357cf) +++ lams_central/src/java/org/lamsfoundation/lams/web/IndexAction.java (.../IndexAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -37,9 +37,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.index.IndexLinkBean; import org.lamsfoundation.lams.integration.service.IIntegrationService; import org.lamsfoundation.lams.integration.service.IntegrationService; @@ -59,6 +56,10 @@ import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.util.HtmlUtils; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * * @author Fei Yang @@ -77,7 +78,7 @@ public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { - setHeaderLinks(request); + IndexAction.setHeaderLinks(request); setAdminLinks(request); // check if this is user's first login; some action (like displaying a dialog for disabling tutorials) can be @@ -114,7 +115,7 @@ return mapping.findForward("editprofile"); } else if (StringUtils.equals(method, "password")) { return mapping.findForward("password"); - } else if (StringUtils.equals(method, "portrait")) { + } else if (StringUtils.equals(method, "portrait")) { return mapping.findForward("portrait"); } else if (StringUtils.equals(method, "lessons")) { return mapping.findForward("lessons"); @@ -129,23 +130,24 @@ "Integration users with learner right are not allowed to access this page"); return null; } - + // only show the growl warning the first time after a user has logged in & if turned on in configuration Boolean tzWarning = Configuration.getAsBoolean(ConfigurationKeys.SHOW_TIMEZONE_WARNING); request.setAttribute("showTimezoneWarning", tzWarning); request.setAttribute("showTimezoneWarningPopup", false); - if ( tzWarning ) { + if (tzWarning) { Boolean ssWarningShown = (Boolean) ss.getAttribute("timezoneWarningShown"); - if ( ! Boolean.TRUE.equals(ssWarningShown) ) { + if (!Boolean.TRUE.equals(ssWarningShown)) { ss.setAttribute("timezoneWarningShown", Boolean.TRUE); request.setAttribute("showTimezoneWarningPopup", true); } } - - List favoriteOrganisations = userManagementService.getFavoriteOrganisationsByUser(userDTO.getUserID()); + + List favoriteOrganisations = userManagementService + .getFavoriteOrganisationsByUser(userDTO.getUserID()); request.setAttribute("favoriteOrganisations", favoriteOrganisations); request.setAttribute("activeOrgId", user.getLastVisitedOrganisationId()); - + boolean isSysadmin = request.isUserInRole(Role.SYSADMIN); int userCoursesCount = userManagementService.getCountActiveCoursesByUser(userDTO.getUserID(), isSysadmin, null); request.setAttribute("isCourseSearchOn", userCoursesCount > 10); @@ -154,9 +156,9 @@ } private static void setHeaderLinks(HttpServletRequest request) { - List headerLinks = new ArrayList(); + List headerLinks = new ArrayList<>(); if (request.isUserInRole(Role.AUTHOR)) { - if (isPedagogicalPlannerAvailable()) { + if (IndexAction.isPedagogicalPlannerAvailable()) { headerLinks.add(new IndexLinkBean("index.planner", "javascript:openPedagogicalPlanner()")); } headerLinks.add(new IndexLinkBean("index.author", "javascript:showAuthoringDialog()")); @@ -172,7 +174,7 @@ } private void setAdminLinks(HttpServletRequest request) { - List adminLinks = new ArrayList(); + List adminLinks = new ArrayList<>(); if (request.isUserInRole(Role.SYSADMIN) || request.isUserInRole(Role.GROUP_ADMIN) || request.isUserInRole(Role.GROUP_MANAGER)) { adminLinks.add(new IndexLinkBean("index.courseman", "javascript:openOrgManagement(" @@ -188,10 +190,10 @@ * Returns list of organisations for user. Used by offcanvas tablesorter on main.jsp. */ public ActionForward getOrgs(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse res) throws IOException, ServletException, JSONException { + HttpServletResponse res) throws IOException, ServletException { getUserManagementService(); User loggedInUser = getUserManagementService().getUserByLogin(request.getRemoteUser()); - + Integer userId = loggedInUser.getUserId(); boolean isSysadmin = request.isUserInRole(Role.SYSADMIN); String searchString = WebUtil.readStrParam(request, "fcol[1]", true); @@ -212,27 +214,28 @@ // // } - List orgDtos = userManagementService.getActiveCoursesByUser(userId, isSysadmin, page, size, searchString); + List orgDtos = userManagementService.getActiveCoursesByUser(userId, isSysadmin, page, size, + searchString); - JSONObject responcedata = new JSONObject(); - responcedata.put("total_rows", userManagementService.getCountActiveCoursesByUser(userId, isSysadmin, searchString)); + ObjectNode responcedata = JsonNodeFactory.instance.objectNode(); + responcedata.put("total_rows", + userManagementService.getCountActiveCoursesByUser(userId, isSysadmin, searchString)); - JSONArray rows = new JSONArray(); + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); for (OrganisationDTO orgDto : orgDtos) { - - JSONObject responseRow = new JSONObject(); + ObjectNode responseRow = JsonNodeFactory.instance.objectNode(); responseRow.put("id", orgDto.getOrganisationID()); String orgName = orgDto.getName() == null ? "" : orgDto.getName(); responseRow.put("name", HtmlUtils.htmlEscape(orgName)); - rows.put(responseRow); + rows.add(responseRow); } - responcedata.put("rows", rows); + responcedata.set("rows", rows); res.setContentType("application/json;charset=utf-8"); res.getWriter().print(new String(responcedata.toString())); return null; } - + /** * Toggles whether organisation is marked as favorite. */ @@ -248,18 +251,18 @@ List favoriteOrganisations = userManagementService.getFavoriteOrganisationsByUser(userId); request.setAttribute("favoriteOrganisations", favoriteOrganisations); - + String activeOrgId = request.getParameter("activeOrgId"); request.setAttribute("activeOrgId", activeOrgId); return mapping.findForward("favoriteOrganisations"); } - + /** * Saves to DB last visited organisation. It's required for displaying some org on main.jsp next time user logs in. */ - public ActionForward storeLastVisitedOrganisation(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse res) throws IOException, ServletException { + public ActionForward storeLastVisitedOrganisation(ActionMapping mapping, ActionForm form, + HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException { getUserManagementService(); Integer lastVisitedOrganisationId = WebUtil.readIntParam(request, "orgId", false); @@ -272,13 +275,13 @@ return null; } - + private Integer getUserId() { HttpSession ss = SessionManager.getSession(); UserDTO learner = (UserDTO) ss.getAttribute(AttributeNames.USER); return learner != null ? learner.getUserID() : null; } - + private IIntegrationService getIntegrationService() { if (integrationService == null) { integrationService = (IntegrationService) WebApplicationContextUtils Index: lams_common/src/java/org/lamsfoundation/lams/integration/service/IntegrationService.java =================================================================== diff -u -r3617b812ba50ea59fd9991680ee73e5ee41357cf -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_common/src/java/org/lamsfoundation/lams/integration/service/IntegrationService.java (.../IntegrationService.java) (revision 3617b812ba50ea59fd9991680ee73e5ee41357cf) +++ lams_common/src/java/org/lamsfoundation/lams/integration/service/IntegrationService.java (.../IntegrationService.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -43,8 +43,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; -import org.apache.tomcat.util.json.JSONArray; -import org.apache.tomcat.util.json.JSONObject; import org.imsglobal.pox.IMSPOXRequest; import org.lamsfoundation.lams.gradebook.GradebookUserLesson; import org.lamsfoundation.lams.gradebook.service.IGradebookService; @@ -73,10 +71,14 @@ import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; import org.lamsfoundation.lams.util.CSVUtil; import org.lamsfoundation.lams.util.HashUtil; +import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.LanguageUtil; import org.lamsfoundation.lams.util.ValidationUtil; import org.lamsfoundation.lams.util.WebUtil; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; + import oauth.signpost.exception.OAuthException; /** @@ -780,25 +782,22 @@ BufferedReader isReader = new BufferedReader(new InputStreamReader(is)); String str = isReader.readLine(); - JSONArray jsonGroups = new JSONArray(str); + ArrayNode jsonGroups = JsonUtil.readArray(str); List extGroups = new ArrayList<>(); - for (int i = 0; i < jsonGroups.length(); i++) { - JSONObject jsonGroup = jsonGroups.getJSONObject(i); + for (JsonNode jsonGroup : jsonGroups) { ExtGroupDTO group = new ExtGroupDTO(); - group.setGroupName(jsonGroup.getString("groupName")); - group.setGroupId(jsonGroup.getString("groupId")); + group.setGroupName(JsonUtil.optString(jsonGroup, "groupName")); + group.setGroupId(JsonUtil.optString(jsonGroup, "groupId")); extGroups.add(group); // in case group info is also requested - provide selected groups' ids if (extGroupIds != null && extGroupIds.length > 0) { ArrayList users = new ArrayList<>(); - JSONArray jsonUsers = jsonGroup.getJSONArray("users"); - for (int j = 0; j < jsonUsers.length(); j++) { - JSONObject jsonUser = jsonUsers.getJSONObject(j); + ArrayNode jsonUsers = JsonUtil.optArray(jsonGroup, "users"); + for (JsonNode jsonUser : jsonUsers) { + String extUsername = JsonUtil.optString(jsonUser, "userName"); - String extUsername = jsonUser.getString("userName"); - ExtUserUseridMap extUserUseridMap = getExistingExtUserUseridMap(extServer, extUsername); //create extUserUseridMap if it's not available @@ -808,7 +807,7 @@ // language>, String[] userData = new String[14]; for (int k = 1; k <= 14; k++) { - String userProperty = jsonUser.getString("" + k); + String userProperty = JsonUtil.optString(jsonUser, "" + k); userData[k - 1] = userProperty; } String salt = HashUtil.salt(); @@ -832,7 +831,7 @@ group.setUsers(users); } else { - group.setNumberUsers(jsonGroup.getInt("groupSize")); + group.setNumberUsers(JsonUtil.optInt(jsonGroup, "groupSize")); } } Index: lams_common/src/java/org/lamsfoundation/lams/learningdesign/service/ExportToolContentService.java =================================================================== diff -u -rb776da39a329453ae50c981cc294562d907b48f5 -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_common/src/java/org/lamsfoundation/lams/learningdesign/service/ExportToolContentService.java (.../ExportToolContentService.java) (revision b776da39a329453ae50c981cc294562d907b48f5) +++ lams_common/src/java/org/lamsfoundation/lams/learningdesign/service/ExportToolContentService.java (.../ExportToolContentService.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -141,9 +141,10 @@ import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.converters.reflection.ReflectionConverter; -import com.thoughtworks.xstream.converters.reflection.SunUnsafeReflectionProvider; + import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; +import com.thoughtworks.xstream.io.xml.StaxDriver; import com.thoughtworks.xstream.security.AnyTypePermission; /** @@ -477,7 +478,7 @@ } // exporting XML - XStream designXml = new XStream(new SunUnsafeReflectionProvider()); + XStream designXml = new XStream(new StaxDriver()); designXml.addPermission(AnyTypePermission.ANY); designXml.toXML(ldDto, ldFile); ldFile.close(); @@ -550,7 +551,7 @@ Writer toolFile = new OutputStreamWriter(new FileOutputStream(toolFileName), "UTF-8"); // serialize tool xml into local file. - XStream toolXml = new XStream(new SunUnsafeReflectionProvider()); + XStream toolXml = new XStream(new StaxDriver()); toolXml.addPermission(AnyTypePermission.ANY); FileConverter fileConverter = null; if (!fileHandleClassList.isEmpty()) { @@ -905,7 +906,7 @@ String toVersion) throws ImportToolContentException { Object toolPOJO = null; // change xml to Tool POJO - XStream toolXml = new XStream(new SunUnsafeReflectionProvider()); + XStream toolXml = new XStream(new StaxDriver()); toolXml.addPermission(AnyTypePermission.ANY); FileConverter fileConverter = null; if (!fileHandleClassList.isEmpty()) { Index: lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookAction.java =================================================================== diff -u -r352e16d0ad309caa12c5422fddebfc221c83714b -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookAction.java (.../GradebookAction.java) (revision 352e16d0ad309caa12c5422fddebfc221c83714b) +++ lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookAction.java (.../GradebookAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -34,8 +34,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.JSONObject; import org.lamsfoundation.lams.gradebook.GradebookUserLesson; import org.lamsfoundation.lams.gradebook.dto.GBLessonGridRowDTO; import org.lamsfoundation.lams.gradebook.dto.GBUserGridRowDTO; @@ -66,6 +64,10 @@ 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; + /** * @author lfoxton * @@ -172,12 +174,12 @@ List gradebookActivityDTOs = getGradebookService().getGBLessonComplete(lessonId, userId); - JSONObject resultJSON = new JSONObject(); + ObjectNode resultJSON = JsonNodeFactory.instance.objectNode(); resultJSON.put(GradebookConstants.ELEMENT_RECORDS, gradebookActivityDTOs.size()); - JSONArray rowsJSON = new JSONArray(); + ArrayNode rowsJSON = JsonNodeFactory.instance.arrayNode(); for (GradebookGridRowDTO gradebookActivityDTO : gradebookActivityDTOs) { - JSONObject rowJSON = new JSONObject(); + ObjectNode rowJSON = JsonNodeFactory.instance.objectNode(); String id = gradebookActivityDTO.getId(); String[] idParts = id.split("_"); if (idParts.length > 1) { @@ -187,21 +189,21 @@ } rowJSON.put(GradebookConstants.ELEMENT_ID, id); - JSONArray cellJSON = new JSONArray(); - cellJSON.put(gradebookActivityDTO.getRowName()); - cellJSON.put(gradebookActivityDTO.getStatus()); - cellJSON.put(gradebookActivityDTO.getAverageMark() == null ? GradebookConstants.CELL_EMPTY + ArrayNode cellJSON = JsonNodeFactory.instance.arrayNode(); + cellJSON.add(gradebookActivityDTO.getRowName()); + cellJSON.add(gradebookActivityDTO.getStatus()); + cellJSON.add(gradebookActivityDTO.getAverageMark() == null ? GradebookConstants.CELL_EMPTY : GradebookUtil.niceFormatting(gradebookActivityDTO.getAverageMark())); - cellJSON.put(gradebookActivityDTO.getMark() == null ? GradebookConstants.CELL_EMPTY + cellJSON.add(gradebookActivityDTO.getMark() == null ? GradebookConstants.CELL_EMPTY : GradebookUtil.niceFormatting(gradebookActivityDTO.getMark())); - rowJSON.put(GradebookConstants.ELEMENT_CELL, cellJSON); - rowsJSON.put(rowJSON); + rowJSON.set(GradebookConstants.ELEMENT_CELL, cellJSON); + rowsJSON.add(rowJSON); } - resultJSON.put(GradebookConstants.ELEMENT_ROWS, rowsJSON); + resultJSON.set(GradebookConstants.ELEMENT_ROWS, rowsJSON); // make a mapping of activity ID -> URL, same as in progress bar - JSONObject activityURLJSON = new JSONObject(); + ObjectNode activityURLJSON = JsonNodeFactory.instance.objectNode(); Object[] ret = getLearnerService().getStructuredActivityURLs(userId, lessonId); for (ActivityURL activity : (List) ret[0]) { String url = activity.getUrl(); @@ -217,7 +219,7 @@ activityURLJSON.put(activity.getActivityId().toString(), activity.getUrl()); } } - resultJSON.put("urls", activityURLJSON); + resultJSON.set("urls", activityURLJSON); boolean isWeighted = getGradebookService().isWeightedMarks(lessonId); GradebookUserLesson gradebookUserLesson = getGradebookService().getGradebookUserLesson(lessonId, userId); Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/GroupingUploadAJAXAction.java =================================================================== diff -u -rd4e021484ff7884e60b88d682d374cc0b7bfae8a -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/GroupingUploadAJAXAction.java (.../GroupingUploadAJAXAction.java) (revision d4e021484ff7884e60b88d682d374cc0b7bfae8a) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/GroupingUploadAJAXAction.java (.../GroupingUploadAJAXAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -57,8 +57,6 @@ import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import org.apache.struts.upload.FormFile; -import org.apache.tomcat.util.json.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.learningdesign.Activity; import org.lamsfoundation.lams.learningdesign.Group; import org.lamsfoundation.lams.learningdesign.GroupComparator; @@ -87,9 +85,12 @@ 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; + /** * The action servlet that provides the support for the AJAX based Chosen Grouping upload from File - * + * * @author Fiona Malikoff */ public class GroupingUploadAJAXAction extends DispatchAction { @@ -102,9 +103,10 @@ private static MessageService centralMessageService; /** - * Get the spreadsheet file containing list of the current users, ready for uploading with groups. If lesson supplied, + * Get the spreadsheet file containing list of the current users, ready for uploading with groups. If lesson + * supplied, * list lesson users, otherwise list organisation users (course grouping screen has just the organisation). - * + * * @throws Exception */ public ActionForward getGroupTemplateFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, @@ -113,22 +115,23 @@ Integer userId = getUserDTO().getUserID(); Integer organisationId = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID, true); Long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID, true); - - if ( lessonId == null && organisationId == null ) { - log.error("Cannot create group template file as lessonId and organisationId are both null."); - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid parameters"); + + if (lessonId == null && organisationId == null) { + log.error("Cannot create group template file as lessonId and organisationId are both null."); + response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid parameters"); } - - Lesson lesson = null; - String lessonOrOrganisationName = null; - - if ( lessonId != null ) { - lesson = (Lesson) getUserManagementService().findById(Lesson.class, lessonId); - lessonOrOrganisationName = lesson.getLessonName(); - organisationId = lesson.getOrganisation().getOrganisationId(); - } else { - Organisation organisation = (Organisation) getUserManagementService().findById(Organisation.class, organisationId); - lessonOrOrganisationName = organisation.getName(); + + Lesson lesson = null; + String lessonOrOrganisationName = null; + + if (lessonId != null) { + lesson = (Lesson) getUserManagementService().findById(Lesson.class, lessonId); + lessonOrOrganisationName = lesson.getLessonName(); + organisationId = lesson.getOrganisation().getOrganisationId(); + } else { + Organisation organisation = (Organisation) getUserManagementService().findById(Organisation.class, + organisationId); + lessonOrOrganisationName = organisation.getName(); } // check if user is allowed to view and edit groups @@ -158,15 +161,17 @@ dataToExport = exportLearnersForGrouping(learners, grouping.getGroups(), null); } else { - @SuppressWarnings("unchecked") - Long groupingId = WebUtil.readLongParam(request, "groupingId", true); + Long groupingId = WebUtil.readLongParam(request, "groupingId", true); Set groups = null; - if ( groupingId != null ) { - OrganisationGrouping orgGrouping = (OrganisationGrouping) getUserManagementService().findById(OrganisationGrouping.class, groupingId); - if ( orgGrouping != null ) + if (groupingId != null) { + OrganisationGrouping orgGrouping = (OrganisationGrouping) getUserManagementService() + .findById(OrganisationGrouping.class, groupingId); + if (orgGrouping != null) { groups = orgGrouping.getGroups(); + } } - Vector learners = (Vector) getUserManagementService().getUsersFromOrganisationByRole(organisationId, Role.LEARNER, true); + Vector learners = getUserManagementService().getUsersFromOrganisationByRole(organisationId, + Role.LEARNER, true); dataToExport = exportLearnersForGrouping(learners, null, groups); } @@ -183,7 +188,8 @@ return null; } - private LinkedHashMap exportLearnersForGrouping(Collection learners, Set groups, Set orgGroups) { + private LinkedHashMap exportLearnersForGrouping(Collection learners, Set groups, + Set orgGroups) { List rowList = new LinkedList(); int numberOfColumns = 4; @@ -195,7 +201,7 @@ title[3] = new ExcelCell(getCentralMessageService().getMessage("spreadsheet.column.groupname"), false); rowList.add(title); - if ( groups != null ) { + if (groups != null) { List groupList = new LinkedList<>(groups); Collections.sort(groupList, new GroupComparator()); for (Group group : groupList) { @@ -206,8 +212,8 @@ } } } - - if ( orgGroups != null ) { + + if (orgGroups != null) { List groupList = new LinkedList<>(orgGroups); for (OrganisationGroup group : groupList) { String groupName = group.getName(); @@ -237,35 +243,35 @@ userRow[3] = new ExcelCell(groupName, false); return userRow; } - + /** * Saves a course grouping. */ public ActionForward importLearnersForGrouping(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, InvalidParameterException, IOException { + HttpServletResponse response) throws InvalidParameterException, IOException { Integer userId = getUserDTO().getUserID(); Integer organisationId = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID, true); boolean isLessonMode = WebUtil.readBooleanParam(request, "lessonMode", true); - + // used for lesson based grouping Long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID, true); Long activityId = WebUtil.readLongParam(request, AttributeNames.PARAM_ACTIVITY_ID, true); Lesson lesson = lessonId != null ? (Lesson) getUserManagementService().findById(Lesson.class, lessonId) : null; // used for course grouping - Long groupingId = WebUtil.readLongParam(request, "groupingId", true); + Long groupingId = WebUtil.readLongParam(request, "groupingId", true); String name = WebUtil.readStrParam(request, "name", true); - if ( isLessonMode && activityId == null ) { + if (isLessonMode && activityId == null) { log.error("Lesson grouping to be saved but activityId is missing"); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid parameters"); - } else if ( !isLessonMode ) { - if ( ( groupingId == null && name == null ) || organisationId == null ) { + } else if (!isLessonMode) { + if ((groupingId == null && name == null) || organisationId == null) { log.error("Course grouping to be saved but groupingId, grouping name or organisationId is missing"); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid parameters"); } } - + Organisation organisation; if (organisationId == null) { // read organisation ID from lesson @@ -277,9 +283,8 @@ // check if user is allowed to save grouping if (!getSecurityService().hasOrgRole(organisationId, userId, - new String[] { Role.GROUP_ADMIN, Role.GROUP_MANAGER, Role.MONITOR, Role.AUTHOR }, - "save organisation grouping from spreadsheet", - false)) { + new String[] { Role.GROUP_ADMIN, Role.GROUP_MANAGER, Role.MONITOR, Role.AUTHOR }, + "save organisation grouping from spreadsheet", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a manager or admin in the organisation"); return null; } @@ -290,27 +295,26 @@ response.sendError(HttpServletResponse.SC_FORBIDDEN, "No file provided"); } if (log.isDebugEnabled()) { - log.debug("Saving course groups from spreadsheet for user " + userId - + " and organisation " + organisationId + " filename " + fileElements); + log.debug("Saving course groups from spreadsheet for user " + userId + " and organisation " + organisationId + + " filename " + fileElements); } - JSONObject responseJSON = isLessonMode ? saveLessonGrouping(lessonId, activityId, fileElements) + ObjectNode responseJSON = isLessonMode ? saveLessonGrouping(lessonId, activityId, fileElements) : saveCourseGrouping(organisation, groupingId, name, fileElements); response.getWriter().write(responseJSON.toString()); return null; } - /** Create the new course grouping */ - private JSONObject saveCourseGrouping(Organisation organisation, Long orgGroupingId, String name, Hashtable fileElements) - throws JSONException, IOException { - + private ObjectNode saveCourseGrouping(Organisation organisation, Long orgGroupingId, String name, + Hashtable fileElements) throws IOException { + OrganisationGrouping orgGrouping = null; if (orgGroupingId != null) { orgGrouping = (OrganisationGrouping) getUserManagementService().findById(OrganisationGrouping.class, orgGroupingId); - } + } if (orgGrouping == null) { orgGrouping = new OrganisationGrouping(); orgGrouping.setOrganisationId(organisation.getOrganisationId()); @@ -325,26 +329,27 @@ } Map> groups = new HashMap>(); - int totalUsersSkipped = parseGroupSpreadsheet((FormFile) fileElements.elements().nextElement(), orgGroupingId, groups); - + int totalUsersSkipped = parseGroupSpreadsheet((FormFile) fileElements.elements().nextElement(), orgGroupingId, + groups); int totalUsersAdded = 0; + List orgGroups = new LinkedList<>(); - for ( Map.Entry> groupEntry : groups.entrySet()) { + for (Map.Entry> groupEntry : groups.entrySet()) { String groupName = groupEntry.getKey(); // just overwrite existing groups; they will be updated if already exist Set learners = new HashSet<>(); - for ( String login : groupEntry.getValue() ) { - User learner = (User) getUserManagementService().getUserByLogin(login); + for (String login : groupEntry.getValue()) { + User learner = getUserManagementService().getUserByLogin(login); if (learner == null) { - log.warn("Unable to add learner " + login + " for group in related to grouping " - + orgGroupingId + " as learner cannot be found."); + log.warn("Unable to add learner " + login + " for group in related to grouping " + orgGroupingId + + " as learner cannot be found."); totalUsersSkipped++; - - //Check user is a part of the organisation + + //Check user is a part of the organisation } else if (!getSecurityService().hasOrgRole(organisation.getOrganisationId(), learner.getUserId(), new String[] { Role.GROUP_MANAGER, Role.LEARNER, Role.MONITOR, Role.AUTHOR }, "be added to grouping", false)) { - + totalUsersSkipped++; } else { @@ -354,7 +359,7 @@ } OrganisationGroup orgGroup = new OrganisationGroup(); Long orgGroupId = existingGroupNameToId.get(groupName); - if ( orgGroupId != null ) { + if (orgGroupId != null) { orgGroup.setGroupId(orgGroupId); orgGroup.setGroupingId(orgGroupingId); } @@ -368,9 +373,8 @@ } - /** Clean out and reuse any existing groups */ - private JSONObject saveLessonGrouping(Long lessonId, Long activityId, Hashtable fileElements) - throws JSONException, IOException { + /** Clean out and reuse any existing groups */ + private ObjectNode saveLessonGrouping(Long lessonId, Long activityId, Hashtable fileElements) throws IOException { IMonitoringService monitoringService = MonitoringServiceProxy .getMonitoringService(getServlet().getServletContext()); @@ -389,42 +393,45 @@ existingGroupNames.add(group.getGroupName()); if (!group.mayBeDeleted()) { String error = getCentralMessageService().getMessage("error.groups.upload.locked"); - return createResponseJSON(true, error, true, grouping.getGroupingId(),0, 0); + return createResponseJSON(true, error, true, grouping.getGroupingId(), 0, 0); } } Map> groups = new HashMap>(); - totalUsersSkipped = parseGroupSpreadsheet((FormFile) fileElements.elements().nextElement(), grouping.getGroupingId(), groups); + totalUsersSkipped = parseGroupSpreadsheet((FormFile) fileElements.elements().nextElement(), + grouping.getGroupingId(), groups); // if branching must use the already specified groups or cannot match to a branch! if (activity.isChosenBranchingActivity()) { for (Map.Entry> groupEntry : groups.entrySet()) { if (!existingGroupNames.contains(groupEntry.getKey())) { StringBuilder groupNamesStrBlder = new StringBuilder(); - for (String name : existingGroupNames) + for (String name : existingGroupNames) { groupNamesStrBlder.append("'").append(name).append("' "); + } String error = getCentralMessageService().getMessage( "error.branching.upload.must.use.existing.groups", new String[] { groupNamesStrBlder.toString() }); return createResponseJSON(true, error.toString(), false, grouping.getGroupingId(), 0, 0); } } } - + //check all users exist and are learners in the specified lesson - for ( Map.Entry> groupEntry : groups.entrySet()) { + for (Map.Entry> groupEntry : groups.entrySet()) { Set logins = groupEntry.getValue(); Iterator iter = logins.iterator(); while (iter.hasNext()) { - String login = iter.next(); - User learner = (User) getUserManagementService().getUserByLogin(login); + String login = iter.next(); + User learner = getUserManagementService().getUserByLogin(login); if (learner == null) { log.warn("Unable to add learner " + login + " to lesson grouping as learner cannot be found."); totalUsersSkipped++; iter.remove(); - - } else if (!getSecurityService().isLessonLearner(lessonId, learner.getUserId(), "be added to grouping", false)) { + + } else if (!getSecurityService().isLessonLearner(lessonId, learner.getUserId(), "be added to grouping", + false)) { //log.warn("Unable to add learner " + login + " to lesson grouping as learner doesn't belong to the lesson."); totalUsersSkipped++; iter.remove(); @@ -446,9 +453,9 @@ return createResponseJSON(false, null, true, grouping.getGroupingId(), totalUsersAdded, totalUsersSkipped); } - private JSONObject createResponseJSON(boolean isError, String errorMessage, boolean reload, Long groupingId, - int totalUsersAdded, int totalUsersSkipped) throws JSONException { - JSONObject responseJSON = new JSONObject(); + private ObjectNode createResponseJSON(boolean isError, String errorMessage, boolean reload, Long groupingId, + int totalUsersAdded, int totalUsersSkipped) { + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); if (isError) { responseJSON.put("result", "FAIL"); responseJSON.put("reload", reload); @@ -464,52 +471,51 @@ /* XLS Version Parse */ private String parseStringCell(HSSFCell cell) { - if (cell != null) { - cell.setCellType(Cell.CELL_TYPE_STRING); - if (cell.getStringCellValue() != null) { - return cell.getStringCellValue().trim(); - } - } - return null; - } + if (cell != null) { + cell.setCellType(Cell.CELL_TYPE_STRING); + if (cell.getStringCellValue() != null) { + return cell.getStringCellValue().trim(); + } + } + return null; + } - public int parseGroupSpreadsheet(FormFile fileItem, Long groupingID, Map> groups) - throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(fileItem.getInputStream()); - HSSFWorkbook wb = new HSSFWorkbook(fs); - HSSFSheet sheet = wb.getSheetAt(0); + public int parseGroupSpreadsheet(FormFile fileItem, Long groupingID, Map> groups) + throws IOException { + POIFSFileSystem fs = new POIFSFileSystem(fileItem.getInputStream()); + HSSFWorkbook wb = new HSSFWorkbook(fs); + HSSFSheet sheet = wb.getSheetAt(0); - int startRow = sheet.getFirstRowNum(); - int endRow = sheet.getLastRowNum(); - int skipped = 0; + int startRow = sheet.getFirstRowNum(); + int endRow = sheet.getLastRowNum(); + int skipped = 0; - for (int i = startRow + 1; i < (endRow + 1); i++) { - HSSFRow row = sheet.getRow(i); - String login = parseStringCell(row.getCell(0)); - if (login != null) { - login = login.trim(); - if (login.length() > 0) { - String groupName = row.getLastCellNum() > 3 ? parseStringCell(row.getCell(3)) : null; - groupName = groupName != null ? groupName.trim() : null; - if (groupName == null || groupName.length() == 0) { + for (int i = startRow + 1; i < (endRow + 1); i++) { + HSSFRow row = sheet.getRow(i); + String login = parseStringCell(row.getCell(0)); + if (login != null) { + login = login.trim(); + if (login.length() > 0) { + String groupName = row.getLastCellNum() > 3 ? parseStringCell(row.getCell(3)) : null; + groupName = groupName != null ? groupName.trim() : null; + if (groupName == null || groupName.length() == 0) { skipped++; - log.warn("Unable to add learner " + login + " for group in related to grouping " + groupingID - + " as group name is missing."); - + GroupingUploadAJAXAction.log.warn("Unable to add learner " + login + + " for group in related to grouping " + groupingID + " as group name is missing."); } else { - Set users = groups.get(groupName); - if (users == null) { - users = new HashSet(); - groups.put(groupName, users); - } - users.add(login); - } - } - } - } - return skipped; - } - + Set users = groups.get(groupName); + if (users == null) { + users = new HashSet(); + groups.put(groupName, users); + } + users.add(login); + } + } + } + } + return skipped; + } + final Comparator ORG_GROUP_COMPARATOR = new Comparator() { @Override public int compare(OrganisationGroup o1, OrganisationGroup o2) { Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/MonitoringAction.java =================================================================== diff -u -ra41ad55b200a8af4eedbbbd22a9169c12a96133c -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/MonitoringAction.java (.../MonitoringAction.java) (revision a41ad55b200a8af4eedbbbd22a9169c12a96133c) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/MonitoringAction.java (.../MonitoringAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -51,9 +51,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.authoring.ObjectExtractor; import org.lamsfoundation.lams.authoring.service.IAuthoringService; import org.lamsfoundation.lams.learning.service.ILearnerService; @@ -91,6 +88,7 @@ import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; import org.lamsfoundation.lams.util.CentralConstants; import org.lamsfoundation.lams.util.DateUtil; +import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.util.ValidationUtil; import org.lamsfoundation.lams.util.WebUtil; @@ -101,8 +99,9 @@ import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.util.HtmlUtils; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; /** * The action servlet that provide all the monitoring functionalities. It interact with the teacher via JSP monitoring @@ -315,7 +314,7 @@ // either all users participate in a lesson, or we split them among instances List lessonInstanceLearners = splitNumberLessons == null ? learners - : new ArrayList((learners.size() / splitNumberLessons) + 1); + : new ArrayList<>((learners.size() / splitNumberLessons) + 1); for (int lessonIndex = 1; lessonIndex <= (splitNumberLessons == null ? 1 : splitNumberLessons); lessonIndex++) { String lessonInstanceName = lessonName; String learnerGroupInstanceName = learnerGroupName; @@ -466,11 +465,12 @@ long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); String dateStr = WebUtil.readStrParam(request, MonitoringConstants.PARAM_LESSON_END_DATE, true); try { - if (dateStr == null || dateStr.length() == 0) + if (dateStr == null || dateStr.length() == 0) { getMonitoringService().suspendLesson(lessonId, getUserId(), true); - else + } else { getMonitoringService().finishLessonOnSchedule(lessonId, MonitoringAction.LESSON_SCHEDULING_DATETIME_FORMAT.parse(dateStr), getUserId()); + } } catch (SecurityException e) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); } @@ -513,7 +513,7 @@ * @throws ServletException */ public ActionForward removeLesson(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException, ServletException { + HttpServletResponse response) throws IOException, ServletException { long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); Integer userId = getUserId(); boolean permanently = WebUtil.readBooleanParam(request, "permanently", false); @@ -525,7 +525,7 @@ return null; } - JSONObject jsonObject = new JSONObject(); + ObjectNode jsonObject = JsonNodeFactory.instance.objectNode(); try { // if this method throws an Exception, there will be no removeLesson=true in the JSON reply @@ -559,7 +559,7 @@ * @throws JSONException */ public ActionForward forceComplete(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException { + HttpServletResponse response) throws IOException, ServletException { // get parameters Long activityId = null; @@ -578,7 +578,7 @@ boolean removeLearnerContent = WebUtil.readBooleanParam(request, MonitoringConstants.PARAM_REMOVE_LEARNER_CONTENT, false); - JSONObject jsonCommand = new JSONObject(); + ObjectNode jsonCommand = JsonNodeFactory.instance.objectNode(); jsonCommand.put("message", getMessageService().getMessage("force.complete.learner.command.message")); jsonCommand.put("redirectURL", "/lams/learning/learner.do?method=joinLesson&lessonID=" + lessonId); String command = jsonCommand.toString(); @@ -636,7 +636,7 @@ * Get learners who are part of the lesson class. */ public ActionForward getLessonLearners(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); if (!getSecurityService().isLessonMonitor(lessonId, getUserId(), "get lesson learners", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); @@ -652,15 +652,15 @@ List learners = getLessonService().getLessonLearners(lessonId, searchPhrase, MonitoringAction.USER_PAGE_SIZE, (pageNumber - 1) * MonitoringAction.USER_PAGE_SIZE, orderAscending); - JSONArray learnersJSON = new JSONArray(); + ArrayNode learnersJSON = JsonNodeFactory.instance.arrayNode(); for (User learner : learners) { - learnersJSON.put(WebUtil.userToJSON(learner)); + learnersJSON.add(WebUtil.userToJSON(learner)); } Integer learnerCount = getLessonService().getCountLessonLearners(lessonId, searchPhrase); - JSONObject responseJSON = new JSONObject(); - responseJSON.put("learners", learnersJSON); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.set("learners", learnersJSON); responseJSON.put("learnerCount", learnerCount); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(responseJSON.toString()); @@ -671,7 +671,7 @@ * Gets learners or monitors of the lesson and organisation containing it. */ public ActionForward getClassMembers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); if (!getSecurityService().isLessonMonitor(lessonId, getUserId(), "get class members", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); @@ -689,7 +689,7 @@ pageNumber = 1; } boolean orderAscending = WebUtil.readBooleanParam(request, "orderAscending", true); - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); // find organisation users and whether they participate in the current lesson Map users = getLessonService().getUsersWithLessonParticipation(lessonId, role, searchPhrase, @@ -702,18 +702,18 @@ responseJSON.put("userCount", userCount); - JSONArray usersJSON = new JSONArray(); + ArrayNode usersJSON = JsonNodeFactory.instance.arrayNode(); for (Entry userEntry : users.entrySet()) { User user = userEntry.getKey(); - JSONObject userJSON = WebUtil.userToJSON(user); + ObjectNode userJSON = WebUtil.userToJSON(user); userJSON.put("classMember", userEntry.getValue()); // teacher can't remove lesson creator and himself from the lesson staff if (isMonitor && (creator.getUserId().equals(user.getUserId()) || currentUserId.equals(user.getUserId()))) { userJSON.put("readonly", true); } - usersJSON.put(userJSON); + usersJSON.add(userJSON); } - responseJSON.put("users", usersJSON); + responseJSON.set("users", usersJSON); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(responseJSON.toString()); @@ -724,8 +724,8 @@ * Gets users in JSON format who are at the given activity at the moment or finished the given lesson. */ public ActionForward getCurrentLearners(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { - JSONArray learnersJSON = new JSONArray(); + HttpServletResponse response) throws IOException { + ArrayNode learnersJSON = JsonNodeFactory.instance.arrayNode(); Integer learnerCount = null; Integer pageNumber = WebUtil.readIntParam(request, "pageNumber", true); @@ -746,7 +746,7 @@ MonitoringAction.USER_PAGE_SIZE, (pageNumber - 1) * MonitoringAction.USER_PAGE_SIZE, orderAscending); for (User learner : learners) { - learnersJSON.put(WebUtil.userToJSON(learner)); + learnersJSON.add(WebUtil.userToJSON(learner)); } learnerCount = getMonitoringService().getCountLearnersCompletedLesson(lessonId); @@ -759,21 +759,21 @@ return null; } - Set activities = new TreeSet(); + Set activities = new TreeSet<>(); activities.add(activityId); List learners = getMonitoringService().getLearnersByActivities(activities.toArray(new Long[] {}), MonitoringAction.USER_PAGE_SIZE, (pageNumber - 1) * MonitoringAction.USER_PAGE_SIZE, orderAscending); for (User learner : learners) { - learnersJSON.put(WebUtil.userToJSON(learner)); + learnersJSON.add(WebUtil.userToJSON(learner)); } learnerCount = getMonitoringService().getCountLearnersCurrentActivities(new Long[] { activityId }) .get(activityId); } - JSONObject responseJSON = new JSONObject(); - responseJSON.put("learners", learnersJSON); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.set("learners", learnersJSON); responseJSON.put("learnerCount", learnerCount); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(responseJSON.toString()); @@ -784,7 +784,7 @@ * Adds/removes learners and monitors to/from lesson class. */ public ActionForward updateLessonClass(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); if (!getSecurityService().isLessonMonitor(lessonId, getUserId(), "update lesson class", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); @@ -829,7 +829,7 @@ String module = WebUtil.readStrParam(request, "module", false); - ArrayList languageCollection = new ArrayList(); + ArrayList languageCollection = new ArrayList<>(); if (module.equals("timechart")) { languageCollection.add(new String("sys.error")); @@ -954,45 +954,47 @@ return mapping.findForward("monitorLesson"); } - + /** * If learning design contains the following activities Grouping->(MCQ or Assessment)->Leader Selection->Scratchie * (potentially with some other gates or activities in the middle), there is a good chance this is a TBL sequence * and all activities must be grouped. */ private boolean isTBLSequence(Long lessonId) { - + Lesson lesson = getLessonService().getLesson(lessonId); Long firstActivityId = lesson.getLearningDesign().getFirstActivity().getActivityId(); //Hibernate CGLIB is failing to load the first activity in the sequence as a ToolActivity Activity firstActivity = getMonitoringService().getActivityById(firstActivityId); - + return verifyNextActivityFitsTbl(firstActivity, "Grouping"); } - + /** * Traverses the learning design verifying it follows typical TBL structure - * + * * @param activity - * @param anticipatedActivity could be either "Grouping", "MCQ or Assessment", "Leaderselection" or "Scratchie" + * @param anticipatedActivity + * could be either "Grouping", "MCQ or Assessment", "Leaderselection" or "Scratchie" */ private boolean verifyNextActivityFitsTbl(Activity activity, String anticipatedActivity) { - + Transition transitionFromActivity = activity.getTransitionFrom(); //TBL can finish with the Scratchie if (transitionFromActivity == null && !"Scratchie".equals(anticipatedActivity)) { return false; } // query activity from DB as transition holds only proxied activity object - Long nextActivityId = transitionFromActivity == null ? null : transitionFromActivity.getToActivity().getActivityId(); + Long nextActivityId = transitionFromActivity == null ? null + : transitionFromActivity.getToActivity().getActivityId(); Activity nextActivity = nextActivityId == null ? null : monitoringService.getActivityById(nextActivityId); - + switch (anticipatedActivity) { case "Grouping": //the first activity should be a grouping if (activity instanceof GroupingActivity) { return verifyNextActivityFitsTbl(nextActivity, "MCQ or Assessment"); - + } else { return verifyNextActivityFitsTbl(nextActivity, "Grouping"); } @@ -1004,7 +1006,7 @@ || CentralConstants.TOOL_SIGNATURE_MCQ .equals(((ToolActivity) activity).getTool().getToolSignature()))) { return verifyNextActivityFitsTbl(nextActivity, "Leaderselection"); - + } else { return verifyNextActivityFitsTbl(nextActivity, "MCQ or Assessment"); } @@ -1014,20 +1016,20 @@ if (activity.isToolActivity() && CentralConstants.TOOL_SIGNATURE_LEADERSELECTION .equals(((ToolActivity) activity).getTool().getToolSignature())) { return verifyNextActivityFitsTbl(nextActivity, "Scratchie"); - + } else { return verifyNextActivityFitsTbl(nextActivity, "Leaderselection"); } - + case "Scratchie": //the fourth activity shall be Scratchie if (activity.isToolActivity() && CentralConstants.TOOL_SIGNATURE_SCRATCHIE .equals(((ToolActivity) activity).getTool().getToolSignature())) { return true; - + } else if (nextActivity == null) { return false; - + } else { return verifyNextActivityFitsTbl(nextActivity, "Scratchie"); } @@ -1041,7 +1043,7 @@ * Gets users whose progress bars will be displayed in Learner tab in Monitor. */ public ActionForward getLearnerProgressPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); if (!getSecurityService().isLessonMonitor(lessonId, getUserId(), "get learner progress page", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); @@ -1060,9 +1062,9 @@ List learners = isProgressSorted ? getMonitoringService().getLearnersByMostProgress(lessonId, searchPhrase, 10, (pageNumber - 1) * 10) : getLessonService().getLessonLearners(lessonId, searchPhrase, 10, (pageNumber - 1) * 10, true); - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); for (User learner : learners) { - responseJSON.append("learners", WebUtil.userToJSON(learner)); + responseJSON.withArray("learners").add(WebUtil.userToJSON(learner)); } // get all possible learners matching the given phrase, if any; used for max page number @@ -1076,7 +1078,7 @@ * Produces data to update Lesson tab in Monitor. */ public ActionForward getLessonDetails(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); HttpSession ss = SessionManager.getSession(); UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); @@ -1086,7 +1088,7 @@ return null; } - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); Lesson lesson = getLessonService().getLesson(lessonId); LearningDesign learningDesign = lesson.getLearningDesign(); @@ -1104,25 +1106,25 @@ Date finishDate = lesson.getScheduleEndDate(); DateFormat indfm = null; - if ( startOrScheduleDate != null || finishDate != null ) + if (startOrScheduleDate != null || finishDate != null) { indfm = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", userLocale); - + } + if (startOrScheduleDate != null) { Date tzStartDate = DateUtil.convertToTimeZoneFromDefault(user.getTimeZone(), startOrScheduleDate); responseJSON.put("startDate", indfm.format(tzStartDate) + " " + user.getTimeZone().getDisplayName(userLocale)); } - if ( finishDate != null ) { + if (finishDate != null) { Date tzFinishDate = DateUtil.convertToTimeZoneFromDefault(user.getTimeZone(), finishDate); responseJSON.put("finishDate", - indfm.format(tzFinishDate) + " " + user.getTimeZone().getDisplayName(userLocale)); + indfm.format(tzFinishDate) + " " + user.getTimeZone().getDisplayName(userLocale)); } - + List contributeActivities = getContributeActivities(lessonId, false); if (contributeActivities != null) { - Gson gson = new GsonBuilder().create(); - responseJSON.put("contributeActivities", new JSONArray(gson.toJson(contributeActivities))); + responseJSON.set("contributeActivities", JsonUtil.readArray(contributeActivities)); } response.setContentType("application/json;charset=utf-8"); @@ -1131,7 +1133,7 @@ } public ActionForward getLessonChartData(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); Integer possibleLearnersCount = getLessonService().getCountLessonLearners(lessonId, null); @@ -1140,21 +1142,21 @@ - completedLearnersCount; Integer notCompletedLearnersCount = possibleLearnersCount - completedLearnersCount - startedLearnersCount; - JSONObject responseJSON = new JSONObject(); - JSONObject notStartedJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + ObjectNode notStartedJSON = JsonNodeFactory.instance.objectNode(); notStartedJSON.put("name", getMessageService().getMessage("lesson.chart.not.completed")); notStartedJSON.put("value", Math.round(notCompletedLearnersCount.doubleValue() / possibleLearnersCount * 100)); - responseJSON.append("data", notStartedJSON); + responseJSON.withArray("data").add(notStartedJSON); - JSONObject startedJSON = new JSONObject(); + ObjectNode startedJSON = JsonNodeFactory.instance.objectNode(); startedJSON.put("name", getMessageService().getMessage("lesson.chart.started")); startedJSON.put("value", Math.round((startedLearnersCount.doubleValue()) / possibleLearnersCount * 100)); - responseJSON.append("data", startedJSON); + responseJSON.withArray("data").add(startedJSON); - JSONObject completedJSON = new JSONObject(); + ObjectNode completedJSON = JsonNodeFactory.instance.objectNode(); completedJSON.put("name", getMessageService().getMessage("lesson.chart.completed")); completedJSON.put("value", Math.round(completedLearnersCount.doubleValue() / possibleLearnersCount * 100)); - responseJSON.append("data", completedJSON); + responseJSON.withArray("data").add(completedJSON); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(responseJSON.toString()); @@ -1166,7 +1168,7 @@ */ @SuppressWarnings("unchecked") public ActionForward getLessonProgress(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); Integer monitorUserId = getUserId(); if (!getSecurityService().isLessonMonitor(lessonId, monitorUserId, "get lesson progress", false)) { @@ -1179,7 +1181,7 @@ LearningDesign learningDesign = lesson.getLearningDesign(); String contentFolderId = learningDesign.getContentFolderID(); - Set activities = new HashSet(); + Set activities = new HashSet<>(); // filter activities that are interesting for further processing for (Activity activity : (Set) learningDesign.getActivities()) { if (activity.isSequenceActivity()) { @@ -1190,11 +1192,10 @@ activities.add(getMonitoringService().getActivityById(activity.getActivityId())); } - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); List contributeActivities = getContributeActivities(lessonId, true); if (contributeActivities != null) { - Gson gson = new GsonBuilder().create(); - responseJSON.put("contributeActivities", new JSONArray(gson.toJson(contributeActivities))); + responseJSON.set("contributeActivities", JsonUtil.readArray(contributeActivities)); } // check if the searched learner has started the lesson @@ -1205,8 +1206,8 @@ } // Fetch number of learners at each activity - ArrayList activityIds = new ArrayList(); - Set leaders = new TreeSet(); + ArrayList activityIds = new ArrayList<>(); + Set leaders = new TreeSet<>(); for (Activity activity : activities) { activityIds.add(activity.getActivityId()); // find leaders from Leader Selection Tool @@ -1222,10 +1223,10 @@ Map learnerCounts = getMonitoringService() .getCountLearnersCurrentActivities(activityIds.toArray(new Long[activityIds.size()])); - JSONArray activitiesJSON = new JSONArray(); + ArrayNode activitiesJSON = JsonNodeFactory.instance.arrayNode(); for (Activity activity : activities) { Long activityId = activity.getActivityId(); - JSONObject activityJSON = new JSONObject(); + ObjectNode activityJSON = JsonNodeFactory.instance.objectNode(); activityJSON.put("id", activityId); activityJSON.put("uiid", activity.getActivityUIID()); activityJSON.put("title", activity.getTitle()); @@ -1288,23 +1289,23 @@ // parse learners into JSON format if (!latestLearners.isEmpty()) { - JSONArray learnersJSON = new JSONArray(); + ArrayNode learnersJSON = JsonNodeFactory.instance.arrayNode(); for (User learner : latestLearners) { - JSONObject userJSON = WebUtil.userToJSON(learner); + ObjectNode userJSON = WebUtil.userToJSON(learner); if (leaders.contains(learner.getUserId().longValue())) { userJSON.put("leader", true); } - learnersJSON.put(userJSON); + learnersJSON.add(userJSON); } - activityJSON.put("learners", learnersJSON); + activityJSON.set("learners", learnersJSON); } } activityJSON.put("learnerCount", learnerCount); - activitiesJSON.put(activityJSON); + activitiesJSON.add(activityJSON); } - responseJSON.put("activities", activitiesJSON); + responseJSON.set("activities", activitiesJSON); // find learners who completed the lesson List completedLearners = getMonitoringService().getLearnersLatestCompleted(lessonId, @@ -1323,25 +1324,25 @@ completedLearners, MonitoringAction.LATEST_LEARNER_PROGRESS_LESSON_DISPLAY_LIMIT); } for (User learner : completedLearners) { - JSONObject learnerJSON = WebUtil.userToJSON(learner); + ObjectNode learnerJSON = WebUtil.userToJSON(learner); // no more details are needed for learners who completed the lesson - responseJSON.append("completedLearners", learnerJSON); + responseJSON.withArray("completedLearners").add(learnerJSON); } responseJSON.put("numberPossibleLearners", getLessonService().getCountLessonLearners(lessonId, null)); // on first fetch get transitions metadata so Monitoring can set their SVG elems IDs if (WebUtil.readBooleanParam(request, "getTransitions", false)) { - JSONArray transitions = new JSONArray(); + ArrayNode transitions = JsonNodeFactory.instance.arrayNode(); for (Transition transition : (Set) learningDesign.getTransitions()) { - JSONObject transitionJSON = new JSONObject(); + ObjectNode transitionJSON = JsonNodeFactory.instance.objectNode(); transitionJSON.put("uiid", transition.getTransitionUIID()); transitionJSON.put("fromID", transition.getFromActivity().getActivityId()); transitionJSON.put("toID", transition.getToActivity().getActivityId()); - transitions.put(transitionJSON); + transitions.add(transitionJSON); } - responseJSON.put("transitions", transitions); + responseJSON.set("transitions", transitions); } response.setContentType("application/json;charset=utf-8"); @@ -1376,13 +1377,13 @@ true); } - JSONArray responseJSON = new JSONArray(); + ArrayNode responseJSON = JsonNodeFactory.instance.arrayNode(); for (User user : users) { - JSONObject userJSON = new JSONObject(); + ObjectNode userJSON = JsonNodeFactory.instance.objectNode(); userJSON.put("label", user.getFirstName() + " " + user.getLastName() + " " + user.getLogin()); userJSON.put("value", user.getUserId()); - responseJSON.put(userJSON); + responseJSON.add(userJSON); } response.setContentType("application/json;charset=utf-8"); @@ -1612,9 +1613,9 @@ } return null; } - + /** - * Set whether or not the activity scores / gradebook values are shown to the learner at the end of the lesson. + * Set whether or not the activity scores / gradebook values are shown to the learner at the end of the lesson. * Expects parameters lessonID and presenceAvailable. */ public ActionForward gradebookOnComplete(ActionMapping mapping, ActionForm form, HttpServletRequest request, @@ -1664,7 +1665,7 @@ private List parseUserList(HttpServletRequest request, String paramName, Collection users) { String userIdList = request.getParameter(paramName); String[] userIdArray = userIdList.split(","); - List result = new ArrayList(userIdArray.length); + List result = new ArrayList<>(userIdArray.length); for (User user : users) { Integer userId = user.getUserId(); @@ -1685,7 +1686,7 @@ Lesson lesson = getLessonService().getLesson(lessonId); if (contributeActivities != null) { - List resultContributeActivities = new ArrayList(); + List resultContributeActivities = new ArrayList<>(); for (ContributeActivityDTO contributeActivity : contributeActivities) { if (contributeActivity.getContributeEntries() != null) { Iterator entryIterator = contributeActivity @@ -1696,7 +1697,7 @@ // extra filtering for chosen branching: do not show in Sequence tab if all users were assigned if (skipCompletedBranching && ContributionTypes.CHOSEN_BRANCHING.equals(contributeEntry.getContributionType())) { - Set learners = new HashSet(lesson.getLessonClass().getLearners()); + Set learners = new HashSet<>(lesson.getLessonClass().getLearners()); ChosenBranchingActivity branching = (ChosenBranchingActivity) getMonitoringService() .getActivityById(contributeActivity.getActivityID()); for (SequenceActivity branch : (Set) branching.getActivities()) { @@ -1732,7 +1733,7 @@ */ private static List insertHighlightedLearner(User searchedLearner, List latestLearners, int limit) { latestLearners.remove(searchedLearner); - LinkedList updatedLatestLearners = new LinkedList(latestLearners); + LinkedList updatedLatestLearners = new LinkedList<>(latestLearners); updatedLatestLearners.addFirst(searchedLearner); if (updatedLatestLearners.size() > limit) { updatedLatestLearners.removeLast(); Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java =================================================================== diff -u -rc2585242b3a8ef9215af42e9644c15992cc6355b -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision c2585242b3a8ef9215af42e9644c15992cc6355b) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -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; @@ -49,9 +50,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.ConfidenceLevelDTO; import org.lamsfoundation.lams.events.IEventNotificationService; import org.lamsfoundation.lams.gradebook.service.IGradebookService; @@ -115,6 +113,11 @@ import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.util.NumberUtil; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Andrey Balan */ @@ -811,9 +814,9 @@ } 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()) { @@ -880,11 +883,11 @@ public AssessmentResult getLastAssessmentResult(Long assessmentUid, Long userId) { return assessmentResultDao.getLastAssessmentResult(assessmentUid, userId); } - + @Override public Boolean isLastAttemptFinishedByUser(AssessmentUser user) { return assessmentResultDao.isLastAttemptFinishedByUser(user); - } + } @Override public AssessmentResult getLastFinishedAssessmentResult(Long assessmentUid, Long userId) { @@ -1001,7 +1004,7 @@ @Override public List getReflectList(Long contentId) { - List reflectList = new LinkedList(); + List reflectList = new LinkedList<>(); List sessionList = assessmentSessionDao.getByContentId(contentId); for (AssessmentSession session : sessionList) { @@ -1052,7 +1055,7 @@ @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) { @@ -1115,7 +1118,7 @@ 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()) { @@ -1163,7 +1166,7 @@ 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()); @@ -1176,12 +1179,12 @@ } //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())) { @@ -1216,27 +1219,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 +1259,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 +1315,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) { @@ -1329,7 +1332,7 @@ 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,7 +1358,7 @@ 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, @@ -1444,7 +1447,7 @@ // ------------------------------------------------------------------ // -------------- Second tab: Question Summary ---------------------- - ArrayList questionSummaryTab = new ArrayList(); + ArrayList questionSummaryTab = new ArrayList<>(); // Create the question summary ExcelCell[] summaryTitle = new ExcelCell[1]; @@ -1500,15 +1503,15 @@ || 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) { @@ -1671,7 +1674,7 @@ // ------------------------------------------------------------------ // -------------- Third tab: User Summary --------------------------- - ArrayList userSummaryTab = new ArrayList(); + ArrayList userSummaryTab = new ArrayList<>(); // Create the question summary ExcelCell[] userSummaryTitle = new ExcelCell[1]; @@ -1693,7 +1696,7 @@ 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; @@ -1749,7 +1752,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); } @@ -2013,11 +2016,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); } @@ -2061,7 +2064,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())) { @@ -2107,7 +2110,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()) @@ -2118,7 +2121,7 @@ } // create list of added references - List addedReferences = new ArrayList(); + List addedReferences = new ArrayList<>(); for (QuestionReference newReference : newReferences) { boolean isNewReferenceMetInOldReferences = false; @@ -2227,7 +2230,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() @@ -2375,8 +2378,8 @@ private LinkedHashMap getMarksSummaryForSession(List userDtos, float minGrade, float maxGrade, Integer numBuckets) { - LinkedHashMap summary = new LinkedHashMap(); - TreeMap inProgress = new TreeMap(); + LinkedHashMap summary = new LinkedHashMap<>(); + TreeMap inProgress = new TreeMap<>(); if (numBuckets == null) { numBuckets = 10; @@ -2946,99 +2949,106 @@ * 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 = getUserCreatedAssessment(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) @@ -3047,22 +3057,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); } @@ -3074,23 +3083,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); } @@ -3112,10 +3121,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); } @@ -3132,7 +3141,7 @@ } @Override - public void notifyLearnersOnAnswerDisclose(long toolContentId) throws JSONException { + public void notifyLearnersOnAnswerDisclose(long toolContentId) { List sessions = assessmentSessionDao.getByContentId(toolContentId); Set userIds = new HashSet(); for (AssessmentSession session : sessions) { @@ -3141,7 +3150,7 @@ } } - JSONObject jsonCommand = new JSONObject(); + ObjectNode jsonCommand = JsonNodeFactory.instance.objectNode(); jsonCommand.put("hookTrigger", "assessment-results-refresh-" + toolContentId); learnerService.createCommandForLearners(toolContentId, userIds, jsonCommand.toString()); } Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/IAssessmentService.java =================================================================== diff -u -ra05411c3da91b4b357b1615cc5361ea25e3614da -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/IAssessmentService.java (.../IAssessmentService.java) (revision a05411c3da91b4b357b1615cc5361ea25e3614da) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/IAssessmentService.java (.../IAssessmentService.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -82,12 +82,12 @@ */ void copyAnswersFromLeader(AssessmentUser user, AssessmentUser leader) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException; - + List getConfidenceLevels(Long toolSessionId); /** * Stores date when user has started activity with time limit. - * + * * @param assessmentUid * @param userId */ @@ -96,7 +96,7 @@ /** * Calculates how many seconds left till the time limit will expire. If it's expired already - returns 1 in order to * show learning.jsp and autosubmit results. - * + * * @param assessment * @param user * @return @@ -122,7 +122,7 @@ String searchString); int getCountUsersBySession(Long sessionId, String searchString); - + int getCountUsersByContentId(Long contentId); List getPagedUsersBySessionAndQuestion(Long sessionId, Long questionUid, int page, int size, @@ -159,14 +159,14 @@ * @return */ AssessmentUser getUserCreatedAssessment(Long userID, Long contentId); - + /** * Get user by given userID and toolContentID. * * @param long1 * @return */ - AssessmentUser getUserByIdAndContent(Long userID, Long contentId); + AssessmentUser getUserByIdAndContent(Long userID, Long contentId); /** * Get user by sessionID and UserID @@ -185,6 +185,11 @@ void saveOrUpdateAssessment(Assessment Assessment); /** + * Update assessment question into database. + */ + void updateAssessmentQuestion(AssessmentQuestion question); + + /** * Delete resoruce question from database. * * @param uid @@ -208,7 +213,7 @@ * @return */ AssessmentSession getSessionBySessionId(Long sessionId); - + /** * Get all assessment toolSessions by toolContentId * @@ -254,6 +259,14 @@ AssessmentResult getLastAssessmentResult(Long assessmentUid, Long userId); /** + * Checks whether the last attempt started by user is finished. + * + * @param user + * @return true if user has finished it, false otherwise + */ + Boolean isLastAttemptFinishedByUser(AssessmentUser user); + + /** * Return the latest *finished* result. * * @param assessmentUid @@ -314,7 +327,7 @@ * @return */ Integer getLastFinishedAssessmentResultTimeTaken(Long assessmentUid, Long userId); - + /** * Count how many last finished attempts selected specified option. */ @@ -372,7 +385,7 @@ /** * Set userFinished to false - * + * * @param toolSessionId * @param userId */ @@ -430,25 +443,28 @@ LinkedHashMap exportSummary(Assessment assessment, List sessionDtos, boolean showUserNames); - /** + /** * Gets the basic statistics for the grades for the Leaders when an Assessment is done using * Group Leaders. So the averages, etc are for the whole Assessment, not for a Group. + * * @param contentId * @return */ LeaderResultsDTO getLeaderResultsDTOForLeaders(Long contentId); - - /** + + /** * Prepares data for the marks summary graph on the statistics page + * * @param assessment * @param sessionDtos * @return */ List getMarksArray(Long sessionId); - /** - * Prepares data for the marks summary graph on the statistics page, using the grades for the Leaders + /** + * Prepares data for the marks summary graph on the statistics page, using the grades for the Leaders * when an Assessment is done using Group Leaders. So the grades are for the whole Assessment, not for a Group. + * * @param assessment * @param sessionDtos * @return @@ -461,7 +477,7 @@ /** * Get a message from the language files with the given key - * + * * @param key * @return */ @@ -474,10 +490,10 @@ * @return */ boolean isGroupedActivity(long toolContentID); - + /** * Audit log the teacher has started editing activity in monitor. - * + * * @param toolContentID */ void auditLogStartEditingActivityInMonitor(long toolContentID); @@ -521,6 +537,14 @@ List deletedReferences); void releaseFromCache(Object object); - + Long getPortraitId(Long userId); + + AssessmentQuestion getAssessmentQuestionByUid(Long questionUid); + + /** + * Sends a websocket command to learners who have assessment results open + * to refresh page because new data is available + */ + void notifyLearnersOnAnswerDisclose(long toolContentId); } Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/AuthoringAction.java =================================================================== diff -u -rb32657226efa9a6bb90a1c12a69e82a5acde2e80 -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/AuthoringAction.java (.../AuthoringAction.java) (revision b32657226efa9a6bb90a1c12a69e82a5acde2e80) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/AuthoringAction.java (.../AuthoringAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -90,7 +90,7 @@ import org.springframework.web.context.support.WebApplicationContextUtils; import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.converters.reflection.SunUnsafeReflectionProvider; +import com.thoughtworks.xstream.io.xml.StaxDriver; import com.thoughtworks.xstream.security.AnyTypePermission; /** @@ -119,7 +119,7 @@ assessment.setDefineLater(true); service.saveOrUpdateAssessment(assessment); - + //audit log the teacher has started editing activity in monitor service.auditLogStartEditingActivityInMonitor(contentId); @@ -225,7 +225,7 @@ AssessmentForm assessmentForm = (AssessmentForm) form; // initial Session Map - SessionMap sessionMap = new SessionMap(); + SessionMap sessionMap = new SessionMap<>(); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); assessmentForm.setSessionMapID(sessionMap.getSessionID()); @@ -246,11 +246,11 @@ AuthoringAction.log.error(e); throw new ServletException(e); } - + if (assessment.getQuestions() != null) { questions = new ArrayList(assessment.getQuestions()); } else { - questions = new ArrayList(); + questions = new ArrayList<>(); } // init assessment question list @@ -339,9 +339,8 @@ } } - Set oldQuestions = (assessmentPO == null) ? new HashSet() - : assessmentPO.getQuestions(); - Set oldReferences = (assessmentPO == null) ? new HashSet() + Set oldQuestions = (assessmentPO == null) ? new HashSet<>() : assessmentPO.getQuestions(); + Set oldReferences = (assessmentPO == null) ? new HashSet<>() : assessmentPO.getQuestionReferences(); AssessmentUser assessmentUser = null; @@ -386,7 +385,7 @@ // ************************* Handle assessment questions ******************* // Handle assessment questions - Set questions = new LinkedHashSet(); + Set questions = new LinkedHashSet<>(); Set newQuestions = getQuestionList(sessionMap); for (AssessmentQuestion question : newQuestions) { removeNewLineCharacters(question); @@ -464,7 +463,7 @@ questionForm.setPenaltyFactor("0"); questionForm.setAnswerRequired(true); - List optionList = new ArrayList(); + List optionList = new ArrayList<>(); for (int i = 0; i < AssessmentConstants.INITIAL_OPTIONS_NUMBER; i++) { AssessmentQuestionOption option = new AssessmentQuestionOption(); option.setSequenceId(i + 1); @@ -473,7 +472,7 @@ } request.setAttribute(AssessmentConstants.ATTR_OPTION_LIST, optionList); - List unitList = new ArrayList(); + List unitList = new ArrayList<>(); AssessmentUnit unit = new AssessmentUnit(); unit.setSequenceId(1); unit.setMultiplier(1); @@ -515,7 +514,7 @@ AssessmentQuestion question = null; if (questionIdx != -1) { SortedSet assessmentList = getQuestionList(sessionMap); - List rList = new ArrayList(assessmentList); + List rList = new ArrayList<>(assessmentList); question = rList.get(questionIdx); if (question != null) { AssessmentQuestionForm questionForm = (AssessmentQuestionForm) form; @@ -612,8 +611,7 @@ String correctAnswer = null; if (question.getAnswers() != null) { - TreeSet optionList = new TreeSet( - new SequencableComparator()); + TreeSet optionList = new TreeSet<>(new SequencableComparator()); int orderId = 0; for (Answer answer : question.getAnswers()) { String answerText = QuestionParser.processHTMLField(answer.getText(), false, contentFolderID, @@ -673,8 +671,7 @@ } questionGrade = new Double(Math.round(totalScore)).intValue(); - TreeSet optionList = new TreeSet( - new SequencableComparator()); + TreeSet optionList = new TreeSet<>(new SequencableComparator()); int orderId = 1; for (Answer answer : question.getAnswers()) { String answerText = answer.getText(); @@ -732,8 +729,7 @@ } questionGrade = new Double(Math.round(totalScore)).intValue(); - TreeSet optionList = new TreeSet( - new SequencableComparator()); + TreeSet optionList = new TreeSet<>(new SequencableComparator()); int orderId = 1; for (int answerIndex = 0; answerIndex < question.getAnswers().size(); answerIndex++) { // QTI allows answers without a match, but LAMS assessment tool does not @@ -767,8 +763,7 @@ String correctAnswer = null; if (question.getAnswers() != null) { - TreeSet optionList = new TreeSet( - new SequencableComparator()); + TreeSet optionList = new TreeSet<>(new SequencableComparator()); int orderId = 1; for (Answer answer : question.getAnswers()) { String answerText = QuestionParser.processHTMLField(answer.getText(), false, contentFolderID, @@ -843,10 +838,10 @@ .getAttribute(sessionMapID); SortedSet questionList = getQuestionList(sessionMap); - List questions = new LinkedList(); + List questions = new LinkedList<>(); for (AssessmentQuestion assessmentQuestion : questionList) { Question question = new Question(); - List answers = new ArrayList(); + List answers = new ArrayList<>(); switch (assessmentQuestion.getType()) { @@ -863,10 +858,12 @@ } Float correctAnswerScore = correctAnswerCount > 0 - ? new Integer(100 / correctAnswerCount).floatValue() : null; + ? new Integer(100 / correctAnswerCount).floatValue() + : null; int incorrectAnswerCount = assessmentQuestion.getOptions().size() - correctAnswerCount; Float incorrectAnswerScore = incorrectAnswerCount > 0 - ? new Integer(-100 / incorrectAnswerCount).floatValue() : null; + ? new Integer(-100 / incorrectAnswerCount).floatValue() + : null; for (AssessmentQuestionOption assessmentAnswer : assessmentQuestion.getOptions()) { Answer answer = new Answer(); @@ -888,8 +885,9 @@ boolean isCorrectAnswer = assessmentAnswer.getGrade() == 1F; answer.setText(assessmentAnswer.getOptionString()); - answer.setScore(isCorrectAnswer - ? new Integer(assessmentQuestion.getDefaultGrade()).floatValue() : 0); + answer.setScore( + isCorrectAnswer ? new Integer(assessmentQuestion.getDefaultGrade()).floatValue() + : 0); answer.setFeedback(isCorrectAnswer ? assessmentQuestion.getFeedbackOnCorrect() : assessmentQuestion.getFeedbackOnIncorrect()); @@ -1024,7 +1022,7 @@ int questionIdx = NumberUtils.toInt(request.getParameter(AssessmentConstants.PARAM_QUESTION_INDEX), -1); if (questionIdx != -1) { SortedSet questionList = getQuestionList(sessionMap); - List rList = new ArrayList(questionList); + List rList = new ArrayList<>(questionList); AssessmentQuestion question = rList.remove(questionIdx); questionList.clear(); questionList.addAll(rList); @@ -1146,7 +1144,7 @@ .toInt(request.getParameter(AssessmentConstants.PARAM_QUESTION_REFERENCE_INDEX), -1); if (questionReferenceIdx != -1) { SortedSet questionReferences = getQuestionReferences(sessionMap); - List rList = new ArrayList(questionReferences); + List rList = new ArrayList<>(questionReferences); QuestionReference questionReference = rList.remove(questionReferenceIdx); questionReferences.clear(); questionReferences.addAll(rList); @@ -1200,7 +1198,7 @@ .toInt(request.getParameter(AssessmentConstants.PARAM_QUESTION_REFERENCE_INDEX), -1); if (questionReferenceIdx != -1) { SortedSet references = getQuestionReferences(sessionMap); - List rList = new ArrayList(references); + List rList = new ArrayList<>(references); // get current and the target item, and switch their sequnece QuestionReference reference = rList.get(questionReferenceIdx); QuestionReference repReference; @@ -1244,10 +1242,10 @@ request.setAttribute(AssessmentConstants.ATTR_SESSION_MAP_ID, sessionMapID); SortedSet oldQuestions = getQuestionList(sessionMap); - List toolsErrorMsgs = new ArrayList(); + List toolsErrorMsgs = new ArrayList<>(); try { File designFile = null; - Map params = new HashMap(); + Map params = new HashMap<>(); String filename = null; String uploadPath = FileUtil.createTempDirectory("_uploaded_2questions_xml"); @@ -1275,7 +1273,8 @@ String filename2 = designFile.getName(); String fileExtension = (filename2 != null) && (filename2.length() >= 4) - ? filename2.substring(filename2.length() - 4) : ""; + ? filename2.substring(filename2.length() - 4) + : ""; if (!fileExtension.equalsIgnoreCase(".xml")) { throw new RuntimeException("Wrong file extension. Xml is expected"); } @@ -1326,14 +1325,14 @@ String errors = null; if (assessment != null) { try { - ArrayList questionsToExport = new ArrayList(); + ArrayList questionsToExport = new ArrayList<>(); for (AssessmentQuestion question : getQuestionList(sessionMap)) { AssessmentQuestion clonedQuestion = (AssessmentQuestion) question.clone(); questionsToExport.add(clonedQuestion); } // exporting XML - XStream designXml = new XStream(new SunUnsafeReflectionProvider()); + XStream designXml = new XStream(new StaxDriver()); designXml.addPermission(AnyTypePermission.ANY); String resultedXml = designXml.toXML(questionsToExport); @@ -1425,7 +1424,7 @@ Set optionList = getOptionsFromRequest(request, false); int optionIndex = NumberUtils.toInt(request.getParameter(AssessmentConstants.PARAM_OPTION_INDEX), -1); if (optionIndex != -1) { - List rList = new ArrayList(optionList); + List rList = new ArrayList<>(optionList); AssessmentQuestionOption question = rList.remove(optionIndex); optionList.clear(); optionList.addAll(rList); @@ -1472,7 +1471,7 @@ int optionIndex = NumberUtils.toInt(request.getParameter(AssessmentConstants.PARAM_OPTION_INDEX), -1); if (optionIndex != -1) { - List rList = new ArrayList(optionList); + List rList = new ArrayList<>(optionList); // get current and the target item, and switch their sequnece AssessmentQuestionOption option = rList.get(optionIndex); @@ -1543,8 +1542,7 @@ Assessment assessment = assessmentForm.getAssessment(); // initial Overall feedbacks list - SortedSet overallFeedbackList = new TreeSet( - new SequencableComparator()); + SortedSet overallFeedbackList = new TreeSet<>(new SequencableComparator()); if (!assessment.getOverallFeedbacks().isEmpty()) { overallFeedbackList.addAll(assessment.getOverallFeedbacks()); } else { @@ -1598,12 +1596,12 @@ private void reinitializeAvailableQuestions(SessionMap sessionMap) { SortedSet bankQuestions = getQuestionList(sessionMap); SortedSet references = getQuestionReferences(sessionMap); - Set questionsFromList = new LinkedHashSet(); + Set questionsFromList = new LinkedHashSet<>(); for (QuestionReference reference : references) { questionsFromList.add(reference.getQuestion()); } - Set availableQuestions = new TreeSet(new SequencableComparator()); + Set availableQuestions = new TreeSet<>(new SequencableComparator()); availableQuestions.addAll(CollectionUtils.subtract(bankQuestions, questionsFromList)); sessionMap.put(AssessmentConstants.ATTR_AVAILABLE_QUESTIONS, availableQuestions); @@ -1628,7 +1626,7 @@ SortedSet list = (SortedSet) sessionMap .get(AssessmentConstants.ATTR_QUESTION_LIST); if (list == null) { - list = new TreeSet(new SequencableComparator()); + list = new TreeSet<>(new SequencableComparator()); sessionMap.put(AssessmentConstants.ATTR_QUESTION_LIST, list); } return list; @@ -1644,7 +1642,7 @@ SortedSet list = (SortedSet) sessionMap .get(AssessmentConstants.ATTR_QUESTION_REFERENCES); if (list == null) { - list = new TreeSet(new SequencableComparator()); + list = new TreeSet<>(new SequencableComparator()); sessionMap.put(AssessmentConstants.ATTR_QUESTION_REFERENCES, list); } return list; @@ -1810,7 +1808,7 @@ question.setSequenceId(maxSeq); questionList.add(question); } else { // edit - List rList = new ArrayList(questionList); + List rList = new ArrayList<>(questionList); question = rList.get(questionIdx); } short type = questionForm.getQuestionType(); @@ -1826,7 +1824,8 @@ if (type == AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE) { question.setMultipleAnswersAllowed(questionForm.isMultipleAnswersAllowed()); boolean incorrectAnswerNullifiesMark = questionForm.isMultipleAnswersAllowed() - ? questionForm.isIncorrectAnswerNullifiesMark() : false; + ? questionForm.isIncorrectAnswerNullifiesMark() + : false; question.setIncorrectAnswerNullifiesMark(incorrectAnswerNullifiesMark); question.setPenaltyFactor(Float.parseFloat(questionForm.getPenaltyFactor())); question.setShuffle(questionForm.isShuffle()); @@ -1871,7 +1870,7 @@ || (type == AssessmentConstants.QUESTION_TYPE_NUMERICAL) || (type == AssessmentConstants.QUESTION_TYPE_MARK_HEDGING)) { Set optionList = getOptionsFromRequest(request, true); - Set options = new LinkedHashSet(); + Set options = new LinkedHashSet<>(); int seqId = 0; for (AssessmentQuestionOption option : optionList) { option.setSequenceId(seqId++); @@ -1882,7 +1881,7 @@ // set units if (type == AssessmentConstants.QUESTION_TYPE_NUMERICAL) { Set unitList = getUnitsFromRequest(request, true); - Set units = new LinkedHashSet(); + Set units = new LinkedHashSet<>(); int seqId = 0; for (AssessmentUnit unit : unitList) { unit.setSequenceId(seqId++); @@ -1933,8 +1932,7 @@ int questionType = WebUtil.readIntParam(request, AssessmentConstants.ATTR_QUESTION_TYPE); Integer correctOptionIndex = (paramMap.get(AssessmentConstants.ATTR_OPTION_CORRECT) == null) ? null : NumberUtils.toInt(paramMap.get(AssessmentConstants.ATTR_OPTION_CORRECT)); - TreeSet optionList = new TreeSet( - new SequencableComparator()); + TreeSet optionList = new TreeSet<>(new SequencableComparator()); for (int i = 0; i < count; i++) { if ((questionType == AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE) || (questionType == AssessmentConstants.QUESTION_TYPE_SHORT_ANSWER)) { @@ -2033,7 +2031,7 @@ Map paramMap = splitRequestParameter(request, AssessmentConstants.ATTR_UNIT_LIST); int count = NumberUtils.toInt(paramMap.get(AssessmentConstants.ATTR_UNIT_COUNT)); - TreeSet unitList = new TreeSet(new SequencableComparator()); + TreeSet unitList = new TreeSet<>(new SequencableComparator()); for (int i = 0; i < count; i++) { String unitStr = paramMap.get(AssessmentConstants.ATTR_UNIT_UNIT_PREFIX + i); if (StringUtils.isBlank(unitStr) && isForSaving) { @@ -2060,8 +2058,7 @@ private TreeSet getOverallFeedbacksFromRequest(HttpServletRequest request, boolean skipBlankOverallFeedbacks) { int count = NumberUtils.toInt(request.getParameter(AssessmentConstants.ATTR_OVERALL_FEEDBACK_COUNT)); - TreeSet overallFeedbackList = new TreeSet( - new SequencableComparator()); + TreeSet overallFeedbackList = new TreeSet<>(new SequencableComparator()); for (int i = 0; i < count; i++) { String gradeBoundaryStr = request .getParameter(AssessmentConstants.ATTR_OVERALL_FEEDBACK_GRADE_BOUNDARY_PREFIX + i); @@ -2094,8 +2091,7 @@ Map paramMap = splitRequestParameter(request, AssessmentConstants.ATTR_OVERALL_FEEDBACK_LIST); int count = NumberUtils.toInt(paramMap.get(AssessmentConstants.ATTR_OVERALL_FEEDBACK_COUNT)); - TreeSet overallFeedbackList = new TreeSet( - new SequencableComparator()); + TreeSet overallFeedbackList = new TreeSet<>(new SequencableComparator()); for (int i = 0; i < count; i++) { String gradeBoundaryStr = paramMap.get(AssessmentConstants.ATTR_OVERALL_FEEDBACK_GRADE_BOUNDARY_PREFIX + i); String feedback = paramMap.get(AssessmentConstants.ATTR_OVERALL_FEEDBACK_FEEDBACK_PREFIX + i); @@ -2131,7 +2127,7 @@ } String[] params = list.split("&"); - Map paramMap = new HashMap(); + Map paramMap = new HashMap<>(); String[] pair; for (String item : params) { pair = item.split("="); Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/LearningAction.java =================================================================== diff -u -rb32657226efa9a6bb90a1c12a69e82a5acde2e80 -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/LearningAction.java (.../LearningAction.java) (revision b32657226efa9a6bb90a1c12a69e82a5acde2e80) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/LearningAction.java (.../LearningAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -55,8 +55,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.learning.web.bean.ActivityPositionDTO; import org.lamsfoundation.lams.learning.web.util.LearningWebUtil; import org.lamsfoundation.lams.notebook.model.NotebookEntry; @@ -91,6 +89,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 */ @@ -101,7 +102,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")) { @@ -164,7 +165,7 @@ InvocationTargetException, NoSuchMethodException { // initialize Session Map - SessionMap sessionMap = new SessionMap(); + SessionMap sessionMap = new SessionMap<>(); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); // save toolContentID into HTTPSession @@ -207,7 +208,8 @@ AssessmentResult lastLeaderResult = service.getLastAssessmentResult(assessment.getUid(), groupLeader.getUserId()); - boolean isLastAttemptFinishedByLeader = lastLeaderResult != null && lastLeaderResult.getFinishDate() != null; + boolean isLastAttemptFinishedByLeader = lastLeaderResult != null + && lastLeaderResult.getFinishDate() != null; // forwards to the waitForLeader pages boolean isNonLeader = !user.getUserId().equals(groupLeader.getUserId()); @@ -242,10 +244,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) { @@ -338,7 +340,7 @@ } //sort questions - LinkedList questionDtos = new LinkedList(); + LinkedList questionDtos = new LinkedList<>(); for (QuestionReference questionReference : questionReferences) { AssessmentQuestion question = questionToReferenceMap.get(questionReference.getUid()); @@ -350,20 +352,19 @@ // 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) { 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) { @@ -373,8 +374,8 @@ return AlphanumComparator.compareAlphnumerically(optionString1, optionString2); } }); - questionDto.setMatchingPairOptions(new LinkedHashSet(optionsSortedByOptionString)); - } + questionDto.setMatchingPairOptions(new LinkedHashSet<>(optionsSortedByOptionString)); + } } //paging @@ -389,7 +390,7 @@ questionsForOnePage.add(questionDto); count++; if ((questionsForOnePage.size() == maxQuestionsPerPage) && (count != questionDtos.size())) { - questionsForOnePage = new LinkedHashSet(); + questionsForOnePage = new LinkedHashSet<>(); pagedQuestionDtos.add(questionsForOnePage); } } @@ -422,7 +423,7 @@ * 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); @@ -434,10 +435,10 @@ boolean isTimeLimitExceeded = service.checkTimeLimitExceeded(session.getAssessment(), leader); boolean isLeaderResponseFinalized = service.isLastAttemptFinishedByUser(leader); - 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; } @@ -528,7 +529,7 @@ */ private ActionForward getSecondsLeft(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException, IllegalAccessException, InvocationTargetException, - NoSuchMethodException, JSONException, IOException { + NoSuchMethodException, IOException { IAssessmentService service = getAssessmentService(); String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID); @@ -537,10 +538,10 @@ 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); + response.getWriter().print(responseJSON); return null; } @@ -639,7 +640,6 @@ loadupLastAttempt(sessionMap); } - //redirect to main path to display results ActionRedirect redirect = new ActionRedirect("start.do"); ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE); if (mode != null) { @@ -764,7 +764,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); @@ -775,7 +775,7 @@ } // put back list - optionDtoList = new LinkedHashSet(rList); + optionDtoList = new LinkedHashSet<>(rList); questionDto.setOptionDtos(optionDtoList); } @@ -1268,7 +1268,7 @@ } if (!isOptionAnswersNeverSubmitted) { - TreeSet orderedSet = new TreeSet(new AnswerIntComparator()); + TreeSet orderedSet = new TreeSet<>(new AnswerIntComparator()); orderedSet.addAll(questionDto.getOptionDtos()); questionDto.setOptionDtos(orderedSet); } Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/MonitoringAction.java =================================================================== diff -u -reed8ffff31396b5fd6c63a4c35cbb92767e49359 -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision eed8ffff31396b5fd6c63a4c35cbb92767e49359) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -45,9 +45,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.gradebook.util.GradebookConstants; import org.lamsfoundation.lams.tool.assessment.AssessmentConstants; import org.lamsfoundation.lams.tool.assessment.dto.AssessmentResultDTO; @@ -70,6 +67,7 @@ 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; @@ -78,14 +76,18 @@ import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.util.HtmlUtils; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + 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(); @@ -140,7 +142,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()); @@ -171,7 +173,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()); @@ -184,7 +186,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); @@ -317,7 +319,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); @@ -332,7 +334,7 @@ // 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())); @@ -343,7 +345,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() @@ -362,7 +364,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()) { @@ -395,32 +397,32 @@ 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 = HtmlUtils.htmlEscape(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())); @@ -431,7 +433,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() @@ -451,7 +453,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()) { @@ -492,54 +494,54 @@ 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) { Long questionResultUid = userDto.getQuestionResultUid(); String fullName = HtmlUtils.htmlEscape(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)); // show confidence levels if this feature is turned ON if (assessment.isEnableConfidenceLevels()) { - userData.put(questionResult.getConfidenceLevel()); + userData.add(questionResult.getConfidenceLevel()); } - userData.put(questionResult.getMark()); + userData.add(questionResult.getMark()); if (userDto.getPortraitId() != null) { - userData.put(userDto.getPortraitId()); + userData.add(userDto.getPortraitId()); } } 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())); @@ -550,7 +552,7 @@ * 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(); @@ -572,11 +574,11 @@ } } - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); if (results != null) { - responseJSON.put("data", results); + responseJSON.set("data", JsonUtil.readArray(results)); } else { - responseJSON.put("data", new Float[0]); + responseJSON.set("data", JsonUtil.readArray(new Float[0])); } res.setContentType("application/json;charset=utf-8"); @@ -675,7 +677,7 @@ * Allows displaying correct answers to learners */ private ActionForward discloseCorrectAnswers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException { + HttpServletResponse response) { Long questionUid = WebUtil.readLongParam(request, "questionUid"); Long toolContentId = WebUtil.readLongParam(request, AssessmentConstants.PARAM_TOOL_CONTENT_ID); @@ -698,7 +700,7 @@ * Allows displaying other groups' answers to learners */ private ActionForward discloseGroupsAnswers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException { + HttpServletResponse response) { Long questionUid = WebUtil.readLongParam(request, "questionUid"); Long toolContentId = WebUtil.readLongParam(request, AssessmentConstants.PARAM_TOOL_CONTENT_ID); Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/TblMonitoringAction.java =================================================================== diff -u -r1e25de333185aa272dbfc03ea327ea740a0094ba -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/TblMonitoringAction.java (.../TblMonitoringAction.java) (revision 1e25de333185aa272dbfc03ea327ea740a0094ba) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/TblMonitoringAction.java (.../TblMonitoringAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -16,7 +16,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.JSONException; import org.lamsfoundation.lams.tool.assessment.AssessmentConstants; import org.lamsfoundation.lams.tool.assessment.dto.AssessmentResultDTO; import org.lamsfoundation.lams.tool.assessment.dto.QuestionSummary; @@ -335,7 +334,7 @@ * @throws IOException */ public ActionForward getModalDialogForTeamsTab(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { initAssessmentService(); long toolContentId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); Long userId = WebUtil.readLongParam(request, AttributeNames.PARAM_USER_ID); Index: lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/web/actions/LearningAction.java =================================================================== diff -u -rbe48c7dd8438a3e7f038876851f7a3b740c8f4f4 -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/web/actions/LearningAction.java (.../LearningAction.java) (revision be48c7dd8438a3e7f038876851f7a3b740c8f4f4) +++ lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/web/actions/LearningAction.java (.../LearningAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.forum.web.actions; import java.io.IOException; @@ -45,8 +44,6 @@ import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; -import org.apache.tomcat.util.json.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.events.IEventNotificationService; import org.lamsfoundation.lams.learning.web.bean.ActivityPositionDTO; import org.lamsfoundation.lams.learning.web.util.LearningWebUtil; @@ -83,6 +80,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; + /** * User: conradb Date: 24/06/2005 Time: 10:54:09 */ @@ -179,7 +179,7 @@ if (sessionMapID != null) { sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); } else { - sessionMap = new SessionMap(); + sessionMap = new SessionMap<>(); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); } @@ -234,14 +234,14 @@ sessionMap.put(ForumConstants.ATTR_USER_FINISHED, forumUser.isSessionFinished()); sessionMap.put(ForumConstants.ATTR_ALLOW_EDIT, forum.isAllowEdit()); sessionMap.put(ForumConstants.ATTR_ALLOW_ANONYMOUS, forum.getAllowAnonym()); - + sessionMap.put(ForumConstants.ATTR_ALLOW_UPLOAD, forum.isAllowUpload()); int uploadMaxFileSize = Configuration.getAsInt(ConfigurationKeys.UPLOAD_FILE_MAX_SIZE); // it defaults to -1 if property was not found if (uploadMaxFileSize > 0) { sessionMap.put(ForumConstants.ATTR_UPLOAD_MAX_FILE_SIZE, FileValidatorUtil.formatSize(uploadMaxFileSize)); } - + sessionMap.put(ForumConstants.ATTR_ALLOW_RATE_MESSAGES, forum.isAllowRateMessages()); sessionMap.put(ForumConstants.ATTR_MINIMUM_RATE, forum.getMinimumRate()); sessionMap.put(ForumConstants.ATTR_MAXIMUM_RATE, forum.getMaximumRate()); @@ -509,11 +509,12 @@ // if coming from topic list, the toolSessionId is in the SessionMap. // if coming from the monitoring statistics window, it is passed in as a parameter. Long toolSessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID, true); - if ( toolSessionId != null ) { + if (toolSessionId != null) { sessionMap.put(AttributeNames.PARAM_TOOL_SESSION_ID, toolSessionId); String mode = WebUtil.readStrParam(request, AttributeNames.PARAM_MODE, true); - if ( mode != null ) + if (mode != null) { sessionMap.put(AttributeNames.PARAM_MODE, mode); + } } else { toolSessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID); } @@ -826,9 +827,8 @@ /** * Create a replayed topic for a parent topic. */ - private ActionForward replyTopicInline(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) - throws InterruptedException, JSONException, IOException { + private ActionForward replyTopicInline(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws InterruptedException, IOException { MessageForm messageForm = (MessageForm) form; SessionMap sessionMap = getSessionMap(request, messageForm); @@ -863,24 +863,23 @@ boolean noMorePosts = forum.getMaximumReply() != 0 && numOfPosts >= forum.getMaximumReply() && !forum.isAllowNewTopic() ? Boolean.TRUE : Boolean.FALSE; - JSONObject JSONObject = new JSONObject(); - JSONObject.put(ForumConstants.ATTR_MESS_ID, newMessageSeq.getMessage().getUid()); - JSONObject.put(ForumConstants.ATTR_NO_MORE_POSTS, noMorePosts); - JSONObject.put(ForumConstants.ATTR_NUM_OF_POSTS, numOfPosts); - JSONObject.put(ForumConstants.ATTR_THREAD_ID, newMessageSeq.getThreadMessage().getUid()); - JSONObject.put(ForumConstants.ATTR_SESSION_MAP_ID, messageForm.getSessionMapID()); - JSONObject.put(ForumConstants.ATTR_ROOT_TOPIC_UID, rootTopicId); - JSONObject.put(ForumConstants.ATTR_PARENT_TOPIC_ID, newMessageSeq.getMessage().getParent().getUid()); + ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); + ObjectNode.put(ForumConstants.ATTR_MESS_ID, newMessageSeq.getMessage().getUid()); + ObjectNode.put(ForumConstants.ATTR_NO_MORE_POSTS, noMorePosts); + ObjectNode.put(ForumConstants.ATTR_NUM_OF_POSTS, numOfPosts); + ObjectNode.put(ForumConstants.ATTR_THREAD_ID, newMessageSeq.getThreadMessage().getUid()); + ObjectNode.put(ForumConstants.ATTR_SESSION_MAP_ID, messageForm.getSessionMapID()); + ObjectNode.put(ForumConstants.ATTR_ROOT_TOPIC_UID, rootTopicId); + ObjectNode.put(ForumConstants.ATTR_PARENT_TOPIC_ID, newMessageSeq.getMessage().getParent().getUid()); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); return null; } private void setMonitorMode(SessionMap sessionMap, Message message) { message.setIsMonitor(ToolAccessMode.TEACHER.equals(sessionMap.get(AttributeNames.ATTR_MODE))); } - - + /** * Display a editable form for a special topic in order to update it. * @@ -998,11 +997,11 @@ userId = messagePO.getCreatedBy().getUserId(); loginName = messagePO.getCreatedBy().getLoginName(); } - if ( messagePO.getToolSession() != null && messagePO.getToolSession().getForum() != null ) { + if (messagePO.getToolSession() != null && messagePO.getToolSession().getForum() != null) { toolContentId = messagePO.getToolSession().getForum().getContentId(); } - forumService.getLogEventService().logChangeLearnerContent(userId, loginName, toolContentId, oldMessageString, - messagePO.toString()); + forumService.getLogEventService().logChangeLearnerContent(userId, loginName, toolContentId, + oldMessageString, messagePO.toString()); } // save message into database @@ -1023,7 +1022,7 @@ * @throws IOException */ public ActionForward updateTopicInline(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws PersistenceException, JSONException, IOException { + HttpServletResponse response) throws PersistenceException, IOException { forumService = getForumManager(); @@ -1034,13 +1033,13 @@ doUpdateTopic(request, messageForm, sessionMap, topicId, message); - JSONObject JSONObject = new JSONObject(); - JSONObject.put(ForumConstants.ATTR_MESS_ID, topicId); - JSONObject.put(ForumConstants.ATTR_SESSION_MAP_ID, messageForm.getSessionMapID()); + ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); + ObjectNode.put(ForumConstants.ATTR_MESS_ID, topicId); + ObjectNode.put(ForumConstants.ATTR_SESSION_MAP_ID, messageForm.getSessionMapID()); Long rootTopicId = forumService.getRootTopicId(topicId); - JSONObject.put(ForumConstants.ATTR_ROOT_TOPIC_UID, rootTopicId); + ObjectNode.put(ForumConstants.ATTR_ROOT_TOPIC_UID, rootTopicId); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); return null; } @@ -1100,7 +1099,7 @@ * @return */ public ActionForward rateMessage(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { forumService = getForumManager(); String sessionMapId = WebUtil.readStrParam(request, ForumConstants.ATTR_SESSION_MAP_ID); @@ -1129,13 +1128,13 @@ sessionMap.put(ForumConstants.ATTR_IS_MIN_RATINGS_COMPLETED, isMinRatingsCompleted); sessionMap.put(ForumConstants.ATTR_NUM_OF_RATINGS, numOfRatings); - JSONObject JSONObject = new JSONObject(); - JSONObject.put("averageRating", averageRatingDTO.getRating()); - JSONObject.put("numberOfVotes", averageRatingDTO.getNumberOfVotes()); - JSONObject.put(ForumConstants.ATTR_NO_MORE_RATINGSS, noMoreRatings); - JSONObject.put(ForumConstants.ATTR_NUM_OF_RATINGS, numOfRatings); + ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); + ObjectNode.put("averageRating", averageRatingDTO.getRating()); + ObjectNode.put("numberOfVotes", averageRatingDTO.getNumberOfVotes()); + ObjectNode.put(ForumConstants.ATTR_NO_MORE_RATINGSS, noMoreRatings); + ObjectNode.put(ForumConstants.ATTR_NUM_OF_RATINGS, numOfRatings); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); return null; } Index: lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McService.java =================================================================== diff -u -rb4f6a6c35d72f0cf2d10144f3700f0e29a527edc -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McService.java (.../McService.java) (revision b4f6a6c35d72f0cf2d10144f3700f0e29a527edc) +++ lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McService.java (.../McService.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -51,9 +51,6 @@ import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; 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.ConfidenceLevelDTO; import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler; import org.lamsfoundation.lams.gradebook.service.IGradebookService; @@ -113,6 +110,10 @@ import org.lamsfoundation.lams.web.util.AttributeNames; import org.springframework.dao.DataAccessException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * * The POJO implementation of Mc service. All business logics of MCQ tool are implemented in this class. It translate @@ -1544,7 +1545,7 @@ McContent content = getMcSessionById(toolSessionId).getMcContent(); - //in case McContent is leader aware return all leaders confidences, otherwise - confidences from the users from the same group as requestor + //in case McContent is leader aware return all leaders confidences, otherwise - confidences from the users from the same group as requestor List userAttemptsAndPortraits = content.isUseSelectLeaderToolOuput() ? mcUsrAttemptDAO.getLeadersFinalizedAttemptsByContentId(content.getMcContentId()) : mcUsrAttemptDAO.getFinalizedAttemptsBySessionId(toolSessionId); @@ -1555,7 +1556,7 @@ : ((Number) userAttemptAndPortraitIter[1]).longValue(); Long userId = userAttempt.getQueUsrId(); - //fill in question's and user answer's hashes + //fill in question's and user answer's hashes McQueContent question = userAttempt.getMcQueContent(); String answer = userAttempt.getMcOptionsContent().getMcQueOptionText(); @@ -1832,17 +1833,20 @@ for (McUsrAttempt item : attempts) { Date newDate = item.getAttemptTime(); if (newDate != null) { - if (startDate == null || newDate.before(startDate)) + if (startDate == null || newDate.before(startDate)) { startDate = newDate; - if (endDate == null || newDate.after(endDate)) + } + if (endDate == null || newDate.after(endDate)) { endDate = newDate; + } } } - if (learner.isResponseFinalised()) + if (learner.isResponseFinalised()) { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_COMPLETED, startDate, endDate); - else + } else { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_ATTEMPTED, startDate, null); + } } @Override @@ -1915,16 +1919,15 @@ /** * Rest call to create a new Multiple Choice content. Required fields in toolContentJSON: "title", "instructions", - * "questions". The questions entry should be JSONArray containing JSON objects, which in turn must contain - * "questionText", "displayOrder" (Integer) and a JSONArray "answers". The answers entry should be JSONArray + * "questions". The questions entry should be ArrayNode containing JSON objects, which in turn must contain + * "questionText", "displayOrder" (Integer) and a ArrayNode "answers". The answers entry should be ArrayNode * containing JSON objects, which in turn must contain "answerText", "displayOrder" (Integer), "correct" (Boolean). * * Retries are controlled by lockWhenFinished, which defaults to true (no retries). */ @SuppressWarnings("unchecked") @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { McContent mcq = new McContent(); Date updateDate = new Date(); @@ -1935,40 +1938,40 @@ mcq.setDefineLater(false); mcq.setMcContentId(toolContentID); - mcq.setTitle(toolContentJSON.getString(RestTags.TITLE)); - mcq.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + mcq.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + mcq.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); - mcq.setRetries(JsonUtil.opt(toolContentJSON, "allowRetries", Boolean.FALSE)); + mcq.setRetries(JsonUtil.optBoolean(toolContentJSON, "allowRetries", Boolean.FALSE)); mcq.setUseSelectLeaderToolOuput( - JsonUtil.opt(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); - mcq.setReflect(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - mcq.setReflectionSubject(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, "")); - mcq.setQuestionsSequenced(JsonUtil.opt(toolContentJSON, "questionsSequenced", Boolean.FALSE)); - mcq.setRandomize(JsonUtil.opt(toolContentJSON, "randomize", Boolean.FALSE)); - mcq.setShowReport(JsonUtil.opt(toolContentJSON, "showReport", Boolean.FALSE)); - mcq.setDisplayAnswers(JsonUtil.opt(toolContentJSON, "displayAnswers", Boolean.FALSE)); - mcq.setDisplayFeedbackOnly(JsonUtil.opt(toolContentJSON, "displayFeedbackOnly", Boolean.FALSE)); - mcq.setShowMarks(JsonUtil.opt(toolContentJSON, "showMarks", Boolean.FALSE)); - mcq.setPrefixAnswersWithLetters(JsonUtil.opt(toolContentJSON, "prefixAnswersWithLetters", Boolean.TRUE)); - mcq.setPassMark(JsonUtil.opt(toolContentJSON, "passMark", 0)); - mcq.setEnableConfidenceLevels(JsonUtil.opt(toolContentJSON, "enableConfidenceLevels", Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); + mcq.setReflect(JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + mcq.setReflectionSubject(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, "")); + mcq.setQuestionsSequenced(JsonUtil.optBoolean(toolContentJSON, "questionsSequenced", Boolean.FALSE)); + mcq.setRandomize(JsonUtil.optBoolean(toolContentJSON, "randomize", Boolean.FALSE)); + mcq.setShowReport(JsonUtil.optBoolean(toolContentJSON, "showReport", Boolean.FALSE)); + mcq.setDisplayAnswers(JsonUtil.optBoolean(toolContentJSON, "displayAnswers", Boolean.FALSE)); + mcq.setDisplayFeedbackOnly(JsonUtil.optBoolean(toolContentJSON, "displayFeedbackOnly", Boolean.FALSE)); + mcq.setShowMarks(JsonUtil.optBoolean(toolContentJSON, "showMarks", Boolean.FALSE)); + mcq.setPrefixAnswersWithLetters(JsonUtil.optBoolean(toolContentJSON, "prefixAnswersWithLetters", Boolean.TRUE)); + mcq.setPassMark(JsonUtil.optInt(toolContentJSON, "passMark", 0)); + mcq.setEnableConfidenceLevels(JsonUtil.optBoolean(toolContentJSON, "enableConfidenceLevels", Boolean.FALSE)); // submissionDeadline is set in monitoring createMc(mcq); // Questions - JSONArray questions = toolContentJSON.getJSONArray(RestTags.QUESTIONS); - for (int i = 0; i < questions.length(); i++) { - JSONObject questionData = (JSONObject) questions.get(i); - String questionText = questionData.getString(RestTags.QUESTION_TEXT); - McQueContent question = new McQueContent(questionText, null, questionData.getInt(RestTags.DISPLAY_ORDER), 1, - "", mcq, null, new HashSet()); + ArrayNode questions = JsonUtil.optArray(toolContentJSON, RestTags.QUESTIONS); + for (JsonNode questionData : questions) { + McQueContent question = new McQueContent(JsonUtil.optString(questionData, RestTags.QUESTION_TEXT), null, + JsonUtil.optInt(questionData, RestTags.DISPLAY_ORDER), 1, "", mcq, null, + new HashSet()); - JSONArray optionsData = questionData.getJSONArray(RestTags.ANSWERS); - for (int j = 0; j < optionsData.length(); j++) { - JSONObject optionData = (JSONObject) optionsData.get(j); - question.getMcOptionsContents().add(new McOptsContent(optionData.getInt(RestTags.DISPLAY_ORDER), - optionData.getBoolean(RestTags.CORRECT), optionData.getString(RestTags.ANSWER_TEXT), question)); + ArrayNode optionsData = JsonUtil.optArray(questionData, RestTags.ANSWERS); + for (JsonNode optionData : optionsData) { + question.getMcOptionsContents() + .add(new McOptsContent(JsonUtil.optInt(optionData, RestTags.DISPLAY_ORDER), + JsonUtil.optBoolean(optionData, RestTags.CORRECT), + JsonUtil.optString(optionData, RestTags.ANSWER_TEXT), question)); } saveOrUpdateMcQueContent(question); } Index: lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/web/action/McLearningAction.java =================================================================== diff -u -rb4f6a6c35d72f0cf2d10144f3700f0e29a527edc -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/web/action/McLearningAction.java (.../McLearningAction.java) (revision b4f6a6c35d72f0cf2d10144f3700f0e29a527edc) +++ lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/web/action/McLearningAction.java (.../McLearningAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -40,8 +40,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.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.learning.web.util.LearningWebUtil; import org.lamsfoundation.lams.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; @@ -68,6 +66,9 @@ import org.lamsfoundation.lams.web.util.AttributeNames; import org.lamsfoundation.lams.web.util.SessionMap; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Ozgur Demirtas */ @@ -260,13 +261,14 @@ String httpSessionID = mcLearningForm.getHttpSessionID(); SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(httpSessionID); request.getSession().setAttribute(httpSessionID, sessionMap); - + String toolSessionID = request.getParameter(AttributeNames.PARAM_TOOL_SESSION_ID); McSession session = mcService.getMcSessionById(new Long(toolSessionID)); String toolContentId = session.getMcContent().getMcContentId().toString(); McContent mcContent = mcService.getMcContent(new Long(toolContentId)); - List answers = McLearningAction.parseLearnerAnswers(mcLearningForm, request, mcContent.isQuestionsSequenced()); + List answers = McLearningAction.parseLearnerAnswers(mcLearningForm, request, + mcContent.isQuestionsSequenced()); if (mcContent.isQuestionsSequenced()) { sessionMap.put(McAppConstants.QUESTION_AND_CANDIDATE_ANSWERS_KEY, answers); } @@ -283,7 +285,7 @@ /* process the answers */ List answerDtos = buildAnswerDtos(answers, mcContent, request); mcService.saveUserAttempt(user, answerDtos); - + //calculate total learner mark int learnerMark = 0; for (AnswerDTO answerDto : answerDtos) { @@ -330,13 +332,14 @@ } //parse learner input - List answers = McLearningAction.parseLearnerAnswers(mcLearningForm, request, mcContent.isQuestionsSequenced()); + List answers = McLearningAction.parseLearnerAnswers(mcLearningForm, request, + mcContent.isQuestionsSequenced()); sessionMap.put(McAppConstants.QUESTION_AND_CANDIDATE_ANSWERS_KEY, answers); //save user attempt List answerDtos = buildAnswerDtos(answers, mcContent, request); mcService.saveUserAttempt(user, answerDtos); - + List learnerAnswersDTOList = mcService.getAnswersFromDatabase(mcContent, user); request.setAttribute(McAppConstants.LEARNER_ANSWERS_DTO_LIST, learnerAnswersDTOList); @@ -389,7 +392,7 @@ String toolContentId = mcSession.getMcContent().getMcContentId().toString(); McContent mcContent = mcService.getMcContent(new Long(toolContentId)); - + String sessionMapID = mcLearningForm.getHttpSessionID(); request.setAttribute("sessionMapID", sessionMapID); @@ -493,15 +496,17 @@ mcGeneralLearnerFlowDTO.setDisplayAnswers(new Boolean(mcContent.isDisplayAnswers()).toString()); mcGeneralLearnerFlowDTO.setDisplayFeedbackOnly(((Boolean)mcContent.isDisplayFeedbackOnly()).toString()); mcGeneralLearnerFlowDTO.setLearnerMark(user.getLastAttemptTotalMark()); - + Object[] markStatistics = null; if (mcContent.isShowMarks()) { markStatistics = mcService.getMarkStatistics(mcSession); } if (markStatistics != null) { - mcGeneralLearnerFlowDTO.setLowestMark(markStatistics[0] != null ? ((Float)markStatistics[0]).intValue() : 0); - mcGeneralLearnerFlowDTO.setAverageMark(markStatistics[1] != null ? ((Float)markStatistics[1]).intValue() : 0); - mcGeneralLearnerFlowDTO.setTopMark(markStatistics[2] != null ? ((Float)markStatistics[2]).intValue() : 0); + mcGeneralLearnerFlowDTO + .setLowestMark(markStatistics[0] != null ? ((Float) markStatistics[0]).intValue() : 0); + mcGeneralLearnerFlowDTO + .setAverageMark(markStatistics[1] != null ? ((Float) markStatistics[1]).intValue() : 0); + mcGeneralLearnerFlowDTO.setTopMark(markStatistics[2] != null ? ((Float) markStatistics[2]).intValue() : 0); } else { mcGeneralLearnerFlowDTO.setLowestMark(0); mcGeneralLearnerFlowDTO.setAverageMark(0); @@ -574,7 +579,7 @@ * checks Leader Progress */ public ActionForward checkLeaderProgress(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { if (mcService == null) { mcService = McServiceProxy.getMcService(getServlet().getServletContext()); @@ -586,10 +591,10 @@ boolean isLeaderResponseFinalized = leader.isResponseFinalised(); - JSONObject JSONObject = new JSONObject(); - JSONObject.put("isLeaderResponseFinalized", isLeaderResponseFinalized); + ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); + ObjectNode.put("isLeaderResponseFinalized", isLeaderResponseFinalized); response.setContentType("application/x-json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); return null; } @@ -708,15 +713,17 @@ return null; } - List answers = McLearningAction.parseLearnerAnswers(mcLearningForm, request, mcContent.isQuestionsSequenced()); + List answers = McLearningAction.parseLearnerAnswers(mcLearningForm, request, + mcContent.isQuestionsSequenced()); List answerDtos = buildAnswerDtos(answers, mcContent, request); mcService.saveUserAttempt(user, answerDtos); return null; } - private static List parseLearnerAnswers(McLearningForm mcLearningForm, HttpServletRequest request, boolean isQuestionsSequenced) { + private static List parseLearnerAnswers(McLearningForm mcLearningForm, HttpServletRequest request, + boolean isQuestionsSequenced) { String httpSessionID = mcLearningForm.getHttpSessionID(); SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(httpSessionID); Index: lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/web/action/McMonitoringAction.java =================================================================== diff -u -rb4f6a6c35d72f0cf2d10144f3700f0e29a527edc -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/web/action/McMonitoringAction.java (.../McMonitoringAction.java) (revision b4f6a6c35d72f0cf2d10144f3700f0e29a527edc) +++ lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/web/action/McMonitoringAction.java (.../McMonitoringAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -37,14 +37,10 @@ import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; -import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionRedirect; -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.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.tool.exception.ToolException; @@ -62,19 +58,22 @@ import org.lamsfoundation.lams.tool.mc.service.IMcService; import org.lamsfoundation.lams.tool.mc.service.McServiceProxy; import org.lamsfoundation.lams.util.DateUtil; +import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.web.action.LamsDispatchAction; import org.lamsfoundation.lams.web.session.SessionManager; import org.lamsfoundation.lams.web.util.AttributeNames; import org.springframework.web.util.HtmlUtils; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * * @author Ozgur Demirtas */ public class McMonitoringAction extends LamsDispatchAction { - private static Logger logger = Logger.getLogger(McMonitoringAction.class.getName()); - /** * Turn on displayAnswers */ @@ -83,7 +82,7 @@ IMcService mcService = McServiceProxy.getMcService(getServlet().getServletContext()); String strToolContentID = request.getParameter(AttributeNames.PARAM_TOOL_CONTENT_ID); String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); - + McContent mcContent = mcService.getMcContent(new Long(strToolContentID)); mcContent.setDisplayAnswers(new Boolean(true)); mcContent.setDisplayFeedbackOnly(new Boolean(false)); @@ -108,7 +107,7 @@ McContent mcContent = mcService.getMcContent(new Long(strToolContentID)); mcContent.setDisplayFeedbackOnly(new Boolean(true)); mcService.updateMc(mcContent); - + // use redirect to prevent resubmition of the same request ActionRedirect redirect = new ActionRedirect(mapping.findForwardConfig("monitoringStarterRedirect")); redirect.addParameter(McAppConstants.TOOL_CONTENT_ID, strToolContentID); @@ -195,7 +194,8 @@ /** * Set Submission Deadline - * @throws IOException + * + * @throws IOException */ public ActionForward setSubmissionDeadline(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -236,14 +236,14 @@ * @throws IOException */ public ActionForward setActivityEvaluation(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { IMcService service = McServiceProxy.getMcService(getServlet().getServletContext()); Long contentID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); String activityEvaluation = WebUtil.readStrParam(request, McAppConstants.ATTR_ACTIVITY_EVALUATION); service.setActivityEvaluation(contentID, 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())); @@ -293,7 +293,7 @@ * Return paged users for jqGrid. */ public ActionForward getPagedUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { IMcService mcService = McServiceProxy.getMcService(getServlet().getServletContext()); Long sessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); @@ -337,38 +337,38 @@ int totalPages = new Double( Math.ceil(new Integer(countVisitLogs).doubleValue() / new Integer(rowLimit).doubleValue())).intValue(); - JSONArray rows = new JSONArray(); + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); int i = 1; for (McUserMarkDTO userDto : userDtos) { - JSONArray visitLogData = new JSONArray(); + ArrayNode visitLogData = JsonNodeFactory.instance.arrayNode(); Long userUid = Long.parseLong(userDto.getQueUsrId()); - visitLogData.put(userUid); - visitLogData.put(userDto.getUserId()); + visitLogData.add(userUid); + visitLogData.add(userDto.getUserId()); String fullName = HtmlUtils.htmlEscape(userDto.getFullName()); if (groupLeader != null && groupLeader.getUid().equals(userUid)) { fullName += " (" + mcService.getLocalizedMessage("label.monitoring.group.leader") + ")"; } - visitLogData.put(fullName); + visitLogData.add(fullName); Long totalMark = (userDto.getTotalMark() == null) ? 0 : userDto.getTotalMark(); - visitLogData.put(totalMark); + visitLogData.add(totalMark); + + visitLogData.add(userDto.getPortraitId()); - visitLogData.put(userDto.getPortraitId()); - - JSONObject userRow = new JSONObject(); + ObjectNode userRow = JsonNodeFactory.instance.objectNode(); userRow.put("id", i++); - userRow.put("cell", visitLogData); + userRow.set("cell", visitLogData); - 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", countVisitLogs); - responseJSON.put("rows", rows); + responseJSON.set("rows", rows); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(responseJSON.toString()); @@ -389,48 +389,49 @@ return null; } - + /** * Get the mark summary with data arranged in bands. Can be displayed graphically or in a table. */ public ActionForward getMarkChartData(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse res) throws IOException, ServletException, JSONException { + HttpServletResponse res) throws IOException, ServletException { IMcService mcService = McServiceProxy.getMcService(getServlet().getServletContext()); Long contentID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); McContent mcContent = mcService.getMcContent(contentID); List results = null; - - if ( mcContent != null ) { - if ( mcContent.isUseSelectLeaderToolOuput() ) { + + if (mcContent != null) { + if (mcContent.isUseSelectLeaderToolOuput()) { results = mcService.getMarksArrayForLeaders(contentID); } else { Long sessionID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); results = mcService.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; } - + public ActionForward statistic(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { IMcService mcService = McServiceProxy.getMcService(getServlet().getServletContext()); Long contentID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); request.setAttribute(AttributeNames.PARAM_TOOL_CONTENT_ID, contentID); McContent mcContent = mcService.getMcContent(contentID); - if ( mcContent != null ) { - if ( mcContent.isUseSelectLeaderToolOuput() ) { + if (mcContent != null) { + if (mcContent.isUseSelectLeaderToolOuput()) { LeaderResultsDTO leaderDto = mcService.getLeaderResultsDTOForLeaders(contentID); request.setAttribute("leaderDto", leaderDto); } else { @@ -439,7 +440,7 @@ } request.setAttribute("useSelectLeaderToolOutput", mcContent.isUseSelectLeaderToolOuput()); } - + // prepare toolOutputDefinitions and activityEvaluation List toolOutputDefinitions = new ArrayList(); toolOutputDefinitions.add(McAppConstants.OUTPUT_NAME_LEARNER_MARK); @@ -451,5 +452,4 @@ return mapping.findForward(McAppConstants.STATISTICS); } - } Index: lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/actions/MonitoringAction.java =================================================================== diff -u -r8b96d871bf93fc27f6f6d086977dc8c95d5e7f90 -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/actions/MonitoringAction.java (.../MonitoringAction.java) (revision 8b96d871bf93fc27f6f6d086977dc8c95d5e7f90) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/actions/MonitoringAction.java (.../MonitoringAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.notebook.web.actions; import java.io.IOException; @@ -34,13 +33,9 @@ import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; -import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; -import org.apache.tomcat.util.json.JSONArray; -import org.apache.tomcat.util.json.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.tool.notebook.dto.NotebookSessionsDTO; import org.lamsfoundation.lams.tool.notebook.model.Notebook; import org.lamsfoundation.lams.tool.notebook.model.NotebookUser; @@ -58,16 +53,11 @@ import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.util.HtmlUtils; -/** - * - * - * - * - * - */ -public class MonitoringAction extends LamsDispatchAction { +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; - private static Logger log = Logger.getLogger(MonitoringAction.class); +public class MonitoringAction extends LamsDispatchAction { private static String noEntryText = null; // access via getNoEntryText() public INotebookService notebookService; @@ -102,14 +92,15 @@ TimeZone teacherTimeZone = teacher.getTimeZone(); Date tzSubmissionDeadline = DateUtil.convertToTimeZoneFromDefault(teacherTimeZone, submissionDeadline); request.setAttribute(NotebookConstants.ATTR_SUBMISSION_DEADLINE, tzSubmissionDeadline.getTime()); - request.setAttribute(NotebookConstants.ATTR_SUBMISSION_DEADLINE_DATESTRING, DateUtil.convertToStringForJSON(submissionDeadline, request.getLocale())); + request.setAttribute(NotebookConstants.ATTR_SUBMISSION_DEADLINE_DATESTRING, + DateUtil.convertToStringForJSON(submissionDeadline, request.getLocale())); } return mapping.findForward("success"); } public ActionForward getUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { setupService(); Long toolSessionId = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID)); @@ -134,13 +125,13 @@ } } - JSONObject responsedata = new JSONObject(); + ObjectNode responsedata = JsonNodeFactory.instance.objectNode(); int totalRows = notebookService.getCountUsersBySession(toolSessionId, searchString); responsedata.put("total_rows", totalRows); responsedata.put("page", page); responsedata.put("total", Math.ceil((float) totalRows / size)); - JSONArray rows = new JSONArray(); + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); // our code expects the first page to be 0 but jqgrid uses 1 for the first page. List users = notebookService.getUsersForTablesorter(toolSessionId, page > 0 ? page - 1 : 0, size, sorting, searchString); @@ -150,7 +141,7 @@ int id = 1; for (Object[] userAndReflection : users) { - JSONObject responseRow = new JSONObject(); + ObjectNode responseRow = JsonNodeFactory.instance.objectNode(); NotebookUser user = (NotebookUser) userAndReflection[0]; responseRow.put("id", id++); @@ -169,19 +160,19 @@ Date modifiedDate = (Date) userAndReflection[2]; responseRow.put(NotebookConstants.PARAM_MODIFIED_DATE, DateUtil.convertToStringForJSON(modifiedDate, request.getLocale())); - responseRow.put(NotebookConstants.PARAM_MODIFIED_DATE_TIMEAGO, + responseRow.put(NotebookConstants.PARAM_MODIFIED_DATE_TIMEAGO, DateUtil.convertToStringForTimeagoJSON(modifiedDate)); } else { responseRow.put(NotebookConstants.PARAM_MODIFIED_DATE, noEntry); } - + responseRow.put(NotebookConstants.ATTR_USER_ID, user.getUserId()); if (userAndReflection.length > 3 && userAndReflection[3] != null) { - responseRow.put(NotebookConstants.ATTR_PORTRAIT_ID, userAndReflection[3]); + responseRow.put(NotebookConstants.ATTR_PORTRAIT_ID, (String) userAndReflection[3]); } - rows.put(responseRow); + rows.add(responseRow); } - responsedata.put("rows", rows); + responsedata.set("rows", rows); response.setContentType("application/json;charset=utf-8"); response.getWriter().print(responsedata.toString()); return null; @@ -230,7 +221,7 @@ * @param request * @param response * @return - * @throws IOException + * @throws IOException */ public ActionForward setSubmissionDeadline(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { Index: lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/web/action/MonitoringAction.java =================================================================== diff -u -r0138aabe01dc8f301e7c727bd39e97424b4fa38a -r920d578377db9f50585f754c68a25e72da1d2c2f --- lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision 0138aabe01dc8f301e7c727bd39e97424b4fa38a) +++ lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision 920d578377db9f50585f754c68a25e72da1d2c2f) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.survey.web.action; import java.io.IOException; @@ -53,9 +52,6 @@ import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; -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.tool.survey.SurveyConstants; import org.lamsfoundation.lams.tool.survey.dto.AnswerDTO; import org.lamsfoundation.lams.tool.survey.model.Survey; @@ -67,6 +63,7 @@ import org.lamsfoundation.lams.tool.survey.util.SurveyWebUtils; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; import org.lamsfoundation.lams.util.DateUtil; +import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.web.session.SessionManager; @@ -76,6 +73,10 @@ import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.util.HtmlUtils; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + public class MonitoringAction extends Action { public ISurveyService surveyService; @@ -91,7 +92,7 @@ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException { + HttpServletResponse response) throws IOException, ServletException { String param = mapping.getParameter(); if (param.equals("summary")) { @@ -125,7 +126,7 @@ /** * Summary page action. - * + * * @param mapping * @param form * @param request @@ -180,7 +181,8 @@ MonitoringAction.log.info("Time:" + tzSubmissionDeadline.getTime()); // store submission deadline to sessionMap sessionMap.put(SurveyConstants.ATTR_SUBMISSION_DEADLINE, tzSubmissionDeadline.getTime()); - sessionMap.put(SurveyConstants.ATTR_SUBMISSION_DEADLINE_DATESTRING, DateUtil.convertToStringForJSON(submissionDeadline, request.getLocale())); + sessionMap.put(SurveyConstants.ATTR_SUBMISSION_DEADLINE_DATESTRING, + DateUtil.convertToStringForJSON(submissionDeadline, request.getLocale())); } return mapping.findForward(SurveyConstants.SUCCESS); @@ -200,7 +202,7 @@ } private ActionForward getAnswersJSON(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { Long sessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); Long questionUid = WebUtil.readLongParam(request, SurveyConstants.ATTR_QUESTION_UID); @@ -222,21 +224,22 @@ List users = service.getQuestionAnswersForTablesorter(sessionId, questionUid, page, size, sorting, searchString); - JSONArray rows = new JSONArray(); - JSONObject responsedata = new JSONObject(); + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); + ObjectNode responsedata = JsonNodeFactory.instance.objectNode(); responsedata.put("total_rows", service.getCountUsersBySession(sessionId, searchString)); for (Object[] userAndAnswers : users) { - JSONObject responseRow = new JSONObject(); + ObjectNode responseRow = JsonNodeFactory.instance.objectNode(); SurveyUser user = (SurveyUser) userAndAnswers[0]; responseRow.put(SurveyConstants.ATTR_USER_NAME, HtmlUtils.htmlEscape(user.getLastName() + " " + user.getFirstName())); responseRow.put(SurveyConstants.ATTR_USER_ID, user.getUserId()); if (userAndAnswers.length > 1 && userAndAnswers[1] != null) { - responseRow.put("choices", SurveyWebUtils.getChoiceList((String) userAndAnswers[1])); + responseRow.put("choices", + JsonUtil.readArray(SurveyWebUtils.getChoiceList((String) userAndAnswers[1]))); } if (userAndAnswers.length > 2 && userAndAnswers[2] != null) { // Data is handled differently in learner depending on whether @@ -257,11 +260,11 @@ responseRow.put("answerText", answer); } if (userAndAnswers.length > 3 && userAndAnswers[3] != null) { - responseRow.put(SurveyConstants.ATTR_PORTRAIT_ID, ((Number)userAndAnswers[3]).longValue()); + responseRow.put(SurveyConstants.ATTR_PORTRAIT_ID, ((Number) userAndAnswers[3]).longValue()); } - rows.put(responseRow); + rows.add(responseRow); } - responsedata.put("rows", rows); + responsedata.set("rows", rows); response.setContentType("application/json;charset=utf-8"); response.getWriter().print(new String(responsedata.toString())); return null; @@ -280,7 +283,7 @@ } private ActionForward getReflectionsJSON(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { Long sessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); @@ -299,39 +302,39 @@ ISurveyService service = getSurveyService(); List users = service.getUserReflectionsForTablesorter(sessionId, page, size, sorting, searchString); - JSONArray rows = new JSONArray(); - JSONObject responsedata = new JSONObject(); + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); + ObjectNode responsedata = JsonNodeFactory.instance.objectNode(); responsedata.put("total_rows", service.getCountUsersBySession(sessionId, searchString)); for (Object[] userAndReflection : users) { - JSONObject responseRow = new JSONObject(); + ObjectNode responseRow = JsonNodeFactory.instance.objectNode(); SurveyUser user = (SurveyUser) userAndReflection[0]; responseRow.put(SurveyConstants.ATTR_USER_NAME, HtmlUtils.htmlEscape(user.getLastName() + " " + user.getFirstName())); responseRow.put(SurveyConstants.ATTR_USER_ID, user.getUserId()); - + if (userAndReflection.length > 1 && userAndReflection[1] != null) { String reflection = HtmlUtils.htmlEscape((String) userAndReflection[1]); responseRow.put(SurveyConstants.ATTR_REFLECTION, reflection.replaceAll("\n", "
")); } if (userAndReflection.length > 2 && userAndReflection[2] != null) { - responseRow.put(SurveyConstants.ATTR_PORTRAIT_ID, ((Number)userAndReflection[2]).longValue()); + responseRow.put(SurveyConstants.ATTR_PORTRAIT_ID, ((Number) userAndReflection[2]).longValue()); } - rows.put(responseRow); + rows.add(responseRow); } - responsedata.put("rows", rows); + responsedata.set("rows", rows); response.setContentType("application/json;charset=utf-8"); response.getWriter().print(new String(responsedata.toString())); return null; } /** * Export Excel format survey data. - * + * * @param mapping * @param form * @param request @@ -351,11 +354,11 @@ try { // create an empty excel file Workbook workbook = new SXSSFWorkbook(); - + // Date format for the timestamp field CellStyle dateStyle = workbook.createCellStyle(); - dateStyle.setDataFormat((short)0x16); // long date/time format e.g. DD/MM/YYYY MM:HH - + dateStyle.setDataFormat((short) 0x16); // long date/time format e.g. DD/MM/YYYY MM:HH + Sheet sheet = workbook.createSheet("Survey"); sheet.setColumnWidth(0, 5000); Row row; @@ -481,7 +484,7 @@ cellIdx++; cell = row.createCell(cellIdx); cell.setCellStyle(dateStyle); - cell.setCellValue(answer.getAnswer().getUpdateDate()); + cell.setCellValue(answer.getAnswer().getUpdateDate()); // for answer's options for (SurveyOption option : options) { cellIdx++; @@ -540,13 +543,13 @@ /** * Set Submission Deadline - * + * * @param mapping * @param form * @param request * @param response * @return - * @throws IOException + * @throws IOException */ public ActionForward setSubmissionDeadline(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException {